Update .bashrc
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-tsserver / 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19     if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20         if (ar || !(i in from)) {
21             if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22             ar[i] = from[i];
23         }
24     }
25     return to.concat(ar || Array.prototype.slice.call(from));
26 };
27 var __assign = (this && this.__assign) || function () {
28     __assign = Object.assign || function(t) {
29         for (var s, i = 1, n = arguments.length; i < n; i++) {
30             s = arguments[i];
31             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
32                 t[p] = s[p];
33         }
34         return t;
35     };
36     return __assign.apply(this, arguments);
37 };
38 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
39     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
40     return cooked;
41 };
42 var __generator = (this && this.__generator) || function (thisArg, body) {
43     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
44     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
45     function verb(n) { return function (v) { return step([n, v]); }; }
46     function step(op) {
47         if (f) throw new TypeError("Generator is already executing.");
48         while (_) try {
49             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;
50             if (y = 0, t) op = [op[0] & 2, t.value];
51             switch (op[0]) {
52                 case 0: case 1: t = op; break;
53                 case 4: _.label++; return { value: op[1], done: false };
54                 case 5: _.label++; y = op[1]; op = [0]; continue;
55                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
56                 default:
57                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
58                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
59                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
60                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
61                     if (t[2]) _.ops.pop();
62                     _.trys.pop(); continue;
63             }
64             op = body.call(thisArg, _);
65         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
66         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
67     }
68 };
69 var __extends = (this && this.__extends) || (function () {
70     var extendStatics = function (d, b) {
71         extendStatics = Object.setPrototypeOf ||
72             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
73             function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
74         return extendStatics(d, b);
75     };
76     return function (d, b) {
77         if (typeof b !== "function" && b !== null)
78             throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
79         extendStatics(d, b);
80         function __() { this.constructor = d; }
81         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
82     };
83 })();
84 var ts;
85 (function (ts) {
86     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
87     // If changing the text in this section, be sure to test `configurePrerelease` too.
88     ts.versionMajorMinor = "4.5";
89     // The following is baselined as a literal template type without intervention
90     /** The version of the TypeScript compiler release */
91     // eslint-disable-next-line @typescript-eslint/no-inferrable-types
92     ts.version = "4.5.2";
93     /* @internal */
94     var Comparison;
95     (function (Comparison) {
96         Comparison[Comparison["LessThan"] = -1] = "LessThan";
97         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
98         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
99     })(Comparison = ts.Comparison || (ts.Comparison = {}));
100     /* @internal */
101     var NativeCollections;
102     (function (NativeCollections) {
103         /**
104          * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
105          */
106         function tryGetNativeMap() {
107             // Internet Explorer's Map doesn't support iteration, so don't use it.
108             // eslint-disable-next-line no-in-operator
109             return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
110         }
111         NativeCollections.tryGetNativeMap = tryGetNativeMap;
112         /**
113          * Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
114          */
115         function tryGetNativeSet() {
116             // Internet Explorer's Set doesn't support iteration, so don't use it.
117             // eslint-disable-next-line no-in-operator
118             return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
119         }
120         NativeCollections.tryGetNativeSet = tryGetNativeSet;
121     })(NativeCollections || (NativeCollections = {}));
122     /* @internal */
123     ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
124     /* @internal */
125     ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
126     /* @internal */
127     function getCollectionImplementation(name, nativeFactory, shimFactory) {
128         var _a;
129         // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
130         var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator);
131         if (constructor)
132             return constructor;
133         throw new Error("TypeScript requires an environment that provides a compatible native ".concat(name, " implementation."));
134     }
135 })(ts || (ts = {}));
136 /* @internal */
137 var ts;
138 (function (ts) {
139     function getIterator(iterable) {
140         if (iterable) {
141             if (isArray(iterable))
142                 return arrayIterator(iterable);
143             if (iterable instanceof ts.Map)
144                 return iterable.entries();
145             if (iterable instanceof ts.Set)
146                 return iterable.values();
147             throw new Error("Iteration not supported.");
148         }
149     }
150     ts.getIterator = getIterator;
151     ts.emptyArray = [];
152     ts.emptyMap = new ts.Map();
153     ts.emptySet = new ts.Set();
154     function createMap() {
155         return new ts.Map();
156     }
157     ts.createMap = createMap;
158     /**
159      * Create a new map from a template object is provided, the map will copy entries from it.
160      * @deprecated Use `new Map(getEntries(template))` instead.
161      */
162     function createMapFromTemplate(template) {
163         var map = new ts.Map();
164         // Copies keys/values from template. Note that for..in will not throw if
165         // template is undefined, and instead will just exit the loop.
166         for (var key in template) {
167             if (hasOwnProperty.call(template, key)) {
168                 map.set(key, template[key]);
169             }
170         }
171         return map;
172     }
173     ts.createMapFromTemplate = createMapFromTemplate;
174     function length(array) {
175         return array ? array.length : 0;
176     }
177     ts.length = length;
178     /**
179      * Iterates through 'array' by index and performs the callback on each element of array until the callback
180      * returns a truthy value, then returns that value.
181      * If no such value is found, the callback is applied to each element of array and undefined is returned.
182      */
183     function forEach(array, callback) {
184         if (array) {
185             for (var i = 0; i < array.length; i++) {
186                 var result = callback(array[i], i);
187                 if (result) {
188                     return result;
189                 }
190             }
191         }
192         return undefined;
193     }
194     ts.forEach = forEach;
195     /**
196      * Like `forEach`, but iterates in reverse order.
197      */
198     function forEachRight(array, callback) {
199         if (array) {
200             for (var i = array.length - 1; i >= 0; i--) {
201                 var result = callback(array[i], i);
202                 if (result) {
203                     return result;
204                 }
205             }
206         }
207         return undefined;
208     }
209     ts.forEachRight = forEachRight;
210     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
211     function firstDefined(array, callback) {
212         if (array === undefined) {
213             return undefined;
214         }
215         for (var i = 0; i < array.length; i++) {
216             var result = callback(array[i], i);
217             if (result !== undefined) {
218                 return result;
219             }
220         }
221         return undefined;
222     }
223     ts.firstDefined = firstDefined;
224     function firstDefinedIterator(iter, callback) {
225         while (true) {
226             var iterResult = iter.next();
227             if (iterResult.done) {
228                 return undefined;
229             }
230             var result = callback(iterResult.value);
231             if (result !== undefined) {
232                 return result;
233             }
234         }
235     }
236     ts.firstDefinedIterator = firstDefinedIterator;
237     function reduceLeftIterator(iterator, f, initial) {
238         var result = initial;
239         if (iterator) {
240             for (var step = iterator.next(), pos = 0; !step.done; step = iterator.next(), pos++) {
241                 result = f(result, step.value, pos);
242             }
243         }
244         return result;
245     }
246     ts.reduceLeftIterator = reduceLeftIterator;
247     function zipWith(arrayA, arrayB, callback) {
248         var result = [];
249         ts.Debug.assertEqual(arrayA.length, arrayB.length);
250         for (var i = 0; i < arrayA.length; i++) {
251             result.push(callback(arrayA[i], arrayB[i], i));
252         }
253         return result;
254     }
255     ts.zipWith = zipWith;
256     function zipToIterator(arrayA, arrayB) {
257         ts.Debug.assertEqual(arrayA.length, arrayB.length);
258         var i = 0;
259         return {
260             next: function () {
261                 if (i === arrayA.length) {
262                     return { value: undefined, done: true };
263                 }
264                 i++;
265                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
266             }
267         };
268     }
269     ts.zipToIterator = zipToIterator;
270     function zipToMap(keys, values) {
271         ts.Debug.assert(keys.length === values.length);
272         var map = new ts.Map();
273         for (var i = 0; i < keys.length; ++i) {
274             map.set(keys[i], values[i]);
275         }
276         return map;
277     }
278     ts.zipToMap = zipToMap;
279     /**
280      * Creates a new array with `element` interspersed in between each element of `input`
281      * if there is more than 1 value in `input`. Otherwise, returns the existing array.
282      */
283     function intersperse(input, element) {
284         if (input.length <= 1) {
285             return input;
286         }
287         var result = [];
288         for (var i = 0, n = input.length; i < n; i++) {
289             if (i)
290                 result.push(element);
291             result.push(input[i]);
292         }
293         return result;
294     }
295     ts.intersperse = intersperse;
296     /**
297      * Iterates through `array` by index and performs the callback on each element of array until the callback
298      * returns a falsey value, then returns false.
299      * If no such value is found, the callback is applied to each element of array and `true` is returned.
300      */
301     function every(array, callback) {
302         if (array) {
303             for (var i = 0; i < array.length; i++) {
304                 if (!callback(array[i], i)) {
305                     return false;
306                 }
307             }
308         }
309         return true;
310     }
311     ts.every = every;
312     function find(array, predicate) {
313         for (var i = 0; i < array.length; i++) {
314             var value = array[i];
315             if (predicate(value, i)) {
316                 return value;
317             }
318         }
319         return undefined;
320     }
321     ts.find = find;
322     function findLast(array, predicate) {
323         for (var i = array.length - 1; i >= 0; i--) {
324             var value = array[i];
325             if (predicate(value, i)) {
326                 return value;
327             }
328         }
329         return undefined;
330     }
331     ts.findLast = findLast;
332     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
333     function findIndex(array, predicate, startIndex) {
334         for (var i = startIndex || 0; i < array.length; i++) {
335             if (predicate(array[i], i)) {
336                 return i;
337             }
338         }
339         return -1;
340     }
341     ts.findIndex = findIndex;
342     function findLastIndex(array, predicate, startIndex) {
343         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
344             if (predicate(array[i], i)) {
345                 return i;
346             }
347         }
348         return -1;
349     }
350     ts.findLastIndex = findLastIndex;
351     /**
352      * Returns the first truthy result of `callback`, or else fails.
353      * This is like `forEach`, but never returns undefined.
354      */
355     function findMap(array, callback) {
356         for (var i = 0; i < array.length; i++) {
357             var result = callback(array[i], i);
358             if (result) {
359                 return result;
360             }
361         }
362         return ts.Debug.fail();
363     }
364     ts.findMap = findMap;
365     function contains(array, value, equalityComparer) {
366         if (equalityComparer === void 0) { equalityComparer = equateValues; }
367         if (array) {
368             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
369                 var v = array_1[_i];
370                 if (equalityComparer(v, value)) {
371                     return true;
372                 }
373             }
374         }
375         return false;
376     }
377     ts.contains = contains;
378     function arraysEqual(a, b, equalityComparer) {
379         if (equalityComparer === void 0) { equalityComparer = equateValues; }
380         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
381     }
382     ts.arraysEqual = arraysEqual;
383     function indexOfAnyCharCode(text, charCodes, start) {
384         for (var i = start || 0; i < text.length; i++) {
385             if (contains(charCodes, text.charCodeAt(i))) {
386                 return i;
387             }
388         }
389         return -1;
390     }
391     ts.indexOfAnyCharCode = indexOfAnyCharCode;
392     function countWhere(array, predicate) {
393         var count = 0;
394         if (array) {
395             for (var i = 0; i < array.length; i++) {
396                 var v = array[i];
397                 if (predicate(v, i)) {
398                     count++;
399                 }
400             }
401         }
402         return count;
403     }
404     ts.countWhere = countWhere;
405     function filter(array, f) {
406         if (array) {
407             var len = array.length;
408             var i = 0;
409             while (i < len && f(array[i]))
410                 i++;
411             if (i < len) {
412                 var result = array.slice(0, i);
413                 i++;
414                 while (i < len) {
415                     var item = array[i];
416                     if (f(item)) {
417                         result.push(item);
418                     }
419                     i++;
420                 }
421                 return result;
422             }
423         }
424         return array;
425     }
426     ts.filter = filter;
427     function filterMutate(array, f) {
428         var outIndex = 0;
429         for (var i = 0; i < array.length; i++) {
430             if (f(array[i], i, array)) {
431                 array[outIndex] = array[i];
432                 outIndex++;
433             }
434         }
435         array.length = outIndex;
436     }
437     ts.filterMutate = filterMutate;
438     function clear(array) {
439         array.length = 0;
440     }
441     ts.clear = clear;
442     function map(array, f) {
443         var result;
444         if (array) {
445             result = [];
446             for (var i = 0; i < array.length; i++) {
447                 result.push(f(array[i], i));
448             }
449         }
450         return result;
451     }
452     ts.map = map;
453     function mapIterator(iter, mapFn) {
454         return {
455             next: function () {
456                 var iterRes = iter.next();
457                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
458             }
459         };
460     }
461     ts.mapIterator = mapIterator;
462     function sameMap(array, f) {
463         if (array) {
464             for (var i = 0; i < array.length; i++) {
465                 var item = array[i];
466                 var mapped = f(item, i);
467                 if (item !== mapped) {
468                     var result = array.slice(0, i);
469                     result.push(mapped);
470                     for (i++; i < array.length; i++) {
471                         result.push(f(array[i], i));
472                     }
473                     return result;
474                 }
475             }
476         }
477         return array;
478     }
479     ts.sameMap = sameMap;
480     /**
481      * Flattens an array containing a mix of array or non-array elements.
482      *
483      * @param array The array to flatten.
484      */
485     function flatten(array) {
486         var result = [];
487         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
488             var v = array_2[_i];
489             if (v) {
490                 if (isArray(v)) {
491                     addRange(result, v);
492                 }
493                 else {
494                     result.push(v);
495                 }
496             }
497         }
498         return result;
499     }
500     ts.flatten = flatten;
501     /**
502      * Maps an array. If the mapped value is an array, it is spread into the result.
503      *
504      * @param array The array to map.
505      * @param mapfn The callback used to map the result into one or more values.
506      */
507     function flatMap(array, mapfn) {
508         var result;
509         if (array) {
510             for (var i = 0; i < array.length; i++) {
511                 var v = mapfn(array[i], i);
512                 if (v) {
513                     if (isArray(v)) {
514                         result = addRange(result, v);
515                     }
516                     else {
517                         result = append(result, v);
518                     }
519                 }
520             }
521         }
522         return result || ts.emptyArray;
523     }
524     ts.flatMap = flatMap;
525     function flatMapToMutable(array, mapfn) {
526         var result = [];
527         if (array) {
528             for (var i = 0; i < array.length; i++) {
529                 var v = mapfn(array[i], i);
530                 if (v) {
531                     if (isArray(v)) {
532                         addRange(result, v);
533                     }
534                     else {
535                         result.push(v);
536                     }
537                 }
538             }
539         }
540         return result;
541     }
542     ts.flatMapToMutable = flatMapToMutable;
543     function flatMapIterator(iter, mapfn) {
544         var first = iter.next();
545         if (first.done) {
546             return ts.emptyIterator;
547         }
548         var currentIter = getIterator(first.value);
549         return {
550             next: function () {
551                 while (true) {
552                     var currentRes = currentIter.next();
553                     if (!currentRes.done) {
554                         return currentRes;
555                     }
556                     var iterRes = iter.next();
557                     if (iterRes.done) {
558                         return iterRes;
559                     }
560                     currentIter = getIterator(iterRes.value);
561                 }
562             },
563         };
564         function getIterator(x) {
565             var res = mapfn(x);
566             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
567         }
568     }
569     ts.flatMapIterator = flatMapIterator;
570     function sameFlatMap(array, mapfn) {
571         var result;
572         if (array) {
573             for (var i = 0; i < array.length; i++) {
574                 var item = array[i];
575                 var mapped = mapfn(item, i);
576                 if (result || item !== mapped || isArray(mapped)) {
577                     if (!result) {
578                         result = array.slice(0, i);
579                     }
580                     if (isArray(mapped)) {
581                         addRange(result, mapped);
582                     }
583                     else {
584                         result.push(mapped);
585                     }
586                 }
587             }
588         }
589         return result || array;
590     }
591     ts.sameFlatMap = sameFlatMap;
592     function mapAllOrFail(array, mapFn) {
593         var result = [];
594         for (var i = 0; i < array.length; i++) {
595             var mapped = mapFn(array[i], i);
596             if (mapped === undefined) {
597                 return undefined;
598             }
599             result.push(mapped);
600         }
601         return result;
602     }
603     ts.mapAllOrFail = mapAllOrFail;
604     function mapDefined(array, mapFn) {
605         var result = [];
606         if (array) {
607             for (var i = 0; i < array.length; i++) {
608                 var mapped = mapFn(array[i], i);
609                 if (mapped !== undefined) {
610                     result.push(mapped);
611                 }
612             }
613         }
614         return result;
615     }
616     ts.mapDefined = mapDefined;
617     function mapDefinedIterator(iter, mapFn) {
618         return {
619             next: function () {
620                 while (true) {
621                     var res = iter.next();
622                     if (res.done) {
623                         return res;
624                     }
625                     var value = mapFn(res.value);
626                     if (value !== undefined) {
627                         return { value: value, done: false };
628                     }
629                 }
630             }
631         };
632     }
633     ts.mapDefinedIterator = mapDefinedIterator;
634     function mapDefinedEntries(map, f) {
635         if (!map) {
636             return undefined;
637         }
638         var result = new ts.Map();
639         map.forEach(function (value, key) {
640             var entry = f(key, value);
641             if (entry !== undefined) {
642                 var newKey = entry[0], newValue = entry[1];
643                 if (newKey !== undefined && newValue !== undefined) {
644                     result.set(newKey, newValue);
645                 }
646             }
647         });
648         return result;
649     }
650     ts.mapDefinedEntries = mapDefinedEntries;
651     function mapDefinedValues(set, f) {
652         if (set) {
653             var result_1 = new ts.Set();
654             set.forEach(function (value) {
655                 var newValue = f(value);
656                 if (newValue !== undefined) {
657                     result_1.add(newValue);
658                 }
659             });
660             return result_1;
661         }
662     }
663     ts.mapDefinedValues = mapDefinedValues;
664     function getOrUpdate(map, key, callback) {
665         if (map.has(key)) {
666             return map.get(key);
667         }
668         var value = callback();
669         map.set(key, value);
670         return value;
671     }
672     ts.getOrUpdate = getOrUpdate;
673     function tryAddToSet(set, value) {
674         if (!set.has(value)) {
675             set.add(value);
676             return true;
677         }
678         return false;
679     }
680     ts.tryAddToSet = tryAddToSet;
681     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
682     function singleIterator(value) {
683         var done = false;
684         return {
685             next: function () {
686                 var wasDone = done;
687                 done = true;
688                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
689             }
690         };
691     }
692     ts.singleIterator = singleIterator;
693     function spanMap(array, keyfn, mapfn) {
694         var result;
695         if (array) {
696             result = [];
697             var len = array.length;
698             var previousKey = void 0;
699             var key = void 0;
700             var start = 0;
701             var pos = 0;
702             while (start < len) {
703                 while (pos < len) {
704                     var value = array[pos];
705                     key = keyfn(value, pos);
706                     if (pos === 0) {
707                         previousKey = key;
708                     }
709                     else if (key !== previousKey) {
710                         break;
711                     }
712                     pos++;
713                 }
714                 if (start < pos) {
715                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
716                     if (v) {
717                         result.push(v);
718                     }
719                     start = pos;
720                 }
721                 previousKey = key;
722                 pos++;
723             }
724         }
725         return result;
726     }
727     ts.spanMap = spanMap;
728     function mapEntries(map, f) {
729         if (!map) {
730             return undefined;
731         }
732         var result = new ts.Map();
733         map.forEach(function (value, key) {
734             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
735             result.set(newKey, newValue);
736         });
737         return result;
738     }
739     ts.mapEntries = mapEntries;
740     function some(array, predicate) {
741         if (array) {
742             if (predicate) {
743                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
744                     var v = array_3[_i];
745                     if (predicate(v)) {
746                         return true;
747                     }
748                 }
749             }
750             else {
751                 return array.length > 0;
752             }
753         }
754         return false;
755     }
756     ts.some = some;
757     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
758     function getRangesWhere(arr, pred, cb) {
759         var start;
760         for (var i = 0; i < arr.length; i++) {
761             if (pred(arr[i])) {
762                 start = start === undefined ? i : start;
763             }
764             else {
765                 if (start !== undefined) {
766                     cb(start, i);
767                     start = undefined;
768                 }
769             }
770         }
771         if (start !== undefined)
772             cb(start, arr.length);
773     }
774     ts.getRangesWhere = getRangesWhere;
775     function concatenate(array1, array2) {
776         if (!some(array2))
777             return array1;
778         if (!some(array1))
779             return array2;
780         return __spreadArray(__spreadArray([], array1, true), array2, true);
781     }
782     ts.concatenate = concatenate;
783     function selectIndex(_, i) {
784         return i;
785     }
786     function indicesOf(array) {
787         return array.map(selectIndex);
788     }
789     ts.indicesOf = indicesOf;
790     function deduplicateRelational(array, equalityComparer, comparer) {
791         // Perform a stable sort of the array. This ensures the first entry in a list of
792         // duplicates remains the first entry in the result.
793         var indices = indicesOf(array);
794         stableSortIndices(array, indices, comparer);
795         var last = array[indices[0]];
796         var deduplicated = [indices[0]];
797         for (var i = 1; i < indices.length; i++) {
798             var index = indices[i];
799             var item = array[index];
800             if (!equalityComparer(last, item)) {
801                 deduplicated.push(index);
802                 last = item;
803             }
804         }
805         // restore original order
806         deduplicated.sort();
807         return deduplicated.map(function (i) { return array[i]; });
808     }
809     function deduplicateEquality(array, equalityComparer) {
810         var result = [];
811         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
812             var item = array_4[_i];
813             pushIfUnique(result, item, equalityComparer);
814         }
815         return result;
816     }
817     /**
818      * Deduplicates an unsorted array.
819      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
820      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
821      * result will remain in the original order in `array`.
822      */
823     function deduplicate(array, equalityComparer, comparer) {
824         return array.length === 0 ? [] :
825             array.length === 1 ? array.slice() :
826                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
827                     deduplicateEquality(array, equalityComparer);
828     }
829     ts.deduplicate = deduplicate;
830     /**
831      * Deduplicates an array that has already been sorted.
832      */
833     function deduplicateSorted(array, comparer) {
834         if (array.length === 0)
835             return ts.emptyArray;
836         var last = array[0];
837         var deduplicated = [last];
838         for (var i = 1; i < array.length; i++) {
839             var next = array[i];
840             switch (comparer(next, last)) {
841                 // equality comparison
842                 case true:
843                 // relational comparison
844                 // falls through
845                 case 0 /* EqualTo */:
846                     continue;
847                 case -1 /* LessThan */:
848                     // If `array` is sorted, `next` should **never** be less than `last`.
849                     return ts.Debug.fail("Array is unsorted.");
850             }
851             deduplicated.push(last = next);
852         }
853         return deduplicated;
854     }
855     function insertSorted(array, insert, compare) {
856         if (array.length === 0) {
857             array.push(insert);
858             return;
859         }
860         var insertIndex = binarySearch(array, insert, identity, compare);
861         if (insertIndex < 0) {
862             array.splice(~insertIndex, 0, insert);
863         }
864     }
865     ts.insertSorted = insertSorted;
866     function sortAndDeduplicate(array, comparer, equalityComparer) {
867         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
868     }
869     ts.sortAndDeduplicate = sortAndDeduplicate;
870     function arrayIsSorted(array, comparer) {
871         if (array.length < 2)
872             return true;
873         var prevElement = array[0];
874         for (var _i = 0, _a = array.slice(1); _i < _a.length; _i++) {
875             var element = _a[_i];
876             if (comparer(prevElement, element) === 1 /* GreaterThan */) {
877                 return false;
878             }
879             prevElement = element;
880         }
881         return true;
882     }
883     ts.arrayIsSorted = arrayIsSorted;
884     function arrayIsEqualTo(array1, array2, equalityComparer) {
885         if (equalityComparer === void 0) { equalityComparer = equateValues; }
886         if (!array1 || !array2) {
887             return array1 === array2;
888         }
889         if (array1.length !== array2.length) {
890             return false;
891         }
892         for (var i = 0; i < array1.length; i++) {
893             if (!equalityComparer(array1[i], array2[i], i)) {
894                 return false;
895             }
896         }
897         return true;
898     }
899     ts.arrayIsEqualTo = arrayIsEqualTo;
900     function compact(array) {
901         var result;
902         if (array) {
903             for (var i = 0; i < array.length; i++) {
904                 var v = array[i];
905                 if (result || !v) {
906                     if (!result) {
907                         result = array.slice(0, i);
908                     }
909                     if (v) {
910                         result.push(v);
911                     }
912                 }
913             }
914         }
915         return result || array;
916     }
917     ts.compact = compact;
918     /**
919      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
920      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
921      * based on the provided comparer.
922      */
923     function relativeComplement(arrayA, arrayB, comparer) {
924         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
925             return arrayB;
926         var result = [];
927         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
928             if (offsetB > 0) {
929                 // Ensure `arrayB` is properly sorted.
930                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
931             }
932             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
933                 if (offsetA > startA) {
934                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
935                     // `offsetA` has changed since we entered the loop.
936                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
937                 }
938                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
939                     case -1 /* LessThan */:
940                         // If B is less than A, B does not exist in arrayA. Add B to the result and
941                         // move to the next element in arrayB without changing the current position
942                         // in arrayA.
943                         result.push(arrayB[offsetB]);
944                         continue loopB;
945                     case 0 /* EqualTo */:
946                         // If B is equal to A, B exists in arrayA. Move to the next element in
947                         // arrayB without adding B to the result or changing the current position
948                         // in arrayA.
949                         continue loopB;
950                     case 1 /* GreaterThan */:
951                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
952                         // the next element in arrayA and recheck.
953                         continue loopA;
954                 }
955             }
956         }
957         return result;
958     }
959     ts.relativeComplement = relativeComplement;
960     function sum(array, prop) {
961         var result = 0;
962         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
963             var v = array_5[_i];
964             result += v[prop];
965         }
966         return result;
967     }
968     ts.sum = sum;
969     function append(to, value) {
970         if (value === undefined)
971             return to;
972         if (to === undefined)
973             return [value];
974         to.push(value);
975         return to;
976     }
977     ts.append = append;
978     function combine(xs, ys) {
979         if (xs === undefined)
980             return ys;
981         if (ys === undefined)
982             return xs;
983         if (isArray(xs))
984             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
985         if (isArray(ys))
986             return append(ys, xs);
987         return [xs, ys];
988     }
989     ts.combine = combine;
990     /**
991      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
992      * position offset from the end of the array.
993      */
994     function toOffset(array, offset) {
995         return offset < 0 ? array.length + offset : offset;
996     }
997     function addRange(to, from, start, end) {
998         if (from === undefined || from.length === 0)
999             return to;
1000         if (to === undefined)
1001             return from.slice(start, end);
1002         start = start === undefined ? 0 : toOffset(from, start);
1003         end = end === undefined ? from.length : toOffset(from, end);
1004         for (var i = start; i < end && i < from.length; i++) {
1005             if (from[i] !== undefined) {
1006                 to.push(from[i]);
1007             }
1008         }
1009         return to;
1010     }
1011     ts.addRange = addRange;
1012     /**
1013      * @return Whether the value was added.
1014      */
1015     function pushIfUnique(array, toAdd, equalityComparer) {
1016         if (contains(array, toAdd, equalityComparer)) {
1017             return false;
1018         }
1019         else {
1020             array.push(toAdd);
1021             return true;
1022         }
1023     }
1024     ts.pushIfUnique = pushIfUnique;
1025     /**
1026      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
1027      */
1028     function appendIfUnique(array, toAdd, equalityComparer) {
1029         if (array) {
1030             pushIfUnique(array, toAdd, equalityComparer);
1031             return array;
1032         }
1033         else {
1034             return [toAdd];
1035         }
1036     }
1037     ts.appendIfUnique = appendIfUnique;
1038     function stableSortIndices(array, indices, comparer) {
1039         // sort indices by value then position
1040         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1041     }
1042     /**
1043      * Returns a new sorted array.
1044      */
1045     function sort(array, comparer) {
1046         return (array.length === 0 ? array : array.slice().sort(comparer));
1047     }
1048     ts.sort = sort;
1049     function arrayIterator(array) {
1050         var i = 0;
1051         return { next: function () {
1052                 if (i === array.length) {
1053                     return { value: undefined, done: true };
1054                 }
1055                 else {
1056                     i++;
1057                     return { value: array[i - 1], done: false };
1058                 }
1059             } };
1060     }
1061     ts.arrayIterator = arrayIterator;
1062     function arrayReverseIterator(array) {
1063         var i = array.length;
1064         return {
1065             next: function () {
1066                 if (i === 0) {
1067                     return { value: undefined, done: true };
1068                 }
1069                 else {
1070                     i--;
1071                     return { value: array[i], done: false };
1072                 }
1073             }
1074         };
1075     }
1076     ts.arrayReverseIterator = arrayReverseIterator;
1077     /**
1078      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1079      */
1080     function stableSort(array, comparer) {
1081         var indices = indicesOf(array);
1082         stableSortIndices(array, indices, comparer);
1083         return indices.map(function (i) { return array[i]; });
1084     }
1085     ts.stableSort = stableSort;
1086     function rangeEquals(array1, array2, pos, end) {
1087         while (pos < end) {
1088             if (array1[pos] !== array2[pos]) {
1089                 return false;
1090             }
1091             pos++;
1092         }
1093         return true;
1094     }
1095     ts.rangeEquals = rangeEquals;
1096     /**
1097      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1098      * A negative offset indicates the element should be retrieved from the end of the array.
1099      */
1100     function elementAt(array, offset) {
1101         if (array) {
1102             offset = toOffset(array, offset);
1103             if (offset < array.length) {
1104                 return array[offset];
1105             }
1106         }
1107         return undefined;
1108     }
1109     ts.elementAt = elementAt;
1110     /**
1111      * Returns the first element of an array if non-empty, `undefined` otherwise.
1112      */
1113     function firstOrUndefined(array) {
1114         return array.length === 0 ? undefined : array[0];
1115     }
1116     ts.firstOrUndefined = firstOrUndefined;
1117     function first(array) {
1118         ts.Debug.assert(array.length !== 0);
1119         return array[0];
1120     }
1121     ts.first = first;
1122     /**
1123      * Returns the last element of an array if non-empty, `undefined` otherwise.
1124      */
1125     function lastOrUndefined(array) {
1126         return array.length === 0 ? undefined : array[array.length - 1];
1127     }
1128     ts.lastOrUndefined = lastOrUndefined;
1129     function last(array) {
1130         ts.Debug.assert(array.length !== 0);
1131         return array[array.length - 1];
1132     }
1133     ts.last = last;
1134     /**
1135      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1136      */
1137     function singleOrUndefined(array) {
1138         return array && array.length === 1
1139             ? array[0]
1140             : undefined;
1141     }
1142     ts.singleOrUndefined = singleOrUndefined;
1143     function singleOrMany(array) {
1144         return array && array.length === 1
1145             ? array[0]
1146             : array;
1147     }
1148     ts.singleOrMany = singleOrMany;
1149     function replaceElement(array, index, value) {
1150         var result = array.slice(0);
1151         result[index] = value;
1152         return result;
1153     }
1154     ts.replaceElement = replaceElement;
1155     /**
1156      * Performs a binary search, finding the index at which `value` occurs in `array`.
1157      * If no such index is found, returns the 2's-complement of first index at which
1158      * `array[index]` exceeds `value`.
1159      * @param array A sorted array whose first element must be no larger than number
1160      * @param value The value to be searched for in the array.
1161      * @param keySelector A callback used to select the search key from `value` and each element of
1162      * `array`.
1163      * @param keyComparer A callback used to compare two keys in a sorted array.
1164      * @param offset An offset into `array` at which to start the search.
1165      */
1166     function binarySearch(array, value, keySelector, keyComparer, offset) {
1167         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1168     }
1169     ts.binarySearch = binarySearch;
1170     /**
1171      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1172      * If no such index is found, returns the 2's-complement of first index at which
1173      * `array[index]` exceeds `key`.
1174      * @param array A sorted array whose first element must be no larger than number
1175      * @param key The key to be searched for in the array.
1176      * @param keySelector A callback used to select the search key from each element of `array`.
1177      * @param keyComparer A callback used to compare two keys in a sorted array.
1178      * @param offset An offset into `array` at which to start the search.
1179      */
1180     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1181         if (!some(array)) {
1182             return -1;
1183         }
1184         var low = offset || 0;
1185         var high = array.length - 1;
1186         while (low <= high) {
1187             var middle = low + ((high - low) >> 1);
1188             var midKey = keySelector(array[middle], middle);
1189             switch (keyComparer(midKey, key)) {
1190                 case -1 /* LessThan */:
1191                     low = middle + 1;
1192                     break;
1193                 case 0 /* EqualTo */:
1194                     return middle;
1195                 case 1 /* GreaterThan */:
1196                     high = middle - 1;
1197                     break;
1198             }
1199         }
1200         return ~low;
1201     }
1202     ts.binarySearchKey = binarySearchKey;
1203     function reduceLeft(array, f, initial, start, count) {
1204         if (array && array.length > 0) {
1205             var size = array.length;
1206             if (size > 0) {
1207                 var pos = start === undefined || start < 0 ? 0 : start;
1208                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1209                 var result = void 0;
1210                 if (arguments.length <= 2) {
1211                     result = array[pos];
1212                     pos++;
1213                 }
1214                 else {
1215                     result = initial;
1216                 }
1217                 while (pos <= end) {
1218                     result = f(result, array[pos], pos);
1219                     pos++;
1220                 }
1221                 return result;
1222             }
1223         }
1224         return initial;
1225     }
1226     ts.reduceLeft = reduceLeft;
1227     var hasOwnProperty = Object.prototype.hasOwnProperty;
1228     /**
1229      * Indicates whether a map-like contains an own property with the specified key.
1230      *
1231      * @param map A map-like.
1232      * @param key A property key.
1233      */
1234     function hasProperty(map, key) {
1235         return hasOwnProperty.call(map, key);
1236     }
1237     ts.hasProperty = hasProperty;
1238     /**
1239      * Gets the value of an owned property in a map-like.
1240      *
1241      * @param map A map-like.
1242      * @param key A property key.
1243      */
1244     function getProperty(map, key) {
1245         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1246     }
1247     ts.getProperty = getProperty;
1248     /**
1249      * Gets the owned, enumerable property keys of a map-like.
1250      */
1251     function getOwnKeys(map) {
1252         var keys = [];
1253         for (var key in map) {
1254             if (hasOwnProperty.call(map, key)) {
1255                 keys.push(key);
1256             }
1257         }
1258         return keys;
1259     }
1260     ts.getOwnKeys = getOwnKeys;
1261     function getAllKeys(obj) {
1262         var result = [];
1263         do {
1264             var names = Object.getOwnPropertyNames(obj);
1265             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1266                 var name = names_1[_i];
1267                 pushIfUnique(result, name);
1268             }
1269         } while (obj = Object.getPrototypeOf(obj));
1270         return result;
1271     }
1272     ts.getAllKeys = getAllKeys;
1273     function getOwnValues(sparseArray) {
1274         var values = [];
1275         for (var key in sparseArray) {
1276             if (hasOwnProperty.call(sparseArray, key)) {
1277                 values.push(sparseArray[key]);
1278             }
1279         }
1280         return values;
1281     }
1282     ts.getOwnValues = getOwnValues;
1283     var _entries = Object.entries || (function (obj) {
1284         var keys = getOwnKeys(obj);
1285         var result = Array(keys.length);
1286         for (var i = 0; i < keys.length; i++) {
1287             result[i] = [keys[i], obj[keys[i]]];
1288         }
1289         return result;
1290     });
1291     function getEntries(obj) {
1292         return obj ? _entries(obj) : [];
1293     }
1294     ts.getEntries = getEntries;
1295     function arrayOf(count, f) {
1296         var result = new Array(count);
1297         for (var i = 0; i < count; i++) {
1298             result[i] = f(i);
1299         }
1300         return result;
1301     }
1302     ts.arrayOf = arrayOf;
1303     function arrayFrom(iterator, map) {
1304         var result = [];
1305         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1306             result.push(map ? map(iterResult.value) : iterResult.value);
1307         }
1308         return result;
1309     }
1310     ts.arrayFrom = arrayFrom;
1311     function assign(t) {
1312         var args = [];
1313         for (var _i = 1; _i < arguments.length; _i++) {
1314             args[_i - 1] = arguments[_i];
1315         }
1316         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1317             var arg = args_1[_a];
1318             if (arg === undefined)
1319                 continue;
1320             for (var p in arg) {
1321                 if (hasProperty(arg, p)) {
1322                     t[p] = arg[p];
1323                 }
1324             }
1325         }
1326         return t;
1327     }
1328     ts.assign = assign;
1329     /**
1330      * Performs a shallow equality comparison of the contents of two map-likes.
1331      *
1332      * @param left A map-like whose properties should be compared.
1333      * @param right A map-like whose properties should be compared.
1334      */
1335     function equalOwnProperties(left, right, equalityComparer) {
1336         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1337         if (left === right)
1338             return true;
1339         if (!left || !right)
1340             return false;
1341         for (var key in left) {
1342             if (hasOwnProperty.call(left, key)) {
1343                 if (!hasOwnProperty.call(right, key))
1344                     return false;
1345                 if (!equalityComparer(left[key], right[key]))
1346                     return false;
1347             }
1348         }
1349         for (var key in right) {
1350             if (hasOwnProperty.call(right, key)) {
1351                 if (!hasOwnProperty.call(left, key))
1352                     return false;
1353             }
1354         }
1355         return true;
1356     }
1357     ts.equalOwnProperties = equalOwnProperties;
1358     function arrayToMap(array, makeKey, makeValue) {
1359         if (makeValue === void 0) { makeValue = identity; }
1360         var result = new ts.Map();
1361         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1362             var value = array_6[_i];
1363             var key = makeKey(value);
1364             if (key !== undefined)
1365                 result.set(key, makeValue(value));
1366         }
1367         return result;
1368     }
1369     ts.arrayToMap = arrayToMap;
1370     function arrayToNumericMap(array, makeKey, makeValue) {
1371         if (makeValue === void 0) { makeValue = identity; }
1372         var result = [];
1373         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1374             var value = array_7[_i];
1375             result[makeKey(value)] = makeValue(value);
1376         }
1377         return result;
1378     }
1379     ts.arrayToNumericMap = arrayToNumericMap;
1380     function arrayToMultiMap(values, makeKey, makeValue) {
1381         if (makeValue === void 0) { makeValue = identity; }
1382         var result = createMultiMap();
1383         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1384             var value = values_1[_i];
1385             result.add(makeKey(value), makeValue(value));
1386         }
1387         return result;
1388     }
1389     ts.arrayToMultiMap = arrayToMultiMap;
1390     function group(values, getGroupId, resultSelector) {
1391         if (resultSelector === void 0) { resultSelector = identity; }
1392         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1393     }
1394     ts.group = group;
1395     function clone(object) {
1396         var result = {};
1397         for (var id in object) {
1398             if (hasOwnProperty.call(object, id)) {
1399                 result[id] = object[id];
1400             }
1401         }
1402         return result;
1403     }
1404     ts.clone = clone;
1405     /**
1406      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1407      *
1408      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1409      */
1410     function extend(first, second) {
1411         var result = {};
1412         for (var id in second) {
1413             if (hasOwnProperty.call(second, id)) {
1414                 result[id] = second[id];
1415             }
1416         }
1417         for (var id in first) {
1418             if (hasOwnProperty.call(first, id)) {
1419                 result[id] = first[id];
1420             }
1421         }
1422         return result;
1423     }
1424     ts.extend = extend;
1425     function copyProperties(first, second) {
1426         for (var id in second) {
1427             if (hasOwnProperty.call(second, id)) {
1428                 first[id] = second[id];
1429             }
1430         }
1431     }
1432     ts.copyProperties = copyProperties;
1433     function maybeBind(obj, fn) {
1434         return fn ? fn.bind(obj) : undefined;
1435     }
1436     ts.maybeBind = maybeBind;
1437     function createMultiMap() {
1438         var map = new ts.Map();
1439         map.add = multiMapAdd;
1440         map.remove = multiMapRemove;
1441         return map;
1442     }
1443     ts.createMultiMap = createMultiMap;
1444     function multiMapAdd(key, value) {
1445         var values = this.get(key);
1446         if (values) {
1447             values.push(value);
1448         }
1449         else {
1450             this.set(key, values = [value]);
1451         }
1452         return values;
1453     }
1454     function multiMapRemove(key, value) {
1455         var values = this.get(key);
1456         if (values) {
1457             unorderedRemoveItem(values, value);
1458             if (!values.length) {
1459                 this.delete(key);
1460             }
1461         }
1462     }
1463     function createUnderscoreEscapedMultiMap() {
1464         return createMultiMap();
1465     }
1466     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1467     /**
1468      * Tests whether a value is an array.
1469      */
1470     function isArray(value) {
1471         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1472     }
1473     ts.isArray = isArray;
1474     function toArray(value) {
1475         return isArray(value) ? value : [value];
1476     }
1477     ts.toArray = toArray;
1478     /**
1479      * Tests whether a value is string
1480      */
1481     function isString(text) {
1482         return typeof text === "string";
1483     }
1484     ts.isString = isString;
1485     function isNumber(x) {
1486         return typeof x === "number";
1487     }
1488     ts.isNumber = isNumber;
1489     function tryCast(value, test) {
1490         return value !== undefined && test(value) ? value : undefined;
1491     }
1492     ts.tryCast = tryCast;
1493     function cast(value, test) {
1494         if (value !== undefined && test(value))
1495             return value;
1496         return ts.Debug.fail("Invalid cast. The supplied value ".concat(value, " did not pass the test '").concat(ts.Debug.getFunctionName(test), "'."));
1497     }
1498     ts.cast = cast;
1499     /** Does nothing. */
1500     function noop(_) { }
1501     ts.noop = noop;
1502     /** Do nothing and return false */
1503     function returnFalse() {
1504         return false;
1505     }
1506     ts.returnFalse = returnFalse;
1507     /** Do nothing and return true */
1508     function returnTrue() {
1509         return true;
1510     }
1511     ts.returnTrue = returnTrue;
1512     /** Do nothing and return undefined */
1513     function returnUndefined() {
1514         return undefined;
1515     }
1516     ts.returnUndefined = returnUndefined;
1517     /** Returns its argument. */
1518     function identity(x) {
1519         return x;
1520     }
1521     ts.identity = identity;
1522     /** Returns lower case string */
1523     function toLowerCase(x) {
1524         return x.toLowerCase();
1525     }
1526     ts.toLowerCase = toLowerCase;
1527     // We convert the file names to lower case as key for file name on case insensitive file system
1528     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1529     // it to lower case, fileName with its lowercase form can exist along side it.
1530     // Handle special characters and make those case sensitive instead
1531     //
1532     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1533     // | 1. | i        | 105       | Ascii i                                                                |
1534     // | 2. | I        | 73        | Ascii I                                                                |
1535     // |-------- Special characters ------------------------------------------------------------------------|
1536     // | 3. | \u0130   | 304       | Upper case I with dot above                                            |
1537     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1538     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1539     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1540     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1541     //
1542     // Because item 3 is special where in its lowercase character has its own
1543     // upper case form we cant convert its case.
1544     // Rest special characters are either already in lower case format or
1545     // they have corresponding upper case character so they dont need special handling
1546     //
1547     // But to avoid having to do string building for most common cases, also ignore
1548     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1549     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1550     /**
1551      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1552      * This function is used in places where we want to make file name as a key on these systems
1553      * 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
1554      * 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
1555      * Technically we would want this function to be platform sepcific as well but
1556      * 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
1557      * We could use upper case and we would still need to deal with the descripencies but
1558      * 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
1559      * 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
1560      */
1561     function toFileNameLowerCase(x) {
1562         return fileNameLowerCaseRegExp.test(x) ?
1563             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1564             x;
1565     }
1566     ts.toFileNameLowerCase = toFileNameLowerCase;
1567     /** Throws an error because a function is not implemented. */
1568     function notImplemented() {
1569         throw new Error("Not implemented");
1570     }
1571     ts.notImplemented = notImplemented;
1572     function memoize(callback) {
1573         var value;
1574         return function () {
1575             if (callback) {
1576                 value = callback();
1577                 callback = undefined;
1578             }
1579             return value;
1580         };
1581     }
1582     ts.memoize = memoize;
1583     /** A version of `memoize` that supports a single primitive argument */
1584     function memoizeOne(callback) {
1585         var map = new ts.Map();
1586         return function (arg) {
1587             var key = "".concat(typeof arg, ":").concat(arg);
1588             var value = map.get(key);
1589             if (value === undefined && !map.has(key)) {
1590                 value = callback(arg);
1591                 map.set(key, value);
1592             }
1593             return value;
1594         };
1595     }
1596     ts.memoizeOne = memoizeOne;
1597     function compose(a, b, c, d, e) {
1598         if (!!e) {
1599             var args_2 = [];
1600             for (var i = 0; i < arguments.length; i++) {
1601                 args_2[i] = arguments[i];
1602             }
1603             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1604         }
1605         else if (d) {
1606             return function (t) { return d(c(b(a(t)))); };
1607         }
1608         else if (c) {
1609             return function (t) { return c(b(a(t))); };
1610         }
1611         else if (b) {
1612             return function (t) { return b(a(t)); };
1613         }
1614         else if (a) {
1615             return function (t) { return a(t); };
1616         }
1617         else {
1618             return function (t) { return t; };
1619         }
1620     }
1621     ts.compose = compose;
1622     var AssertionLevel;
1623     (function (AssertionLevel) {
1624         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1625         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1626         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1627         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1628     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1629     function equateValues(a, b) {
1630         return a === b;
1631     }
1632     ts.equateValues = equateValues;
1633     /**
1634      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1635      *
1636      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1637      * value of each code-point after applying `toUpperCase` to each string. We always map both
1638      * strings to their upper-case form as some unicode characters do not properly round-trip to
1639      * lowercase (such as `ẞ` (German sharp capital s)).
1640      */
1641     function equateStringsCaseInsensitive(a, b) {
1642         return a === b
1643             || a !== undefined
1644                 && b !== undefined
1645                 && a.toUpperCase() === b.toUpperCase();
1646     }
1647     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1648     /**
1649      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1650      *
1651      * Case-sensitive comparisons compare both strings one code-point at a time using the
1652      * integer value of each code-point.
1653      */
1654     function equateStringsCaseSensitive(a, b) {
1655         return equateValues(a, b);
1656     }
1657     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1658     function compareComparableValues(a, b) {
1659         return a === b ? 0 /* EqualTo */ :
1660             a === undefined ? -1 /* LessThan */ :
1661                 b === undefined ? 1 /* GreaterThan */ :
1662                     a < b ? -1 /* LessThan */ :
1663                         1 /* GreaterThan */;
1664     }
1665     /**
1666      * Compare two numeric values for their order relative to each other.
1667      * To compare strings, use any of the `compareStrings` functions.
1668      */
1669     function compareValues(a, b) {
1670         return compareComparableValues(a, b);
1671     }
1672     ts.compareValues = compareValues;
1673     /**
1674      * Compare two TextSpans, first by `start`, then by `length`.
1675      */
1676     function compareTextSpans(a, b) {
1677         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);
1678     }
1679     ts.compareTextSpans = compareTextSpans;
1680     function min(a, b, compare) {
1681         return compare(a, b) === -1 /* LessThan */ ? a : b;
1682     }
1683     ts.min = min;
1684     /**
1685      * Compare two strings using a case-insensitive ordinal comparison.
1686      *
1687      * Ordinal comparisons are based on the difference between the unicode code points of both
1688      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1689      * comparisons provide predictable ordering, but place "a" after "B".
1690      *
1691      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1692      * value of each code-point after applying `toUpperCase` to each string. We always map both
1693      * strings to their upper-case form as some unicode characters do not properly round-trip to
1694      * lowercase (such as `ẞ` (German sharp capital s)).
1695      */
1696     function compareStringsCaseInsensitive(a, b) {
1697         if (a === b)
1698             return 0 /* EqualTo */;
1699         if (a === undefined)
1700             return -1 /* LessThan */;
1701         if (b === undefined)
1702             return 1 /* GreaterThan */;
1703         a = a.toUpperCase();
1704         b = b.toUpperCase();
1705         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1706     }
1707     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1708     /**
1709      * Compare two strings using a case-sensitive ordinal comparison.
1710      *
1711      * Ordinal comparisons are based on the difference between the unicode code points of both
1712      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1713      * comparisons provide predictable ordering, but place "a" after "B".
1714      *
1715      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1716      * value of each code-point.
1717      */
1718     function compareStringsCaseSensitive(a, b) {
1719         return compareComparableValues(a, b);
1720     }
1721     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1722     function getStringComparer(ignoreCase) {
1723         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1724     }
1725     ts.getStringComparer = getStringComparer;
1726     /**
1727      * Creates a string comparer for use with string collation in the UI.
1728      */
1729     var createUIStringComparer = (function () {
1730         var defaultComparer;
1731         var enUSComparer;
1732         var stringComparerFactory = getStringComparerFactory();
1733         return createStringComparer;
1734         function compareWithCallback(a, b, comparer) {
1735             if (a === b)
1736                 return 0 /* EqualTo */;
1737             if (a === undefined)
1738                 return -1 /* LessThan */;
1739             if (b === undefined)
1740                 return 1 /* GreaterThan */;
1741             var value = comparer(a, b);
1742             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1743         }
1744         function createIntlCollatorStringComparer(locale) {
1745             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1746             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1747             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1748             return function (a, b) { return compareWithCallback(a, b, comparer); };
1749         }
1750         function createLocaleCompareStringComparer(locale) {
1751             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1752             if (locale !== undefined)
1753                 return createFallbackStringComparer();
1754             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1755             function compareStrings(a, b) {
1756                 return a.localeCompare(b);
1757             }
1758         }
1759         function createFallbackStringComparer() {
1760             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1761             // We first sort case insensitively.  So "Aaa" will come before "baa".
1762             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1763             //
1764             // For case insensitive comparisons we always map both strings to their
1765             // upper-case form as some unicode characters do not properly round-trip to
1766             // lowercase (such as `ẞ` (German sharp capital s)).
1767             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1768             function compareDictionaryOrder(a, b) {
1769                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1770             }
1771             function compareStrings(a, b) {
1772                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1773             }
1774         }
1775         function getStringComparerFactory() {
1776             // If the host supports Intl, we use it for comparisons using the default locale.
1777             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1778                 return createIntlCollatorStringComparer;
1779             }
1780             // If the host does not support Intl, we fall back to localeCompare.
1781             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1782             if (typeof String.prototype.localeCompare === "function" &&
1783                 typeof String.prototype.toLocaleUpperCase === "function" &&
1784                 "a".localeCompare("B") < 0) {
1785                 return createLocaleCompareStringComparer;
1786             }
1787             // Otherwise, fall back to ordinal comparison:
1788             return createFallbackStringComparer;
1789         }
1790         function createStringComparer(locale) {
1791             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1792             // tests.
1793             if (locale === undefined) {
1794                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1795             }
1796             else if (locale === "en-US") {
1797                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1798             }
1799             else {
1800                 return stringComparerFactory(locale);
1801             }
1802         }
1803     })();
1804     var uiComparerCaseSensitive;
1805     var uiLocale;
1806     function getUILocale() {
1807         return uiLocale;
1808     }
1809     ts.getUILocale = getUILocale;
1810     function setUILocale(value) {
1811         if (uiLocale !== value) {
1812             uiLocale = value;
1813             uiComparerCaseSensitive = undefined;
1814         }
1815     }
1816     ts.setUILocale = setUILocale;
1817     /**
1818      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1819      *
1820      * Ordering is not predictable between different host locales, but is best for displaying
1821      * ordered data for UI presentation. Characters with multiple unicode representations may
1822      * be considered equal.
1823      *
1824      * Case-sensitive comparisons compare strings that differ in base characters, or
1825      * accents/diacritic marks, or case as unequal.
1826      */
1827     function compareStringsCaseSensitiveUI(a, b) {
1828         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1829         return comparer(a, b);
1830     }
1831     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1832     function compareProperties(a, b, key, comparer) {
1833         return a === b ? 0 /* EqualTo */ :
1834             a === undefined ? -1 /* LessThan */ :
1835                 b === undefined ? 1 /* GreaterThan */ :
1836                     comparer(a[key], b[key]);
1837     }
1838     ts.compareProperties = compareProperties;
1839     /** True is greater than false. */
1840     function compareBooleans(a, b) {
1841         return compareValues(a ? 1 : 0, b ? 1 : 0);
1842     }
1843     ts.compareBooleans = compareBooleans;
1844     /**
1845      * 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.
1846      * Names less than length 3 only check for case-insensitive equality.
1847      *
1848      * find the candidate with the smallest Levenshtein distance,
1849      *    except for candidates:
1850      *      * With no name
1851      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1852      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1853      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1854      *         and 1 insertion/deletion at 3 characters)
1855      */
1856     function getSpellingSuggestion(name, candidates, getName) {
1857         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1858         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother.
1859         var bestCandidate;
1860         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1861             var candidate = candidates_1[_i];
1862             var candidateName = getName(candidate);
1863             if (candidateName !== undefined && Math.abs(candidateName.length - name.length) <= maximumLengthDifference) {
1864                 if (candidateName === name) {
1865                     continue;
1866                 }
1867                 // Only consider candidates less than 3 characters long when they differ by case.
1868                 // Otherwise, don't bother, since a user would usually notice differences of a 2-character name.
1869                 if (candidateName.length < 3 && candidateName.toLowerCase() !== name.toLowerCase()) {
1870                     continue;
1871                 }
1872                 var distance = levenshteinWithMax(name, candidateName, bestDistance - 0.1);
1873                 if (distance === undefined) {
1874                     continue;
1875                 }
1876                 ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1877                 bestDistance = distance;
1878                 bestCandidate = candidate;
1879             }
1880         }
1881         return bestCandidate;
1882     }
1883     ts.getSpellingSuggestion = getSpellingSuggestion;
1884     function levenshteinWithMax(s1, s2, max) {
1885         var previous = new Array(s2.length + 1);
1886         var current = new Array(s2.length + 1);
1887         /** Represents any value > max. We don't care about the particular value. */
1888         var big = max + 0.01;
1889         for (var i = 0; i <= s2.length; i++) {
1890             previous[i] = i;
1891         }
1892         for (var i = 1; i <= s1.length; i++) {
1893             var c1 = s1.charCodeAt(i - 1);
1894             var minJ = Math.ceil(i > max ? i - max : 1);
1895             var maxJ = Math.floor(s2.length > max + i ? max + i : s2.length);
1896             current[0] = i;
1897             /** Smallest value of the matrix in the ith column. */
1898             var colMin = i;
1899             for (var j = 1; j < minJ; j++) {
1900                 current[j] = big;
1901             }
1902             for (var j = minJ; j <= maxJ; j++) {
1903                 // case difference should be significantly cheaper than other differences
1904                 var substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase()
1905                     ? (previous[j - 1] + 0.1)
1906                     : (previous[j - 1] + 2);
1907                 var dist = c1 === s2.charCodeAt(j - 1)
1908                     ? previous[j - 1]
1909                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ substitutionDistance);
1910                 current[j] = dist;
1911                 colMin = Math.min(colMin, dist);
1912             }
1913             for (var j = maxJ + 1; j <= s2.length; j++) {
1914                 current[j] = big;
1915             }
1916             if (colMin > max) {
1917                 // Give up -- everything in this column is > max and it can't get better in future columns.
1918                 return undefined;
1919             }
1920             var temp = previous;
1921             previous = current;
1922             current = temp;
1923         }
1924         var res = previous[s2.length];
1925         return res > max ? undefined : res;
1926     }
1927     function endsWith(str, suffix) {
1928         var expectedPos = str.length - suffix.length;
1929         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1930     }
1931     ts.endsWith = endsWith;
1932     function removeSuffix(str, suffix) {
1933         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1934     }
1935     ts.removeSuffix = removeSuffix;
1936     function tryRemoveSuffix(str, suffix) {
1937         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1938     }
1939     ts.tryRemoveSuffix = tryRemoveSuffix;
1940     function stringContains(str, substring) {
1941         return str.indexOf(substring) !== -1;
1942     }
1943     ts.stringContains = stringContains;
1944     /**
1945      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1946      */
1947     function removeMinAndVersionNumbers(fileName) {
1948         // We used to use the regex /[.-]((min)|(\d+(\.\d+)*))$/ and would just .replace it twice.
1949         // Unfortunately, that regex has O(n^2) performance because v8 doesn't match from the end of the string.
1950         // Instead, we now essentially scan the filename (backwards) ourselves.
1951         var end = fileName.length;
1952         for (var pos = end - 1; pos > 0; pos--) {
1953             var ch = fileName.charCodeAt(pos);
1954             if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
1955                 // Match a \d+ segment
1956                 do {
1957                     --pos;
1958                     ch = fileName.charCodeAt(pos);
1959                 } while (pos > 0 && ch >= 48 /* _0 */ && ch <= 57 /* _9 */);
1960             }
1961             else if (pos > 4 && (ch === 110 /* n */ || ch === 78 /* N */)) {
1962                 // Looking for "min" or "min"
1963                 // Already matched the 'n'
1964                 --pos;
1965                 ch = fileName.charCodeAt(pos);
1966                 if (ch !== 105 /* i */ && ch !== 73 /* I */) {
1967                     break;
1968                 }
1969                 --pos;
1970                 ch = fileName.charCodeAt(pos);
1971                 if (ch !== 109 /* m */ && ch !== 77 /* M */) {
1972                     break;
1973                 }
1974                 --pos;
1975                 ch = fileName.charCodeAt(pos);
1976             }
1977             else {
1978                 // This character is not part of either suffix pattern
1979                 break;
1980             }
1981             if (ch !== 45 /* minus */ && ch !== 46 /* dot */) {
1982                 break;
1983             }
1984             end = pos;
1985         }
1986         // end might be fileName.length, in which case this should internally no-op
1987         return end === fileName.length ? fileName : fileName.slice(0, end);
1988     }
1989     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1990     /** Remove an item from an array, moving everything to its right one space left. */
1991     function orderedRemoveItem(array, item) {
1992         for (var i = 0; i < array.length; i++) {
1993             if (array[i] === item) {
1994                 orderedRemoveItemAt(array, i);
1995                 return true;
1996             }
1997         }
1998         return false;
1999     }
2000     ts.orderedRemoveItem = orderedRemoveItem;
2001     /** Remove an item by index from an array, moving everything to its right one space left. */
2002     function orderedRemoveItemAt(array, index) {
2003         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
2004         for (var i = index; i < array.length - 1; i++) {
2005             array[i] = array[i + 1];
2006         }
2007         array.pop();
2008     }
2009     ts.orderedRemoveItemAt = orderedRemoveItemAt;
2010     function unorderedRemoveItemAt(array, index) {
2011         // Fill in the "hole" left at `index`.
2012         array[index] = array[array.length - 1];
2013         array.pop();
2014     }
2015     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
2016     /** Remove the *first* occurrence of `item` from the array. */
2017     function unorderedRemoveItem(array, item) {
2018         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
2019     }
2020     ts.unorderedRemoveItem = unorderedRemoveItem;
2021     /** Remove the *first* element satisfying `predicate`. */
2022     function unorderedRemoveFirstItemWhere(array, predicate) {
2023         for (var i = 0; i < array.length; i++) {
2024             if (predicate(array[i])) {
2025                 unorderedRemoveItemAt(array, i);
2026                 return true;
2027             }
2028         }
2029         return false;
2030     }
2031     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
2032         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
2033     }
2034     ts.createGetCanonicalFileName = createGetCanonicalFileName;
2035     function patternText(_a) {
2036         var prefix = _a.prefix, suffix = _a.suffix;
2037         return "".concat(prefix, "*").concat(suffix);
2038     }
2039     ts.patternText = patternText;
2040     /**
2041      * Given that candidate matches pattern, returns the text matching the '*'.
2042      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2043      */
2044     function matchedText(pattern, candidate) {
2045         ts.Debug.assert(isPatternMatch(pattern, candidate));
2046         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2047     }
2048     ts.matchedText = matchedText;
2049     /** Return the object corresponding to the best pattern to match `candidate`. */
2050     function findBestPatternMatch(values, getPattern, candidate) {
2051         var matchedValue;
2052         // use length of prefix as betterness criteria
2053         var longestMatchPrefixLength = -1;
2054         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2055             var v = values_2[_i];
2056             var pattern = getPattern(v);
2057             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2058                 longestMatchPrefixLength = pattern.prefix.length;
2059                 matchedValue = v;
2060             }
2061         }
2062         return matchedValue;
2063     }
2064     ts.findBestPatternMatch = findBestPatternMatch;
2065     function startsWith(str, prefix) {
2066         return str.lastIndexOf(prefix, 0) === 0;
2067     }
2068     ts.startsWith = startsWith;
2069     function removePrefix(str, prefix) {
2070         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2071     }
2072     ts.removePrefix = removePrefix;
2073     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2074         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2075         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2076     }
2077     ts.tryRemovePrefix = tryRemovePrefix;
2078     function isPatternMatch(_a, candidate) {
2079         var prefix = _a.prefix, suffix = _a.suffix;
2080         return candidate.length >= prefix.length + suffix.length &&
2081             startsWith(candidate, prefix) &&
2082             endsWith(candidate, suffix);
2083     }
2084     function and(f, g) {
2085         return function (arg) { return f(arg) && g(arg); };
2086     }
2087     ts.and = and;
2088     function or() {
2089         var fs = [];
2090         for (var _i = 0; _i < arguments.length; _i++) {
2091             fs[_i] = arguments[_i];
2092         }
2093         return function () {
2094             var args = [];
2095             for (var _i = 0; _i < arguments.length; _i++) {
2096                 args[_i] = arguments[_i];
2097             }
2098             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2099                 var f = fs_1[_a];
2100                 if (f.apply(void 0, args)) {
2101                     return true;
2102                 }
2103             }
2104             return false;
2105         };
2106     }
2107     ts.or = or;
2108     function not(fn) {
2109         return function () {
2110             var args = [];
2111             for (var _i = 0; _i < arguments.length; _i++) {
2112                 args[_i] = arguments[_i];
2113             }
2114             return !fn.apply(void 0, args);
2115         };
2116     }
2117     ts.not = not;
2118     function assertType(_) { }
2119     ts.assertType = assertType;
2120     function singleElementArray(t) {
2121         return t === undefined ? undefined : [t];
2122     }
2123     ts.singleElementArray = singleElementArray;
2124     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2125         unchanged = unchanged || noop;
2126         var newIndex = 0;
2127         var oldIndex = 0;
2128         var newLen = newItems.length;
2129         var oldLen = oldItems.length;
2130         var hasChanges = false;
2131         while (newIndex < newLen && oldIndex < oldLen) {
2132             var newItem = newItems[newIndex];
2133             var oldItem = oldItems[oldIndex];
2134             var compareResult = comparer(newItem, oldItem);
2135             if (compareResult === -1 /* LessThan */) {
2136                 inserted(newItem);
2137                 newIndex++;
2138                 hasChanges = true;
2139             }
2140             else if (compareResult === 1 /* GreaterThan */) {
2141                 deleted(oldItem);
2142                 oldIndex++;
2143                 hasChanges = true;
2144             }
2145             else {
2146                 unchanged(oldItem, newItem);
2147                 newIndex++;
2148                 oldIndex++;
2149             }
2150         }
2151         while (newIndex < newLen) {
2152             inserted(newItems[newIndex++]);
2153             hasChanges = true;
2154         }
2155         while (oldIndex < oldLen) {
2156             deleted(oldItems[oldIndex++]);
2157             hasChanges = true;
2158         }
2159         return hasChanges;
2160     }
2161     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2162     function fill(length, cb) {
2163         var result = Array(length);
2164         for (var i = 0; i < length; i++) {
2165             result[i] = cb(i);
2166         }
2167         return result;
2168     }
2169     ts.fill = fill;
2170     function cartesianProduct(arrays) {
2171         var result = [];
2172         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2173         return result;
2174     }
2175     ts.cartesianProduct = cartesianProduct;
2176     function cartesianProductWorker(arrays, result, outer, index) {
2177         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2178             var element = _a[_i];
2179             var inner = void 0;
2180             if (outer) {
2181                 inner = outer.slice();
2182                 inner.push(element);
2183             }
2184             else {
2185                 inner = [element];
2186             }
2187             if (index === arrays.length - 1) {
2188                 result.push(inner);
2189             }
2190             else {
2191                 cartesianProductWorker(arrays, result, inner, index + 1);
2192             }
2193         }
2194     }
2195     /**
2196      * Returns string left-padded with spaces or zeros until it reaches the given length.
2197      *
2198      * @param s String to pad.
2199      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2200      * @param padString Character to use as padding (default " ").
2201      */
2202     function padLeft(s, length, padString) {
2203         if (padString === void 0) { padString = " "; }
2204         return length <= s.length ? s : padString.repeat(length - s.length) + s;
2205     }
2206     ts.padLeft = padLeft;
2207     /**
2208      * Returns string right-padded with spaces until it reaches the given length.
2209      *
2210      * @param s String to pad.
2211      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2212      * @param padString Character to use as padding (default " ").
2213      */
2214     function padRight(s, length, padString) {
2215         if (padString === void 0) { padString = " "; }
2216         return length <= s.length ? s : s + padString.repeat(length - s.length);
2217     }
2218     ts.padRight = padRight;
2219     function takeWhile(array, predicate) {
2220         var len = array.length;
2221         var index = 0;
2222         while (index < len && predicate(array[index])) {
2223             index++;
2224         }
2225         return array.slice(0, index);
2226     }
2227     ts.takeWhile = takeWhile;
2228     /**
2229      * Removes the leading and trailing white space and line terminator characters from a string.
2230      */
2231     ts.trimString = !!String.prototype.trim ? (function (s) { return s.trim(); }) : function (s) { return ts.trimStringEnd(ts.trimStringStart(s)); };
2232     /**
2233      * Returns a copy with trailing whitespace removed.
2234      */
2235     ts.trimStringEnd = !!String.prototype.trimEnd ? (function (s) { return s.trimEnd(); }) : trimEndImpl;
2236     /**
2237      * Returns a copy with leading whitespace removed.
2238      */
2239     ts.trimStringStart = !!String.prototype.trimStart ? (function (s) { return s.trimStart(); }) : function (s) { return s.replace(/^\s+/g, ""); };
2240     /**
2241      * https://jsbench.me/gjkoxld4au/1
2242      * The simple regex for this, /\s+$/g is O(n^2) in v8.
2243      * The native .trimEnd method is by far best, but since that's technically ES2019,
2244      * we provide a (still much faster than the simple regex) fallback.
2245      */
2246     function trimEndImpl(s) {
2247         var end = s.length - 1;
2248         while (end >= 0) {
2249             if (!ts.isWhiteSpaceLike(s.charCodeAt(end)))
2250                 break;
2251             end--;
2252         }
2253         return s.slice(0, end + 1);
2254     }
2255 })(ts || (ts = {}));
2256 /* @internal */
2257 var ts;
2258 (function (ts) {
2259     var LogLevel;
2260     (function (LogLevel) {
2261         LogLevel[LogLevel["Off"] = 0] = "Off";
2262         LogLevel[LogLevel["Error"] = 1] = "Error";
2263         LogLevel[LogLevel["Warning"] = 2] = "Warning";
2264         LogLevel[LogLevel["Info"] = 3] = "Info";
2265         LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
2266     })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
2267     var Debug;
2268     (function (Debug) {
2269         var typeScriptVersion;
2270         /* eslint-disable prefer-const */
2271         var currentAssertionLevel = 0 /* None */;
2272         Debug.currentLogLevel = LogLevel.Warning;
2273         Debug.isDebugging = false;
2274         function getTypeScriptVersion() {
2275             return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
2276         }
2277         Debug.getTypeScriptVersion = getTypeScriptVersion;
2278         function shouldLog(level) {
2279             return Debug.currentLogLevel <= level;
2280         }
2281         Debug.shouldLog = shouldLog;
2282         function logMessage(level, s) {
2283             if (Debug.loggingHost && shouldLog(level)) {
2284                 Debug.loggingHost.log(level, s);
2285             }
2286         }
2287         function log(s) {
2288             logMessage(LogLevel.Info, s);
2289         }
2290         Debug.log = log;
2291         (function (log_1) {
2292             function error(s) {
2293                 logMessage(LogLevel.Error, s);
2294             }
2295             log_1.error = error;
2296             function warn(s) {
2297                 logMessage(LogLevel.Warning, s);
2298             }
2299             log_1.warn = warn;
2300             function log(s) {
2301                 logMessage(LogLevel.Info, s);
2302             }
2303             log_1.log = log;
2304             function trace(s) {
2305                 logMessage(LogLevel.Verbose, s);
2306             }
2307             log_1.trace = trace;
2308         })(log = Debug.log || (Debug.log = {}));
2309         var assertionCache = {};
2310         function getAssertionLevel() {
2311             return currentAssertionLevel;
2312         }
2313         Debug.getAssertionLevel = getAssertionLevel;
2314         function setAssertionLevel(level) {
2315             var prevAssertionLevel = currentAssertionLevel;
2316             currentAssertionLevel = level;
2317             if (level > prevAssertionLevel) {
2318                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2319                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2320                     var key = _a[_i];
2321                     var cachedFunc = assertionCache[key];
2322                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2323                         Debug[key] = cachedFunc;
2324                         assertionCache[key] = undefined;
2325                     }
2326                 }
2327             }
2328         }
2329         Debug.setAssertionLevel = setAssertionLevel;
2330         function shouldAssert(level) {
2331             return currentAssertionLevel >= level;
2332         }
2333         Debug.shouldAssert = shouldAssert;
2334         /**
2335          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2336          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2337          * @param level The minimum assertion level required.
2338          * @param name The name of the current assertion function.
2339          */
2340         function shouldAssertFunction(level, name) {
2341             if (!shouldAssert(level)) {
2342                 assertionCache[name] = { level: level, assertion: Debug[name] };
2343                 Debug[name] = ts.noop;
2344                 return false;
2345             }
2346             return true;
2347         }
2348         function fail(message, stackCrawlMark) {
2349             debugger;
2350             var e = new Error(message ? "Debug Failure. ".concat(message) : "Debug Failure.");
2351             if (Error.captureStackTrace) {
2352                 Error.captureStackTrace(e, stackCrawlMark || fail);
2353             }
2354             throw e;
2355         }
2356         Debug.fail = fail;
2357         function failBadSyntaxKind(node, message, stackCrawlMark) {
2358             return fail("".concat(message || "Unexpected node.", "\r\nNode ").concat(formatSyntaxKind(node.kind), " was unexpected."), stackCrawlMark || failBadSyntaxKind);
2359         }
2360         Debug.failBadSyntaxKind = failBadSyntaxKind;
2361         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2362             if (!expression) {
2363                 message = message ? "False expression: ".concat(message) : "False expression.";
2364                 if (verboseDebugInfo) {
2365                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2366                 }
2367                 fail(message, stackCrawlMark || assert);
2368             }
2369         }
2370         Debug.assert = assert;
2371         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2372             if (a !== b) {
2373                 var message = msg ? msg2 ? "".concat(msg, " ").concat(msg2) : msg : "";
2374                 fail("Expected ".concat(a, " === ").concat(b, ". ").concat(message), stackCrawlMark || assertEqual);
2375             }
2376         }
2377         Debug.assertEqual = assertEqual;
2378         function assertLessThan(a, b, msg, stackCrawlMark) {
2379             if (a >= b) {
2380                 fail("Expected ".concat(a, " < ").concat(b, ". ").concat(msg || ""), stackCrawlMark || assertLessThan);
2381             }
2382         }
2383         Debug.assertLessThan = assertLessThan;
2384         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2385             if (a > b) {
2386                 fail("Expected ".concat(a, " <= ").concat(b), stackCrawlMark || assertLessThanOrEqual);
2387             }
2388         }
2389         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2390         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2391             if (a < b) {
2392                 fail("Expected ".concat(a, " >= ").concat(b), stackCrawlMark || assertGreaterThanOrEqual);
2393             }
2394         }
2395         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2396         function assertIsDefined(value, message, stackCrawlMark) {
2397             // eslint-disable-next-line no-null/no-null
2398             if (value === undefined || value === null) {
2399                 fail(message, stackCrawlMark || assertIsDefined);
2400             }
2401         }
2402         Debug.assertIsDefined = assertIsDefined;
2403         function checkDefined(value, message, stackCrawlMark) {
2404             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2405             return value;
2406         }
2407         Debug.checkDefined = checkDefined;
2408         /**
2409          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2410          * a value is defined at the statement level.
2411          */
2412         Debug.assertDefined = checkDefined;
2413         function assertEachIsDefined(value, message, stackCrawlMark) {
2414             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2415                 var v = value_1[_i];
2416                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2417             }
2418         }
2419         Debug.assertEachIsDefined = assertEachIsDefined;
2420         function checkEachDefined(value, message, stackCrawlMark) {
2421             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2422             return value;
2423         }
2424         Debug.checkEachDefined = checkEachDefined;
2425         /**
2426          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2427          * the elements of an array are defined at the statement level.
2428          */
2429         Debug.assertEachDefined = checkEachDefined;
2430         function assertNever(member, message, stackCrawlMark) {
2431             if (message === void 0) { message = "Illegal value:"; }
2432             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2433             return fail("".concat(message, " ").concat(detail), stackCrawlMark || assertNever);
2434         }
2435         Debug.assertNever = assertNever;
2436         function assertEachNode(nodes, test, message, stackCrawlMark) {
2437             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2438                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '".concat(getFunctionName(test), "'."); }, stackCrawlMark || assertEachNode);
2439             }
2440         }
2441         Debug.assertEachNode = assertEachNode;
2442         function assertNode(node, test, message, stackCrawlMark) {
2443             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2444                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNode);
2445             }
2446         }
2447         Debug.assertNode = assertNode;
2448         function assertNotNode(node, test, message, stackCrawlMark) {
2449             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2450                 assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " should not have passed test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNotNode);
2451             }
2452         }
2453         Debug.assertNotNode = assertNotNode;
2454         function assertOptionalNode(node, test, message, stackCrawlMark) {
2455             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2456                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertOptionalNode);
2457             }
2458         }
2459         Debug.assertOptionalNode = assertOptionalNode;
2460         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2461             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2462                 assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " was not a '").concat(formatSyntaxKind(kind), "' token."); }, stackCrawlMark || assertOptionalToken);
2463             }
2464         }
2465         Debug.assertOptionalToken = assertOptionalToken;
2466         function assertMissingNode(node, message, stackCrawlMark) {
2467             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2468                 assert(node === undefined, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " was unexpected'."); }, stackCrawlMark || assertMissingNode);
2469             }
2470         }
2471         Debug.assertMissingNode = assertMissingNode;
2472         function type(_value) { }
2473         Debug.type = type;
2474         function getFunctionName(func) {
2475             if (typeof func !== "function") {
2476                 return "";
2477             }
2478             else if (func.hasOwnProperty("name")) {
2479                 return func.name;
2480             }
2481             else {
2482                 var text = Function.prototype.toString.call(func);
2483                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2484                 return match ? match[1] : "";
2485             }
2486         }
2487         Debug.getFunctionName = getFunctionName;
2488         function formatSymbol(symbol) {
2489             return "{ name: ".concat(ts.unescapeLeadingUnderscores(symbol.escapedName), "; flags: ").concat(formatSymbolFlags(symbol.flags), "; declarations: ").concat(ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }), " }");
2490         }
2491         Debug.formatSymbol = formatSymbol;
2492         /**
2493          * Formats an enum value as a string for debugging and debug assertions.
2494          */
2495         function formatEnum(value, enumObject, isFlags) {
2496             if (value === void 0) { value = 0; }
2497             var members = getEnumMembers(enumObject);
2498             if (value === 0) {
2499                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2500             }
2501             if (isFlags) {
2502                 var result = "";
2503                 var remainingFlags = value;
2504                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2505                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2506                     if (enumValue > value) {
2507                         break;
2508                     }
2509                     if (enumValue !== 0 && enumValue & value) {
2510                         result = "".concat(result).concat(result ? "|" : "").concat(enumName);
2511                         remainingFlags &= ~enumValue;
2512                     }
2513                 }
2514                 if (remainingFlags === 0) {
2515                     return result;
2516                 }
2517             }
2518             else {
2519                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2520                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2521                     if (enumValue === value) {
2522                         return enumName;
2523                     }
2524                 }
2525             }
2526             return value.toString();
2527         }
2528         Debug.formatEnum = formatEnum;
2529         function getEnumMembers(enumObject) {
2530             var result = [];
2531             for (var name in enumObject) {
2532                 var value = enumObject[name];
2533                 if (typeof value === "number") {
2534                     result.push([value, name]);
2535                 }
2536             }
2537             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2538         }
2539         function formatSyntaxKind(kind) {
2540             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2541         }
2542         Debug.formatSyntaxKind = formatSyntaxKind;
2543         function formatSnippetKind(kind) {
2544             return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false);
2545         }
2546         Debug.formatSnippetKind = formatSnippetKind;
2547         function formatNodeFlags(flags) {
2548             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2549         }
2550         Debug.formatNodeFlags = formatNodeFlags;
2551         function formatModifierFlags(flags) {
2552             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2553         }
2554         Debug.formatModifierFlags = formatModifierFlags;
2555         function formatTransformFlags(flags) {
2556             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2557         }
2558         Debug.formatTransformFlags = formatTransformFlags;
2559         function formatEmitFlags(flags) {
2560             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2561         }
2562         Debug.formatEmitFlags = formatEmitFlags;
2563         function formatSymbolFlags(flags) {
2564             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2565         }
2566         Debug.formatSymbolFlags = formatSymbolFlags;
2567         function formatTypeFlags(flags) {
2568             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2569         }
2570         Debug.formatTypeFlags = formatTypeFlags;
2571         function formatSignatureFlags(flags) {
2572             return formatEnum(flags, ts.SignatureFlags, /*isFlags*/ true);
2573         }
2574         Debug.formatSignatureFlags = formatSignatureFlags;
2575         function formatObjectFlags(flags) {
2576             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2577         }
2578         Debug.formatObjectFlags = formatObjectFlags;
2579         function formatFlowFlags(flags) {
2580             return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true);
2581         }
2582         Debug.formatFlowFlags = formatFlowFlags;
2583         var isDebugInfoEnabled = false;
2584         var extendedDebugModule;
2585         function extendedDebug() {
2586             enableDebugInfo();
2587             if (!extendedDebugModule) {
2588                 throw new Error("Debugging helpers could not be loaded.");
2589             }
2590             return extendedDebugModule;
2591         }
2592         function printControlFlowGraph(flowNode) {
2593             return console.log(formatControlFlowGraph(flowNode));
2594         }
2595         Debug.printControlFlowGraph = printControlFlowGraph;
2596         function formatControlFlowGraph(flowNode) {
2597             return extendedDebug().formatControlFlowGraph(flowNode);
2598         }
2599         Debug.formatControlFlowGraph = formatControlFlowGraph;
2600         var flowNodeProto;
2601         function attachFlowNodeDebugInfoWorker(flowNode) {
2602             if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2603                 Object.defineProperties(flowNode, {
2604                     // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2605                     __tsDebuggerDisplay: {
2606                         value: function () {
2607                             var flowHeader = this.flags & 2 /* Start */ ? "FlowStart" :
2608                                 this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" :
2609                                     this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" :
2610                                         this.flags & 16 /* Assignment */ ? "FlowAssignment" :
2611                                             this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" :
2612                                                 this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" :
2613                                                     this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" :
2614                                                         this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" :
2615                                                             this.flags & 512 /* Call */ ? "FlowCall" :
2616                                                                 this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" :
2617                                                                     this.flags & 1 /* Unreachable */ ? "FlowUnreachable" :
2618                                                                         "UnknownFlow";
2619                             var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1);
2620                             return "".concat(flowHeader).concat(remainingFlags ? " (".concat(formatFlowFlags(remainingFlags), ")") : "");
2621                         }
2622                     },
2623                     __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2624                     __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2625                 });
2626             }
2627         }
2628         function attachFlowNodeDebugInfo(flowNode) {
2629             if (isDebugInfoEnabled) {
2630                 if (typeof Object.setPrototypeOf === "function") {
2631                     // if we're in es2015, attach the method to a shared prototype for `FlowNode`
2632                     // so the method doesn't show up in the watch window.
2633                     if (!flowNodeProto) {
2634                         flowNodeProto = Object.create(Object.prototype);
2635                         attachFlowNodeDebugInfoWorker(flowNodeProto);
2636                     }
2637                     Object.setPrototypeOf(flowNode, flowNodeProto);
2638                 }
2639                 else {
2640                     // not running in an es2015 environment, attach the method directly.
2641                     attachFlowNodeDebugInfoWorker(flowNode);
2642                 }
2643             }
2644         }
2645         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2646         var nodeArrayProto;
2647         function attachNodeArrayDebugInfoWorker(array) {
2648             if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
2649                 Object.defineProperties(array, {
2650                     __tsDebuggerDisplay: {
2651                         value: function (defaultValue) {
2652                             // An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
2653                             // these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
2654                             // formatted string.
2655                             // This regex can trigger slow backtracking because of overlapping potential captures.
2656                             // We don't care, this is debug code that's only enabled with a debugger attached -
2657                             // we're just taking note of it for anyone checking regex performance in the future.
2658                             defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
2659                             return "NodeArray ".concat(defaultValue);
2660                         }
2661                     }
2662                 });
2663             }
2664         }
2665         function attachNodeArrayDebugInfo(array) {
2666             if (isDebugInfoEnabled) {
2667                 if (typeof Object.setPrototypeOf === "function") {
2668                     // if we're in es2015, attach the method to a shared prototype for `NodeArray`
2669                     // so the method doesn't show up in the watch window.
2670                     if (!nodeArrayProto) {
2671                         nodeArrayProto = Object.create(Array.prototype);
2672                         attachNodeArrayDebugInfoWorker(nodeArrayProto);
2673                     }
2674                     Object.setPrototypeOf(array, nodeArrayProto);
2675                 }
2676                 else {
2677                     // not running in an es2015 environment, attach the method directly.
2678                     attachNodeArrayDebugInfoWorker(array);
2679                 }
2680             }
2681         }
2682         Debug.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo;
2683         /**
2684          * Injects debug information into frequently used types.
2685          */
2686         function enableDebugInfo() {
2687             if (isDebugInfoEnabled)
2688                 return;
2689             // avoid recomputing
2690             var weakTypeTextMap;
2691             var weakNodeTextMap;
2692             function getWeakTypeTextMap() {
2693                 if (weakTypeTextMap === undefined) {
2694                     if (typeof WeakMap === "function")
2695                         weakTypeTextMap = new WeakMap();
2696                 }
2697                 return weakTypeTextMap;
2698             }
2699             function getWeakNodeTextMap() {
2700                 if (weakNodeTextMap === undefined) {
2701                     if (typeof WeakMap === "function")
2702                         weakNodeTextMap = new WeakMap();
2703                 }
2704                 return weakNodeTextMap;
2705             }
2706             // Add additional properties in debug mode to assist with debugging.
2707             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2708                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2709                 __tsDebuggerDisplay: {
2710                     value: function () {
2711                         var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" :
2712                             "Symbol";
2713                         var remainingSymbolFlags = this.flags & ~33554432 /* Transient */;
2714                         return "".concat(symbolHeader, " '").concat(ts.symbolName(this), "'").concat(remainingSymbolFlags ? " (".concat(formatSymbolFlags(remainingSymbolFlags), ")") : "");
2715                     }
2716                 },
2717                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2718             });
2719             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2720                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2721                 __tsDebuggerDisplay: {
2722                     value: function () {
2723                         var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" :
2724                             this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType ".concat(JSON.stringify(this.value)) :
2725                                 this.flags & 2048 /* BigIntLiteral */ ? "LiteralType ".concat(this.value.negative ? "-" : "").concat(this.value.base10Value, "n") :
2726                                     this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" :
2727                                         this.flags & 32 /* Enum */ ? "EnumType" :
2728                                             this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType ".concat(this.intrinsicName) :
2729                                                 this.flags & 1048576 /* Union */ ? "UnionType" :
2730                                                     this.flags & 2097152 /* Intersection */ ? "IntersectionType" :
2731                                                         this.flags & 4194304 /* Index */ ? "IndexType" :
2732                                                             this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" :
2733                                                                 this.flags & 16777216 /* Conditional */ ? "ConditionalType" :
2734                                                                     this.flags & 33554432 /* Substitution */ ? "SubstitutionType" :
2735                                                                         this.flags & 262144 /* TypeParameter */ ? "TypeParameter" :
2736                                                                             this.flags & 524288 /* Object */ ?
2737                                                                                 this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" :
2738                                                                                     this.objectFlags & 4 /* Reference */ ? "TypeReference" :
2739                                                                                         this.objectFlags & 8 /* Tuple */ ? "TupleType" :
2740                                                                                             this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" :
2741                                                                                                 this.objectFlags & 32 /* Mapped */ ? "MappedType" :
2742                                                                                                     this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" :
2743                                                                                                         this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" :
2744                                                                                                             "ObjectType" :
2745                                                                                 "Type";
2746                         var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0;
2747                         return "".concat(typeHeader).concat(this.symbol ? " '".concat(ts.symbolName(this.symbol), "'") : "").concat(remainingObjectFlags ? " (".concat(formatObjectFlags(remainingObjectFlags), ")") : "");
2748                     }
2749                 },
2750                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2751                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2752                 __debugTypeToString: {
2753                     value: function () {
2754                         // avoid recomputing
2755                         var map = getWeakTypeTextMap();
2756                         var text = map === null || map === void 0 ? void 0 : map.get(this);
2757                         if (text === undefined) {
2758                             text = this.checker.typeToString(this);
2759                             map === null || map === void 0 ? void 0 : map.set(this, text);
2760                         }
2761                         return text;
2762                     }
2763                 },
2764             });
2765             Object.defineProperties(ts.objectAllocator.getSignatureConstructor().prototype, {
2766                 __debugFlags: { get: function () { return formatSignatureFlags(this.flags); } },
2767                 __debugSignatureToString: { value: function () { var _a; return (_a = this.checker) === null || _a === void 0 ? void 0 : _a.signatureToString(this); } }
2768             });
2769             var nodeConstructors = [
2770                 ts.objectAllocator.getNodeConstructor(),
2771                 ts.objectAllocator.getIdentifierConstructor(),
2772                 ts.objectAllocator.getTokenConstructor(),
2773                 ts.objectAllocator.getSourceFileConstructor()
2774             ];
2775             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2776                 var ctor = nodeConstructors_1[_i];
2777                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2778                     Object.defineProperties(ctor.prototype, {
2779                         // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2780                         __tsDebuggerDisplay: {
2781                             value: function () {
2782                                 var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
2783                                     ts.isIdentifier(this) ? "Identifier '".concat(ts.idText(this), "'") :
2784                                         ts.isPrivateIdentifier(this) ? "PrivateIdentifier '".concat(ts.idText(this), "'") :
2785                                             ts.isStringLiteral(this) ? "StringLiteral ".concat(JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")) :
2786                                                 ts.isNumericLiteral(this) ? "NumericLiteral ".concat(this.text) :
2787                                                     ts.isBigIntLiteral(this) ? "BigIntLiteral ".concat(this.text, "n") :
2788                                                         ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
2789                                                             ts.isParameter(this) ? "ParameterDeclaration" :
2790                                                                 ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" :
2791                                                                     ts.isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
2792                                                                         ts.isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
2793                                                                             ts.isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
2794                                                                                 ts.isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
2795                                                                                     ts.isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
2796                                                                                         ts.isTypePredicateNode(this) ? "TypePredicateNode" :
2797                                                                                             ts.isTypeReferenceNode(this) ? "TypeReferenceNode" :
2798                                                                                                 ts.isFunctionTypeNode(this) ? "FunctionTypeNode" :
2799                                                                                                     ts.isConstructorTypeNode(this) ? "ConstructorTypeNode" :
2800                                                                                                         ts.isTypeQueryNode(this) ? "TypeQueryNode" :
2801                                                                                                             ts.isTypeLiteralNode(this) ? "TypeLiteralNode" :
2802                                                                                                                 ts.isArrayTypeNode(this) ? "ArrayTypeNode" :
2803                                                                                                                     ts.isTupleTypeNode(this) ? "TupleTypeNode" :
2804                                                                                                                         ts.isOptionalTypeNode(this) ? "OptionalTypeNode" :
2805                                                                                                                             ts.isRestTypeNode(this) ? "RestTypeNode" :
2806                                                                                                                                 ts.isUnionTypeNode(this) ? "UnionTypeNode" :
2807                                                                                                                                     ts.isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
2808                                                                                                                                         ts.isConditionalTypeNode(this) ? "ConditionalTypeNode" :
2809                                                                                                                                             ts.isInferTypeNode(this) ? "InferTypeNode" :
2810                                                                                                                                                 ts.isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
2811                                                                                                                                                     ts.isThisTypeNode(this) ? "ThisTypeNode" :
2812                                                                                                                                                         ts.isTypeOperatorNode(this) ? "TypeOperatorNode" :
2813                                                                                                                                                             ts.isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
2814                                                                                                                                                                 ts.isMappedTypeNode(this) ? "MappedTypeNode" :
2815                                                                                                                                                                     ts.isLiteralTypeNode(this) ? "LiteralTypeNode" :
2816                                                                                                                                                                         ts.isNamedTupleMember(this) ? "NamedTupleMember" :
2817                                                                                                                                                                             ts.isImportTypeNode(this) ? "ImportTypeNode" :
2818                                                                                                                                                                                 formatSyntaxKind(this.kind);
2819                                 return "".concat(nodeHeader).concat(this.flags ? " (".concat(formatNodeFlags(this.flags), ")") : "");
2820                             }
2821                         },
2822                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2823                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2824                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
2825                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2826                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2827                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2828                         __debugGetText: {
2829                             value: function (includeTrivia) {
2830                                 if (ts.nodeIsSynthesized(this))
2831                                     return "";
2832                                 // avoid recomputing
2833                                 var map = getWeakNodeTextMap();
2834                                 var text = map === null || map === void 0 ? void 0 : map.get(this);
2835                                 if (text === undefined) {
2836                                     var parseNode = ts.getParseTreeNode(this);
2837                                     var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2838                                     text = sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2839                                     map === null || map === void 0 ? void 0 : map.set(this, text);
2840                                 }
2841                                 return text;
2842                             }
2843                         }
2844                     });
2845                 }
2846             }
2847             // attempt to load extended debugging information
2848             try {
2849                 if (ts.sys && ts.sys.require) {
2850                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2851                     var result = ts.sys.require(basePath, "./compiler-debug");
2852                     if (!result.error) {
2853                         result.module.init(ts);
2854                         extendedDebugModule = result.module;
2855                     }
2856                 }
2857             }
2858             catch (_a) {
2859                 // do nothing
2860             }
2861             isDebugInfoEnabled = true;
2862         }
2863         Debug.enableDebugInfo = enableDebugInfo;
2864         function formatDeprecationMessage(name, error, errorAfter, since, message) {
2865             var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
2866             deprecationMessage += "'".concat(name, "' ");
2867             deprecationMessage += since ? "has been deprecated since v".concat(since) : "is deprecated";
2868             deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v".concat(errorAfter, ".") : ".";
2869             deprecationMessage += message ? " ".concat(ts.formatStringFromArgs(message, [name], 0)) : "";
2870             return deprecationMessage;
2871         }
2872         function createErrorDeprecation(name, errorAfter, since, message) {
2873             var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
2874             return function () {
2875                 throw new TypeError(deprecationMessage);
2876             };
2877         }
2878         function createWarningDeprecation(name, errorAfter, since, message) {
2879             var hasWrittenDeprecation = false;
2880             return function () {
2881                 if (!hasWrittenDeprecation) {
2882                     log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
2883                     hasWrittenDeprecation = true;
2884                 }
2885             };
2886         }
2887         function createDeprecation(name, options) {
2888             var _a, _b;
2889             if (options === void 0) { options = {}; }
2890             var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
2891             var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
2892             var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
2893             var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
2894             var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
2895             var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
2896             return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
2897                 warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
2898                     ts.noop;
2899         }
2900         function wrapFunction(deprecation, func) {
2901             return function () {
2902                 deprecation();
2903                 return func.apply(this, arguments);
2904             };
2905         }
2906         function deprecate(func, options) {
2907             var deprecation = createDeprecation(getFunctionName(func), options);
2908             return wrapFunction(deprecation, func);
2909         }
2910         Debug.deprecate = deprecate;
2911     })(Debug = ts.Debug || (ts.Debug = {}));
2912 })(ts || (ts = {}));
2913 /* @internal */
2914 var ts;
2915 (function (ts) {
2916     // https://semver.org/#spec-item-2
2917     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2918     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2919     // > version, and Z is the patch version. Each element MUST increase numerically.
2920     //
2921     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2922     // value of `0`.
2923     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2924     // https://semver.org/#spec-item-9
2925     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2926     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2927     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2928     // > MUST NOT include leading zeroes.
2929     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2930     // https://semver.org/#spec-item-10
2931     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2932     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2933     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2934     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2935     // https://semver.org/#spec-item-9
2936     // > Numeric identifiers MUST NOT include leading zeroes.
2937     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2938     /**
2939      * Describes a precise semantic version number, https://semver.org
2940      */
2941     var Version = /** @class */ (function () {
2942         function Version(major, minor, patch, prerelease, build) {
2943             if (minor === void 0) { minor = 0; }
2944             if (patch === void 0) { patch = 0; }
2945             if (prerelease === void 0) { prerelease = ""; }
2946             if (build === void 0) { build = ""; }
2947             if (typeof major === "string") {
2948                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2949                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2950             }
2951             ts.Debug.assert(major >= 0, "Invalid argument: major");
2952             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2953             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2954             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2955             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2956             this.major = major;
2957             this.minor = minor;
2958             this.patch = patch;
2959             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2960             this.build = build ? build.split(".") : ts.emptyArray;
2961         }
2962         Version.tryParse = function (text) {
2963             var result = tryParseComponents(text);
2964             if (!result)
2965                 return undefined;
2966             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2967             return new Version(major, minor, patch, prerelease, build);
2968         };
2969         Version.prototype.compareTo = function (other) {
2970             // https://semver.org/#spec-item-11
2971             // > Precedence is determined by the first difference when comparing each of these
2972             // > identifiers from left to right as follows: Major, minor, and patch versions are
2973             // > always compared numerically.
2974             //
2975             // https://semver.org/#spec-item-11
2976             // > Precedence for two pre-release versions with the same major, minor, and patch version
2977             // > MUST be determined by comparing each dot separated identifier from left to right until
2978             // > a difference is found [...]
2979             //
2980             // https://semver.org/#spec-item-11
2981             // > Build metadata does not figure into precedence
2982             if (this === other)
2983                 return 0 /* EqualTo */;
2984             if (other === undefined)
2985                 return 1 /* GreaterThan */;
2986             return ts.compareValues(this.major, other.major)
2987                 || ts.compareValues(this.minor, other.minor)
2988                 || ts.compareValues(this.patch, other.patch)
2989                 || comparePrereleaseIdentifiers(this.prerelease, other.prerelease);
2990         };
2991         Version.prototype.increment = function (field) {
2992             switch (field) {
2993                 case "major": return new Version(this.major + 1, 0, 0);
2994                 case "minor": return new Version(this.major, this.minor + 1, 0);
2995                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2996                 default: return ts.Debug.assertNever(field);
2997             }
2998         };
2999         Version.prototype.toString = function () {
3000             var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch);
3001             if (ts.some(this.prerelease))
3002                 result += "-".concat(this.prerelease.join("."));
3003             if (ts.some(this.build))
3004                 result += "+".concat(this.build.join("."));
3005             return result;
3006         };
3007         Version.zero = new Version(0, 0, 0);
3008         return Version;
3009     }());
3010     ts.Version = Version;
3011     function tryParseComponents(text) {
3012         var match = versionRegExp.exec(text);
3013         if (!match)
3014             return undefined;
3015         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;
3016         if (prerelease && !prereleaseRegExp.test(prerelease))
3017             return undefined;
3018         if (build && !buildRegExp.test(build))
3019             return undefined;
3020         return {
3021             major: parseInt(major, 10),
3022             minor: parseInt(minor, 10),
3023             patch: parseInt(patch, 10),
3024             prerelease: prerelease,
3025             build: build
3026         };
3027     }
3028     function comparePrereleaseIdentifiers(left, right) {
3029         // https://semver.org/#spec-item-11
3030         // > When major, minor, and patch are equal, a pre-release version has lower precedence
3031         // > than a normal version.
3032         if (left === right)
3033             return 0 /* EqualTo */;
3034         if (left.length === 0)
3035             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
3036         if (right.length === 0)
3037             return -1 /* LessThan */;
3038         // https://semver.org/#spec-item-11
3039         // > Precedence for two pre-release versions with the same major, minor, and patch version
3040         // > MUST be determined by comparing each dot separated identifier from left to right until
3041         // > a difference is found [...]
3042         var length = Math.min(left.length, right.length);
3043         for (var i = 0; i < length; i++) {
3044             var leftIdentifier = left[i];
3045             var rightIdentifier = right[i];
3046             if (leftIdentifier === rightIdentifier)
3047                 continue;
3048             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
3049             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
3050             if (leftIsNumeric || rightIsNumeric) {
3051                 // https://semver.org/#spec-item-11
3052                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
3053                 if (leftIsNumeric !== rightIsNumeric)
3054                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
3055                 // https://semver.org/#spec-item-11
3056                 // > identifiers consisting of only digits are compared numerically
3057                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
3058                 if (result)
3059                     return result;
3060             }
3061             else {
3062                 // https://semver.org/#spec-item-11
3063                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
3064                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
3065                 if (result)
3066                     return result;
3067             }
3068         }
3069         // https://semver.org/#spec-item-11
3070         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
3071         // > of the preceding identifiers are equal.
3072         return ts.compareValues(left.length, right.length);
3073     }
3074     /**
3075      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
3076      */
3077     var VersionRange = /** @class */ (function () {
3078         function VersionRange(spec) {
3079             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
3080         }
3081         VersionRange.tryParse = function (text) {
3082             var sets = parseRange(text);
3083             if (sets) {
3084                 var range = new VersionRange("");
3085                 range._alternatives = sets;
3086                 return range;
3087             }
3088             return undefined;
3089         };
3090         VersionRange.prototype.test = function (version) {
3091             if (typeof version === "string")
3092                 version = new Version(version);
3093             return testDisjunction(version, this._alternatives);
3094         };
3095         VersionRange.prototype.toString = function () {
3096             return formatDisjunction(this._alternatives);
3097         };
3098         return VersionRange;
3099     }());
3100     ts.VersionRange = VersionRange;
3101     // https://github.com/npm/node-semver#range-grammar
3102     //
3103     // range-set    ::= range ( logical-or range ) *
3104     // range        ::= hyphen | simple ( ' ' simple ) * | ''
3105     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
3106     var logicalOrRegExp = /\|\|/g;
3107     var whitespaceRegExp = /\s+/g;
3108     // https://github.com/npm/node-semver#range-grammar
3109     //
3110     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
3111     // xr           ::= 'x' | 'X' | '*' | nr
3112     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
3113     // qualifier    ::= ( '-' pre )? ( '+' build )?
3114     // pre          ::= parts
3115     // build        ::= parts
3116     // parts        ::= part ( '.' part ) *
3117     // part         ::= nr | [-0-9A-Za-z]+
3118     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
3119     // https://github.com/npm/node-semver#range-grammar
3120     //
3121     // hyphen       ::= partial ' - ' partial
3122     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
3123     // https://github.com/npm/node-semver#range-grammar
3124     //
3125     // simple       ::= primitive | partial | tilde | caret
3126     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
3127     // tilde        ::= '~' partial
3128     // caret        ::= '^' partial
3129     var rangeRegExp = /^(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
3130     function parseRange(text) {
3131         var alternatives = [];
3132         for (var _i = 0, _a = ts.trimString(text).split(logicalOrRegExp); _i < _a.length; _i++) {
3133             var range = _a[_i];
3134             if (!range)
3135                 continue;
3136             var comparators = [];
3137             range = ts.trimString(range);
3138             var match = hyphenRegExp.exec(range);
3139             if (match) {
3140                 if (!parseHyphen(match[1], match[2], comparators))
3141                     return undefined;
3142             }
3143             else {
3144                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
3145                     var simple = _c[_b];
3146                     var match_1 = rangeRegExp.exec(ts.trimString(simple));
3147                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
3148                         return undefined;
3149                 }
3150             }
3151             alternatives.push(comparators);
3152         }
3153         return alternatives;
3154     }
3155     function parsePartial(text) {
3156         var match = partialRegExp.exec(text);
3157         if (!match)
3158             return undefined;
3159         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];
3160         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);
3161         return { version: version, major: major, minor: minor, patch: patch };
3162     }
3163     function parseHyphen(left, right, comparators) {
3164         var leftResult = parsePartial(left);
3165         if (!leftResult)
3166             return false;
3167         var rightResult = parsePartial(right);
3168         if (!rightResult)
3169             return false;
3170         if (!isWildcard(leftResult.major)) {
3171             comparators.push(createComparator(">=", leftResult.version));
3172         }
3173         if (!isWildcard(rightResult.major)) {
3174             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
3175                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
3176                     createComparator("<=", rightResult.version));
3177         }
3178         return true;
3179     }
3180     function parseComparator(operator, text, comparators) {
3181         var result = parsePartial(text);
3182         if (!result)
3183             return false;
3184         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
3185         if (!isWildcard(major)) {
3186             switch (operator) {
3187                 case "~":
3188                     comparators.push(createComparator(">=", version));
3189                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
3190                         "minor")));
3191                     break;
3192                 case "^":
3193                     comparators.push(createComparator(">=", version));
3194                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
3195                         version.minor > 0 || isWildcard(patch) ? "minor" :
3196                             "patch")));
3197                     break;
3198                 case "<":
3199                 case ">=":
3200                     comparators.push(createComparator(operator, version));
3201                     break;
3202                 case "<=":
3203                 case ">":
3204                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3205                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3206                             createComparator(operator, version));
3207                     break;
3208                 case "=":
3209                 case undefined:
3210                     if (isWildcard(minor) || isWildcard(patch)) {
3211                         comparators.push(createComparator(">=", version));
3212                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3213                     }
3214                     else {
3215                         comparators.push(createComparator("=", version));
3216                     }
3217                     break;
3218                 default:
3219                     // unrecognized
3220                     return false;
3221             }
3222         }
3223         else if (operator === "<" || operator === ">") {
3224             comparators.push(createComparator("<", Version.zero));
3225         }
3226         return true;
3227     }
3228     function isWildcard(part) {
3229         return part === "*" || part === "x" || part === "X";
3230     }
3231     function createComparator(operator, operand) {
3232         return { operator: operator, operand: operand };
3233     }
3234     function testDisjunction(version, alternatives) {
3235         // an empty disjunction is treated as "*" (all versions)
3236         if (alternatives.length === 0)
3237             return true;
3238         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3239             var alternative = alternatives_1[_i];
3240             if (testAlternative(version, alternative))
3241                 return true;
3242         }
3243         return false;
3244     }
3245     function testAlternative(version, comparators) {
3246         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3247             var comparator = comparators_1[_i];
3248             if (!testComparator(version, comparator.operator, comparator.operand))
3249                 return false;
3250         }
3251         return true;
3252     }
3253     function testComparator(version, operator, operand) {
3254         var cmp = version.compareTo(operand);
3255         switch (operator) {
3256             case "<": return cmp < 0;
3257             case "<=": return cmp <= 0;
3258             case ">": return cmp > 0;
3259             case ">=": return cmp >= 0;
3260             case "=": return cmp === 0;
3261             default: return ts.Debug.assertNever(operator);
3262         }
3263     }
3264     function formatDisjunction(alternatives) {
3265         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3266     }
3267     function formatAlternative(comparators) {
3268         return ts.map(comparators, formatComparator).join(" ");
3269     }
3270     function formatComparator(comparator) {
3271         return "".concat(comparator.operator).concat(comparator.operand);
3272     }
3273 })(ts || (ts = {}));
3274 /*@internal*/
3275 var ts;
3276 (function (ts) {
3277     // The following definitions provide the minimum compatible support for the Web Performance User Timings API
3278     // between browsers and NodeJS:
3279     // eslint-disable-next-line @typescript-eslint/naming-convention
3280     function hasRequiredAPI(performance, PerformanceObserver) {
3281         return typeof performance === "object" &&
3282             typeof performance.timeOrigin === "number" &&
3283             typeof performance.mark === "function" &&
3284             typeof performance.measure === "function" &&
3285             typeof performance.now === "function" &&
3286             typeof PerformanceObserver === "function";
3287     }
3288     function tryGetWebPerformanceHooks() {
3289         if (typeof performance === "object" &&
3290             typeof PerformanceObserver === "function" &&
3291             hasRequiredAPI(performance, PerformanceObserver)) {
3292             return {
3293                 // For now we always write native performance events when running in the browser. We may
3294                 // make this conditional in the future if we find that native web performance hooks
3295                 // in the browser also slow down compilation.
3296                 shouldWriteNativeEvents: true,
3297                 performance: performance,
3298                 PerformanceObserver: PerformanceObserver
3299             };
3300         }
3301     }
3302     function tryGetNodePerformanceHooks() {
3303         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") {
3304             try {
3305                 var performance_1;
3306                 var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
3307                 if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) {
3308                     performance_1 = nodePerformance_1;
3309                     // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
3310                     // match the Web Performance API specification. Node's implementation did not allow
3311                     // optional `start` and `end` arguments for `performance.measure`.
3312                     // See https://github.com/nodejs/node/pull/32651 for more information.
3313                     var version_1 = new ts.Version(process.versions.node);
3314                     var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
3315                     if (range.test(version_1)) {
3316                         performance_1 = {
3317                             get timeOrigin() { return nodePerformance_1.timeOrigin; },
3318                             now: function () { return nodePerformance_1.now(); },
3319                             mark: function (name) { return nodePerformance_1.mark(name); },
3320                             measure: function (name, start, end) {
3321                                 if (start === void 0) { start = "nodeStart"; }
3322                                 if (end === undefined) {
3323                                     end = "__performance.measure-fix__";
3324                                     nodePerformance_1.mark(end);
3325                                 }
3326                                 nodePerformance_1.measure(name, start, end);
3327                                 if (end === "__performance.measure-fix__") {
3328                                     nodePerformance_1.clearMarks("__performance.measure-fix__");
3329                                 }
3330                             }
3331                         };
3332                     }
3333                     return {
3334                         // By default, only write native events when generating a cpu profile or using the v8 profiler.
3335                         shouldWriteNativeEvents: false,
3336                         performance: performance_1,
3337                         PerformanceObserver: PerformanceObserver_1
3338                     };
3339                 }
3340             }
3341             catch (_b) {
3342                 // ignore errors
3343             }
3344         }
3345     }
3346     // Unlike with the native Map/Set 'tryGet' functions in corePublic.ts, we eagerly evaluate these
3347     // since we will need them for `timestamp`, below.
3348     var nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks();
3349     var nativePerformance = nativePerformanceHooks === null || nativePerformanceHooks === void 0 ? void 0 : nativePerformanceHooks.performance;
3350     function tryGetNativePerformanceHooks() {
3351         return nativePerformanceHooks;
3352     }
3353     ts.tryGetNativePerformanceHooks = tryGetNativePerformanceHooks;
3354     /** Gets a timestamp with (at least) ms resolution */
3355     ts.timestamp = nativePerformance ? function () { return nativePerformance.now(); } :
3356         Date.now ? Date.now :
3357             function () { return +(new Date()); };
3358 })(ts || (ts = {}));
3359 /*@internal*/
3360 /** Performance measurements for the compiler. */
3361 var ts;
3362 (function (ts) {
3363     var performance;
3364     (function (performance) {
3365         var perfHooks;
3366         // when set, indicates the implementation of `Performance` to use for user timing.
3367         // when unset, indicates user timing is unavailable or disabled.
3368         var performanceImpl;
3369         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
3370             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
3371         }
3372         performance.createTimerIf = createTimerIf;
3373         function createTimer(measureName, startMarkName, endMarkName) {
3374             var enterCount = 0;
3375             return {
3376                 enter: enter,
3377                 exit: exit
3378             };
3379             function enter() {
3380                 if (++enterCount === 1) {
3381                     mark(startMarkName);
3382                 }
3383             }
3384             function exit() {
3385                 if (--enterCount === 0) {
3386                     mark(endMarkName);
3387                     measure(measureName, startMarkName, endMarkName);
3388                 }
3389                 else if (enterCount < 0) {
3390                     ts.Debug.fail("enter/exit count does not match.");
3391                 }
3392             }
3393         }
3394         performance.createTimer = createTimer;
3395         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
3396         var enabled = false;
3397         var timeorigin = ts.timestamp();
3398         var marks = new ts.Map();
3399         var counts = new ts.Map();
3400         var durations = new ts.Map();
3401         /**
3402          * Marks a performance event.
3403          *
3404          * @param markName The name of the mark.
3405          */
3406         function mark(markName) {
3407             var _a;
3408             if (enabled) {
3409                 var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0;
3410                 counts.set(markName, count + 1);
3411                 marks.set(markName, ts.timestamp());
3412                 performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
3413             }
3414         }
3415         performance.mark = mark;
3416         /**
3417          * Adds a performance measurement with the specified name.
3418          *
3419          * @param measureName The name of the performance measurement.
3420          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
3421          *      profiler was enabled is used.
3422          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
3423          *      used.
3424          */
3425         function measure(measureName, startMarkName, endMarkName) {
3426             var _a, _b;
3427             if (enabled) {
3428                 var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp();
3429                 var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin;
3430                 var previousDuration = durations.get(measureName) || 0;
3431                 durations.set(measureName, previousDuration + (end - start));
3432                 performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
3433             }
3434         }
3435         performance.measure = measure;
3436         /**
3437          * Gets the number of times a marker was encountered.
3438          *
3439          * @param markName The name of the mark.
3440          */
3441         function getCount(markName) {
3442             return counts.get(markName) || 0;
3443         }
3444         performance.getCount = getCount;
3445         /**
3446          * Gets the total duration of all measurements with the supplied name.
3447          *
3448          * @param measureName The name of the measure whose durations should be accumulated.
3449          */
3450         function getDuration(measureName) {
3451             return durations.get(measureName) || 0;
3452         }
3453         performance.getDuration = getDuration;
3454         /**
3455          * Iterate over each measure, performing some action
3456          *
3457          * @param cb The action to perform for each measure
3458          */
3459         function forEachMeasure(cb) {
3460             durations.forEach(function (duration, measureName) { return cb(measureName, duration); });
3461         }
3462         performance.forEachMeasure = forEachMeasure;
3463         /**
3464          * Indicates whether the performance API is enabled.
3465          */
3466         function isEnabled() {
3467             return enabled;
3468         }
3469         performance.isEnabled = isEnabled;
3470         /** Enables (and resets) performance measurements for the compiler. */
3471         function enable(system) {
3472             var _a;
3473             if (system === void 0) { system = ts.sys; }
3474             if (!enabled) {
3475                 enabled = true;
3476                 perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
3477                 if (perfHooks) {
3478                     timeorigin = perfHooks.performance.timeOrigin;
3479                     // NodeJS's Web Performance API is currently slower than expected, but we'd still like
3480                     // to be able to leverage native trace events when node is run with either `--cpu-prof`
3481                     // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when
3482                     // running in debug mode (since its possible to generate a cpu profile while debugging).
3483                     if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) {
3484                         performanceImpl = perfHooks.performance;
3485                     }
3486                 }
3487             }
3488             return true;
3489         }
3490         performance.enable = enable;
3491         /** Disables performance measurements for the compiler. */
3492         function disable() {
3493             if (enabled) {
3494                 marks.clear();
3495                 counts.clear();
3496                 durations.clear();
3497                 performanceImpl = undefined;
3498                 enabled = false;
3499             }
3500         }
3501         performance.disable = disable;
3502     })(performance = ts.performance || (ts.performance = {}));
3503 })(ts || (ts = {}));
3504 /* @internal */
3505 var ts;
3506 (function (ts) {
3507     var _a;
3508     var nullLogger = {
3509         logEvent: ts.noop,
3510         logErrEvent: ts.noop,
3511         logPerfEvent: ts.noop,
3512         logInfoEvent: ts.noop,
3513         logStartCommand: ts.noop,
3514         logStopCommand: ts.noop,
3515         logStartUpdateProgram: ts.noop,
3516         logStopUpdateProgram: ts.noop,
3517         logStartUpdateGraph: ts.noop,
3518         logStopUpdateGraph: ts.noop,
3519         logStartResolveModule: ts.noop,
3520         logStopResolveModule: ts.noop,
3521         logStartParseSourceFile: ts.noop,
3522         logStopParseSourceFile: ts.noop,
3523         logStartReadFile: ts.noop,
3524         logStopReadFile: ts.noop,
3525         logStartBindFile: ts.noop,
3526         logStopBindFile: ts.noop,
3527         logStartScheduledOperation: ts.noop,
3528         logStopScheduledOperation: ts.noop,
3529     };
3530     // Load optional module to enable Event Tracing for Windows
3531     // See https://github.com/microsoft/typescript-etw for more information
3532     var etwModule;
3533     try {
3534         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
3535         // require() will throw an exception if the module is not found
3536         // It may also return undefined if not installed properly
3537         etwModule = require(etwModulePath);
3538     }
3539     catch (e) {
3540         etwModule = undefined;
3541     }
3542     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
3543     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
3544 })(ts || (ts = {}));
3545 /* Tracing events for the compiler. */
3546 /*@internal*/
3547 var ts;
3548 (function (ts) {
3549     // enable the above using startTracing()
3550     // `tracingEnabled` should never be used directly, only through the above
3551     var tracingEnabled;
3552     (function (tracingEnabled) {
3553         var fs;
3554         var traceCount = 0;
3555         var traceFd = 0;
3556         var mode;
3557         var typeCatalog = []; // NB: id is index + 1
3558         var legendPath;
3559         var legend = [];
3560         ;
3561         /** Starts tracing for the given project. */
3562         function startTracing(tracingMode, traceDir, configFilePath) {
3563             ts.Debug.assert(!ts.tracing, "Tracing already started");
3564             if (fs === undefined) {
3565                 try {
3566                     fs = require("fs");
3567                 }
3568                 catch (e) {
3569                     throw new Error("tracing requires having fs\n(original error: ".concat(e.message || e, ")"));
3570                 }
3571             }
3572             mode = tracingMode;
3573             typeCatalog.length = 0;
3574             if (legendPath === undefined) {
3575                 legendPath = ts.combinePaths(traceDir, "legend.json");
3576             }
3577             // Note that writing will fail later on if it exists and is not a directory
3578             if (!fs.existsSync(traceDir)) {
3579                 fs.mkdirSync(traceDir, { recursive: true });
3580             }
3581             var countPart = mode === "build" ? ".".concat(process.pid, "-").concat(++traceCount)
3582                 : mode === "server" ? ".".concat(process.pid)
3583                     : "";
3584             var tracePath = ts.combinePaths(traceDir, "trace".concat(countPart, ".json"));
3585             var typesPath = ts.combinePaths(traceDir, "types".concat(countPart, ".json"));
3586             legend.push({
3587                 configFilePath: configFilePath,
3588                 tracePath: tracePath,
3589                 typesPath: typesPath,
3590             });
3591             traceFd = fs.openSync(tracePath, "w");
3592             ts.tracing = tracingEnabled; // only when traceFd is properly set
3593             // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
3594             var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
3595             fs.writeSync(traceFd, "[\n"
3596                 + [__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" })]
3597                     .map(function (v) { return JSON.stringify(v); }).join(",\n"));
3598         }
3599         tracingEnabled.startTracing = startTracing;
3600         /** Stops tracing for the in-progress project and dumps the type catalog. */
3601         function stopTracing() {
3602             ts.Debug.assert(ts.tracing, "Tracing is not in progress");
3603             ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode
3604             fs.writeSync(traceFd, "\n]\n");
3605             fs.closeSync(traceFd);
3606             ts.tracing = undefined;
3607             if (typeCatalog.length) {
3608                 dumpTypes(typeCatalog);
3609             }
3610             else {
3611                 // We pre-computed this path for convenience, but clear it
3612                 // now that the file won't be created.
3613                 legend[legend.length - 1].typesPath = undefined;
3614             }
3615         }
3616         tracingEnabled.stopTracing = stopTracing;
3617         function recordType(type) {
3618             if (mode !== "server") {
3619                 typeCatalog.push(type);
3620             }
3621         }
3622         tracingEnabled.recordType = recordType;
3623         var Phase;
3624         (function (Phase) {
3625             Phase["Parse"] = "parse";
3626             Phase["Program"] = "program";
3627             Phase["Bind"] = "bind";
3628             Phase["Check"] = "check";
3629             Phase["CheckTypes"] = "checkTypes";
3630             Phase["Emit"] = "emit";
3631             Phase["Session"] = "session";
3632         })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {}));
3633         function instant(phase, name, args) {
3634             writeEvent("I", phase, name, args, "\"s\":\"g\"");
3635         }
3636         tracingEnabled.instant = instant;
3637         var eventStack = [];
3638         /**
3639          * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event
3640          * never terminates (typically for reducing a scenario too big to trace to one that can be completed).
3641          * In the future we might implement an exit handler to dump unfinished events which would deprecate
3642          * these operations.
3643          */
3644         function push(phase, name, args, separateBeginAndEnd) {
3645             if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; }
3646             if (separateBeginAndEnd) {
3647                 writeEvent("B", phase, name, args);
3648             }
3649             eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd });
3650         }
3651         tracingEnabled.push = push;
3652         function pop() {
3653             ts.Debug.assert(eventStack.length > 0);
3654             writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp());
3655             eventStack.length--;
3656         }
3657         tracingEnabled.pop = pop;
3658         function popAll() {
3659             var endTime = 1000 * ts.timestamp();
3660             for (var i = eventStack.length - 1; i >= 0; i--) {
3661                 writeStackEvent(i, endTime);
3662             }
3663             eventStack.length = 0;
3664         }
3665         tracingEnabled.popAll = popAll;
3666         // sample every 10ms
3667         var sampleInterval = 1000 * 10;
3668         function writeStackEvent(index, endTime) {
3669             var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd;
3670             if (separateBeginAndEnd) {
3671                 writeEvent("E", phase, name, args, /*extras*/ undefined, endTime);
3672             }
3673             // test if [time,endTime) straddles a sampling point
3674             else if (sampleInterval - (time % sampleInterval) <= endTime - time) {
3675                 writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time);
3676             }
3677         }
3678         function writeEvent(eventType, phase, name, args, extras, time) {
3679             if (time === void 0) { time = 1000 * ts.timestamp(); }
3680             // In server mode, there's no easy way to dump type information, so we drop events that would require it.
3681             if (mode === "server" && phase === "checkTypes" /* CheckTypes */)
3682                 return;
3683             ts.performance.mark("beginTracing");
3684             fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"".concat(eventType, "\",\"cat\":\"").concat(phase, "\",\"ts\":").concat(time, ",\"name\":\"").concat(name, "\""));
3685             if (extras)
3686                 fs.writeSync(traceFd, ",".concat(extras));
3687             if (args)
3688                 fs.writeSync(traceFd, ",\"args\":".concat(JSON.stringify(args)));
3689             fs.writeSync(traceFd, "}");
3690             ts.performance.mark("endTracing");
3691             ts.performance.measure("Tracing", "beginTracing", "endTracing");
3692         }
3693         function getLocation(node) {
3694             var file = ts.getSourceFileOfNode(node);
3695             return !file
3696                 ? undefined
3697                 : {
3698                     path: file.path,
3699                     start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)),
3700                     end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)),
3701                 };
3702             function indexFromOne(lc) {
3703                 return {
3704                     line: lc.line + 1,
3705                     character: lc.character + 1,
3706                 };
3707             }
3708         }
3709         function dumpTypes(types) {
3710             var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
3711             ts.performance.mark("beginDumpTypes");
3712             var typesPath = legend[legend.length - 1].typesPath;
3713             var typesFd = fs.openSync(typesPath, "w");
3714             var recursionIdentityMap = new ts.Map();
3715             // Cleverness: no line break here so that the type ID will match the line number
3716             fs.writeSync(typesFd, "[");
3717             var numTypes = types.length;
3718             for (var i = 0; i < numTypes; i++) {
3719                 var type = types[i];
3720                 var objectFlags = type.objectFlags;
3721                 var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol;
3722                 // It's slow to compute the display text, so skip it unless it's really valuable (or cheap)
3723                 var display = void 0;
3724                 if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) {
3725                     try {
3726                         display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type);
3727                     }
3728                     catch (_y) {
3729                         display = undefined;
3730                     }
3731                 }
3732                 var indexedAccessProperties = {};
3733                 if (type.flags & 8388608 /* IndexedAccess */) {
3734                     var indexedAccessType = type;
3735                     indexedAccessProperties = {
3736                         indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id,
3737                         indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id,
3738                     };
3739                 }
3740                 var referenceProperties = {};
3741                 if (objectFlags & 4 /* Reference */) {
3742                     var referenceType = type;
3743                     referenceProperties = {
3744                         instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id,
3745                         typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }),
3746                         referenceLocation: getLocation(referenceType.node),
3747                     };
3748                 }
3749                 var conditionalProperties = {};
3750                 if (type.flags & 16777216 /* Conditional */) {
3751                     var conditionalType = type;
3752                     conditionalProperties = {
3753                         conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id,
3754                         conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id,
3755                         conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1,
3756                         conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1,
3757                     };
3758                 }
3759                 var substitutionProperties = {};
3760                 if (type.flags & 33554432 /* Substitution */) {
3761                     var substitutionType = type;
3762                     substitutionProperties = {
3763                         substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id,
3764                         substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id,
3765                     };
3766                 }
3767                 var reverseMappedProperties = {};
3768                 if (objectFlags & 1024 /* ReverseMapped */) {
3769                     var reverseMappedType = type;
3770                     reverseMappedProperties = {
3771                         reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id,
3772                         reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id,
3773                         reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id,
3774                     };
3775                 }
3776                 var evolvingArrayProperties = {};
3777                 if (objectFlags & 256 /* EvolvingArray */) {
3778                     var evolvingArrayType = type;
3779                     evolvingArrayProperties = {
3780                         evolvingArrayElementType: evolvingArrayType.elementType.id,
3781                         evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id,
3782                     };
3783                 }
3784                 // We can't print out an arbitrary object, so just assign each one a unique number.
3785                 // Don't call it an "id" so people don't treat it as a type id.
3786                 var recursionToken = void 0;
3787                 var recursionIdentity = type.checker.getRecursionIdentity(type);
3788                 if (recursionIdentity) {
3789                     recursionToken = recursionIdentityMap.get(recursionIdentity);
3790                     if (!recursionToken) {
3791                         recursionToken = recursionIdentityMap.size;
3792                         recursionIdentityMap.set(recursionIdentity, recursionToken);
3793                     }
3794                 }
3795                 var descriptor = __assign(__assign(__assign(__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, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display });
3796                 fs.writeSync(typesFd, JSON.stringify(descriptor));
3797                 if (i < numTypes - 1) {
3798                     fs.writeSync(typesFd, ",\n");
3799                 }
3800             }
3801             fs.writeSync(typesFd, "]\n");
3802             fs.closeSync(typesFd);
3803             ts.performance.mark("endDumpTypes");
3804             ts.performance.measure("Dump types", "beginDumpTypes", "endDumpTypes");
3805         }
3806         function dumpLegend() {
3807             if (!legendPath) {
3808                 return;
3809             }
3810             fs.writeFileSync(legendPath, JSON.stringify(legend));
3811         }
3812         tracingEnabled.dumpLegend = dumpLegend;
3813     })(tracingEnabled || (tracingEnabled = {}));
3814     // define after tracingEnabled is initialized
3815     ts.startTracing = tracingEnabled.startTracing;
3816     ts.dumpTracingLegend = tracingEnabled.dumpLegend;
3817 })(ts || (ts = {}));
3818 var ts;
3819 (function (ts) {
3820     // token > SyntaxKind.Identifier => token is a keyword
3821     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3822     var SyntaxKind;
3823     (function (SyntaxKind) {
3824         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3825         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3826         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3827         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3828         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3829         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3830         // We detect and preserve #! on the first line
3831         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3832         // We detect and provide better error recovery when we encounter a git merge marker.  This
3833         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3834         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3835         // Literals
3836         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3837         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3838         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3839         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3840         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3841         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3842         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3843         // Pseudo-literals
3844         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3845         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3846         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3847         // Punctuation
3848         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3849         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3850         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3851         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3852         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3853         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3854         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3855         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3856         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3857         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3858         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3859         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3860         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3861         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3862         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3863         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3864         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3865         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3866         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3867         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3868         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3869         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3870         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3871         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3872         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3873         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3874         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3875         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3876         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3877         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3878         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3879         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3880         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3881         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3882         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3883         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3884         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3885         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3886         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3887         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3888         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3889         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3890         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3891         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3892         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3893         /** Only the JSDoc scanner produces HashToken. The normal scanner produces PrivateIdentifier. */
3894         SyntaxKind[SyntaxKind["HashToken"] = 62] = "HashToken";
3895         // Assignments
3896         SyntaxKind[SyntaxKind["EqualsToken"] = 63] = "EqualsToken";
3897         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 64] = "PlusEqualsToken";
3898         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 65] = "MinusEqualsToken";
3899         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 66] = "AsteriskEqualsToken";
3900         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 67] = "AsteriskAsteriskEqualsToken";
3901         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 68] = "SlashEqualsToken";
3902         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 69] = "PercentEqualsToken";
3903         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 70] = "LessThanLessThanEqualsToken";
3904         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanEqualsToken";
3905         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 72] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3906         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 73] = "AmpersandEqualsToken";
3907         SyntaxKind[SyntaxKind["BarEqualsToken"] = 74] = "BarEqualsToken";
3908         SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 75] = "BarBarEqualsToken";
3909         SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 76] = "AmpersandAmpersandEqualsToken";
3910         SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 77] = "QuestionQuestionEqualsToken";
3911         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 78] = "CaretEqualsToken";
3912         // Identifiers and PrivateIdentifiers
3913         SyntaxKind[SyntaxKind["Identifier"] = 79] = "Identifier";
3914         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 80] = "PrivateIdentifier";
3915         // Reserved words
3916         SyntaxKind[SyntaxKind["BreakKeyword"] = 81] = "BreakKeyword";
3917         SyntaxKind[SyntaxKind["CaseKeyword"] = 82] = "CaseKeyword";
3918         SyntaxKind[SyntaxKind["CatchKeyword"] = 83] = "CatchKeyword";
3919         SyntaxKind[SyntaxKind["ClassKeyword"] = 84] = "ClassKeyword";
3920         SyntaxKind[SyntaxKind["ConstKeyword"] = 85] = "ConstKeyword";
3921         SyntaxKind[SyntaxKind["ContinueKeyword"] = 86] = "ContinueKeyword";
3922         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 87] = "DebuggerKeyword";
3923         SyntaxKind[SyntaxKind["DefaultKeyword"] = 88] = "DefaultKeyword";
3924         SyntaxKind[SyntaxKind["DeleteKeyword"] = 89] = "DeleteKeyword";
3925         SyntaxKind[SyntaxKind["DoKeyword"] = 90] = "DoKeyword";
3926         SyntaxKind[SyntaxKind["ElseKeyword"] = 91] = "ElseKeyword";
3927         SyntaxKind[SyntaxKind["EnumKeyword"] = 92] = "EnumKeyword";
3928         SyntaxKind[SyntaxKind["ExportKeyword"] = 93] = "ExportKeyword";
3929         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 94] = "ExtendsKeyword";
3930         SyntaxKind[SyntaxKind["FalseKeyword"] = 95] = "FalseKeyword";
3931         SyntaxKind[SyntaxKind["FinallyKeyword"] = 96] = "FinallyKeyword";
3932         SyntaxKind[SyntaxKind["ForKeyword"] = 97] = "ForKeyword";
3933         SyntaxKind[SyntaxKind["FunctionKeyword"] = 98] = "FunctionKeyword";
3934         SyntaxKind[SyntaxKind["IfKeyword"] = 99] = "IfKeyword";
3935         SyntaxKind[SyntaxKind["ImportKeyword"] = 100] = "ImportKeyword";
3936         SyntaxKind[SyntaxKind["InKeyword"] = 101] = "InKeyword";
3937         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 102] = "InstanceOfKeyword";
3938         SyntaxKind[SyntaxKind["NewKeyword"] = 103] = "NewKeyword";
3939         SyntaxKind[SyntaxKind["NullKeyword"] = 104] = "NullKeyword";
3940         SyntaxKind[SyntaxKind["ReturnKeyword"] = 105] = "ReturnKeyword";
3941         SyntaxKind[SyntaxKind["SuperKeyword"] = 106] = "SuperKeyword";
3942         SyntaxKind[SyntaxKind["SwitchKeyword"] = 107] = "SwitchKeyword";
3943         SyntaxKind[SyntaxKind["ThisKeyword"] = 108] = "ThisKeyword";
3944         SyntaxKind[SyntaxKind["ThrowKeyword"] = 109] = "ThrowKeyword";
3945         SyntaxKind[SyntaxKind["TrueKeyword"] = 110] = "TrueKeyword";
3946         SyntaxKind[SyntaxKind["TryKeyword"] = 111] = "TryKeyword";
3947         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 112] = "TypeOfKeyword";
3948         SyntaxKind[SyntaxKind["VarKeyword"] = 113] = "VarKeyword";
3949         SyntaxKind[SyntaxKind["VoidKeyword"] = 114] = "VoidKeyword";
3950         SyntaxKind[SyntaxKind["WhileKeyword"] = 115] = "WhileKeyword";
3951         SyntaxKind[SyntaxKind["WithKeyword"] = 116] = "WithKeyword";
3952         // Strict mode reserved words
3953         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 117] = "ImplementsKeyword";
3954         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 118] = "InterfaceKeyword";
3955         SyntaxKind[SyntaxKind["LetKeyword"] = 119] = "LetKeyword";
3956         SyntaxKind[SyntaxKind["PackageKeyword"] = 120] = "PackageKeyword";
3957         SyntaxKind[SyntaxKind["PrivateKeyword"] = 121] = "PrivateKeyword";
3958         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 122] = "ProtectedKeyword";
3959         SyntaxKind[SyntaxKind["PublicKeyword"] = 123] = "PublicKeyword";
3960         SyntaxKind[SyntaxKind["StaticKeyword"] = 124] = "StaticKeyword";
3961         SyntaxKind[SyntaxKind["YieldKeyword"] = 125] = "YieldKeyword";
3962         // Contextual keywords
3963         SyntaxKind[SyntaxKind["AbstractKeyword"] = 126] = "AbstractKeyword";
3964         SyntaxKind[SyntaxKind["AsKeyword"] = 127] = "AsKeyword";
3965         SyntaxKind[SyntaxKind["AssertsKeyword"] = 128] = "AssertsKeyword";
3966         SyntaxKind[SyntaxKind["AssertKeyword"] = 129] = "AssertKeyword";
3967         SyntaxKind[SyntaxKind["AnyKeyword"] = 130] = "AnyKeyword";
3968         SyntaxKind[SyntaxKind["AsyncKeyword"] = 131] = "AsyncKeyword";
3969         SyntaxKind[SyntaxKind["AwaitKeyword"] = 132] = "AwaitKeyword";
3970         SyntaxKind[SyntaxKind["BooleanKeyword"] = 133] = "BooleanKeyword";
3971         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 134] = "ConstructorKeyword";
3972         SyntaxKind[SyntaxKind["DeclareKeyword"] = 135] = "DeclareKeyword";
3973         SyntaxKind[SyntaxKind["GetKeyword"] = 136] = "GetKeyword";
3974         SyntaxKind[SyntaxKind["InferKeyword"] = 137] = "InferKeyword";
3975         SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 138] = "IntrinsicKeyword";
3976         SyntaxKind[SyntaxKind["IsKeyword"] = 139] = "IsKeyword";
3977         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 140] = "KeyOfKeyword";
3978         SyntaxKind[SyntaxKind["ModuleKeyword"] = 141] = "ModuleKeyword";
3979         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 142] = "NamespaceKeyword";
3980         SyntaxKind[SyntaxKind["NeverKeyword"] = 143] = "NeverKeyword";
3981         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 144] = "ReadonlyKeyword";
3982         SyntaxKind[SyntaxKind["RequireKeyword"] = 145] = "RequireKeyword";
3983         SyntaxKind[SyntaxKind["NumberKeyword"] = 146] = "NumberKeyword";
3984         SyntaxKind[SyntaxKind["ObjectKeyword"] = 147] = "ObjectKeyword";
3985         SyntaxKind[SyntaxKind["SetKeyword"] = 148] = "SetKeyword";
3986         SyntaxKind[SyntaxKind["StringKeyword"] = 149] = "StringKeyword";
3987         SyntaxKind[SyntaxKind["SymbolKeyword"] = 150] = "SymbolKeyword";
3988         SyntaxKind[SyntaxKind["TypeKeyword"] = 151] = "TypeKeyword";
3989         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 152] = "UndefinedKeyword";
3990         SyntaxKind[SyntaxKind["UniqueKeyword"] = 153] = "UniqueKeyword";
3991         SyntaxKind[SyntaxKind["UnknownKeyword"] = 154] = "UnknownKeyword";
3992         SyntaxKind[SyntaxKind["FromKeyword"] = 155] = "FromKeyword";
3993         SyntaxKind[SyntaxKind["GlobalKeyword"] = 156] = "GlobalKeyword";
3994         SyntaxKind[SyntaxKind["BigIntKeyword"] = 157] = "BigIntKeyword";
3995         SyntaxKind[SyntaxKind["OverrideKeyword"] = 158] = "OverrideKeyword";
3996         SyntaxKind[SyntaxKind["OfKeyword"] = 159] = "OfKeyword";
3997         // Parse tree nodes
3998         // Names
3999         SyntaxKind[SyntaxKind["QualifiedName"] = 160] = "QualifiedName";
4000         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 161] = "ComputedPropertyName";
4001         // Signature elements
4002         SyntaxKind[SyntaxKind["TypeParameter"] = 162] = "TypeParameter";
4003         SyntaxKind[SyntaxKind["Parameter"] = 163] = "Parameter";
4004         SyntaxKind[SyntaxKind["Decorator"] = 164] = "Decorator";
4005         // TypeMember
4006         SyntaxKind[SyntaxKind["PropertySignature"] = 165] = "PropertySignature";
4007         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 166] = "PropertyDeclaration";
4008         SyntaxKind[SyntaxKind["MethodSignature"] = 167] = "MethodSignature";
4009         SyntaxKind[SyntaxKind["MethodDeclaration"] = 168] = "MethodDeclaration";
4010         SyntaxKind[SyntaxKind["ClassStaticBlockDeclaration"] = 169] = "ClassStaticBlockDeclaration";
4011         SyntaxKind[SyntaxKind["Constructor"] = 170] = "Constructor";
4012         SyntaxKind[SyntaxKind["GetAccessor"] = 171] = "GetAccessor";
4013         SyntaxKind[SyntaxKind["SetAccessor"] = 172] = "SetAccessor";
4014         SyntaxKind[SyntaxKind["CallSignature"] = 173] = "CallSignature";
4015         SyntaxKind[SyntaxKind["ConstructSignature"] = 174] = "ConstructSignature";
4016         SyntaxKind[SyntaxKind["IndexSignature"] = 175] = "IndexSignature";
4017         // Type
4018         SyntaxKind[SyntaxKind["TypePredicate"] = 176] = "TypePredicate";
4019         SyntaxKind[SyntaxKind["TypeReference"] = 177] = "TypeReference";
4020         SyntaxKind[SyntaxKind["FunctionType"] = 178] = "FunctionType";
4021         SyntaxKind[SyntaxKind["ConstructorType"] = 179] = "ConstructorType";
4022         SyntaxKind[SyntaxKind["TypeQuery"] = 180] = "TypeQuery";
4023         SyntaxKind[SyntaxKind["TypeLiteral"] = 181] = "TypeLiteral";
4024         SyntaxKind[SyntaxKind["ArrayType"] = 182] = "ArrayType";
4025         SyntaxKind[SyntaxKind["TupleType"] = 183] = "TupleType";
4026         SyntaxKind[SyntaxKind["OptionalType"] = 184] = "OptionalType";
4027         SyntaxKind[SyntaxKind["RestType"] = 185] = "RestType";
4028         SyntaxKind[SyntaxKind["UnionType"] = 186] = "UnionType";
4029         SyntaxKind[SyntaxKind["IntersectionType"] = 187] = "IntersectionType";
4030         SyntaxKind[SyntaxKind["ConditionalType"] = 188] = "ConditionalType";
4031         SyntaxKind[SyntaxKind["InferType"] = 189] = "InferType";
4032         SyntaxKind[SyntaxKind["ParenthesizedType"] = 190] = "ParenthesizedType";
4033         SyntaxKind[SyntaxKind["ThisType"] = 191] = "ThisType";
4034         SyntaxKind[SyntaxKind["TypeOperator"] = 192] = "TypeOperator";
4035         SyntaxKind[SyntaxKind["IndexedAccessType"] = 193] = "IndexedAccessType";
4036         SyntaxKind[SyntaxKind["MappedType"] = 194] = "MappedType";
4037         SyntaxKind[SyntaxKind["LiteralType"] = 195] = "LiteralType";
4038         SyntaxKind[SyntaxKind["NamedTupleMember"] = 196] = "NamedTupleMember";
4039         SyntaxKind[SyntaxKind["TemplateLiteralType"] = 197] = "TemplateLiteralType";
4040         SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 198] = "TemplateLiteralTypeSpan";
4041         SyntaxKind[SyntaxKind["ImportType"] = 199] = "ImportType";
4042         // Binding patterns
4043         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 200] = "ObjectBindingPattern";
4044         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 201] = "ArrayBindingPattern";
4045         SyntaxKind[SyntaxKind["BindingElement"] = 202] = "BindingElement";
4046         // Expression
4047         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 203] = "ArrayLiteralExpression";
4048         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 204] = "ObjectLiteralExpression";
4049         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 205] = "PropertyAccessExpression";
4050         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 206] = "ElementAccessExpression";
4051         SyntaxKind[SyntaxKind["CallExpression"] = 207] = "CallExpression";
4052         SyntaxKind[SyntaxKind["NewExpression"] = 208] = "NewExpression";
4053         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 209] = "TaggedTemplateExpression";
4054         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 210] = "TypeAssertionExpression";
4055         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 211] = "ParenthesizedExpression";
4056         SyntaxKind[SyntaxKind["FunctionExpression"] = 212] = "FunctionExpression";
4057         SyntaxKind[SyntaxKind["ArrowFunction"] = 213] = "ArrowFunction";
4058         SyntaxKind[SyntaxKind["DeleteExpression"] = 214] = "DeleteExpression";
4059         SyntaxKind[SyntaxKind["TypeOfExpression"] = 215] = "TypeOfExpression";
4060         SyntaxKind[SyntaxKind["VoidExpression"] = 216] = "VoidExpression";
4061         SyntaxKind[SyntaxKind["AwaitExpression"] = 217] = "AwaitExpression";
4062         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 218] = "PrefixUnaryExpression";
4063         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 219] = "PostfixUnaryExpression";
4064         SyntaxKind[SyntaxKind["BinaryExpression"] = 220] = "BinaryExpression";
4065         SyntaxKind[SyntaxKind["ConditionalExpression"] = 221] = "ConditionalExpression";
4066         SyntaxKind[SyntaxKind["TemplateExpression"] = 222] = "TemplateExpression";
4067         SyntaxKind[SyntaxKind["YieldExpression"] = 223] = "YieldExpression";
4068         SyntaxKind[SyntaxKind["SpreadElement"] = 224] = "SpreadElement";
4069         SyntaxKind[SyntaxKind["ClassExpression"] = 225] = "ClassExpression";
4070         SyntaxKind[SyntaxKind["OmittedExpression"] = 226] = "OmittedExpression";
4071         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 227] = "ExpressionWithTypeArguments";
4072         SyntaxKind[SyntaxKind["AsExpression"] = 228] = "AsExpression";
4073         SyntaxKind[SyntaxKind["NonNullExpression"] = 229] = "NonNullExpression";
4074         SyntaxKind[SyntaxKind["MetaProperty"] = 230] = "MetaProperty";
4075         SyntaxKind[SyntaxKind["SyntheticExpression"] = 231] = "SyntheticExpression";
4076         // Misc
4077         SyntaxKind[SyntaxKind["TemplateSpan"] = 232] = "TemplateSpan";
4078         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 233] = "SemicolonClassElement";
4079         // Element
4080         SyntaxKind[SyntaxKind["Block"] = 234] = "Block";
4081         SyntaxKind[SyntaxKind["EmptyStatement"] = 235] = "EmptyStatement";
4082         SyntaxKind[SyntaxKind["VariableStatement"] = 236] = "VariableStatement";
4083         SyntaxKind[SyntaxKind["ExpressionStatement"] = 237] = "ExpressionStatement";
4084         SyntaxKind[SyntaxKind["IfStatement"] = 238] = "IfStatement";
4085         SyntaxKind[SyntaxKind["DoStatement"] = 239] = "DoStatement";
4086         SyntaxKind[SyntaxKind["WhileStatement"] = 240] = "WhileStatement";
4087         SyntaxKind[SyntaxKind["ForStatement"] = 241] = "ForStatement";
4088         SyntaxKind[SyntaxKind["ForInStatement"] = 242] = "ForInStatement";
4089         SyntaxKind[SyntaxKind["ForOfStatement"] = 243] = "ForOfStatement";
4090         SyntaxKind[SyntaxKind["ContinueStatement"] = 244] = "ContinueStatement";
4091         SyntaxKind[SyntaxKind["BreakStatement"] = 245] = "BreakStatement";
4092         SyntaxKind[SyntaxKind["ReturnStatement"] = 246] = "ReturnStatement";
4093         SyntaxKind[SyntaxKind["WithStatement"] = 247] = "WithStatement";
4094         SyntaxKind[SyntaxKind["SwitchStatement"] = 248] = "SwitchStatement";
4095         SyntaxKind[SyntaxKind["LabeledStatement"] = 249] = "LabeledStatement";
4096         SyntaxKind[SyntaxKind["ThrowStatement"] = 250] = "ThrowStatement";
4097         SyntaxKind[SyntaxKind["TryStatement"] = 251] = "TryStatement";
4098         SyntaxKind[SyntaxKind["DebuggerStatement"] = 252] = "DebuggerStatement";
4099         SyntaxKind[SyntaxKind["VariableDeclaration"] = 253] = "VariableDeclaration";
4100         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 254] = "VariableDeclarationList";
4101         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 255] = "FunctionDeclaration";
4102         SyntaxKind[SyntaxKind["ClassDeclaration"] = 256] = "ClassDeclaration";
4103         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 257] = "InterfaceDeclaration";
4104         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 258] = "TypeAliasDeclaration";
4105         SyntaxKind[SyntaxKind["EnumDeclaration"] = 259] = "EnumDeclaration";
4106         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 260] = "ModuleDeclaration";
4107         SyntaxKind[SyntaxKind["ModuleBlock"] = 261] = "ModuleBlock";
4108         SyntaxKind[SyntaxKind["CaseBlock"] = 262] = "CaseBlock";
4109         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 263] = "NamespaceExportDeclaration";
4110         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 264] = "ImportEqualsDeclaration";
4111         SyntaxKind[SyntaxKind["ImportDeclaration"] = 265] = "ImportDeclaration";
4112         SyntaxKind[SyntaxKind["ImportClause"] = 266] = "ImportClause";
4113         SyntaxKind[SyntaxKind["NamespaceImport"] = 267] = "NamespaceImport";
4114         SyntaxKind[SyntaxKind["NamedImports"] = 268] = "NamedImports";
4115         SyntaxKind[SyntaxKind["ImportSpecifier"] = 269] = "ImportSpecifier";
4116         SyntaxKind[SyntaxKind["ExportAssignment"] = 270] = "ExportAssignment";
4117         SyntaxKind[SyntaxKind["ExportDeclaration"] = 271] = "ExportDeclaration";
4118         SyntaxKind[SyntaxKind["NamedExports"] = 272] = "NamedExports";
4119         SyntaxKind[SyntaxKind["NamespaceExport"] = 273] = "NamespaceExport";
4120         SyntaxKind[SyntaxKind["ExportSpecifier"] = 274] = "ExportSpecifier";
4121         SyntaxKind[SyntaxKind["MissingDeclaration"] = 275] = "MissingDeclaration";
4122         // Module references
4123         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 276] = "ExternalModuleReference";
4124         // JSX
4125         SyntaxKind[SyntaxKind["JsxElement"] = 277] = "JsxElement";
4126         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 278] = "JsxSelfClosingElement";
4127         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 279] = "JsxOpeningElement";
4128         SyntaxKind[SyntaxKind["JsxClosingElement"] = 280] = "JsxClosingElement";
4129         SyntaxKind[SyntaxKind["JsxFragment"] = 281] = "JsxFragment";
4130         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 282] = "JsxOpeningFragment";
4131         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 283] = "JsxClosingFragment";
4132         SyntaxKind[SyntaxKind["JsxAttribute"] = 284] = "JsxAttribute";
4133         SyntaxKind[SyntaxKind["JsxAttributes"] = 285] = "JsxAttributes";
4134         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 286] = "JsxSpreadAttribute";
4135         SyntaxKind[SyntaxKind["JsxExpression"] = 287] = "JsxExpression";
4136         // Clauses
4137         SyntaxKind[SyntaxKind["CaseClause"] = 288] = "CaseClause";
4138         SyntaxKind[SyntaxKind["DefaultClause"] = 289] = "DefaultClause";
4139         SyntaxKind[SyntaxKind["HeritageClause"] = 290] = "HeritageClause";
4140         SyntaxKind[SyntaxKind["CatchClause"] = 291] = "CatchClause";
4141         SyntaxKind[SyntaxKind["AssertClause"] = 292] = "AssertClause";
4142         SyntaxKind[SyntaxKind["AssertEntry"] = 293] = "AssertEntry";
4143         // Property assignments
4144         SyntaxKind[SyntaxKind["PropertyAssignment"] = 294] = "PropertyAssignment";
4145         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 295] = "ShorthandPropertyAssignment";
4146         SyntaxKind[SyntaxKind["SpreadAssignment"] = 296] = "SpreadAssignment";
4147         // Enum
4148         SyntaxKind[SyntaxKind["EnumMember"] = 297] = "EnumMember";
4149         // Unparsed
4150         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 298] = "UnparsedPrologue";
4151         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 299] = "UnparsedPrepend";
4152         SyntaxKind[SyntaxKind["UnparsedText"] = 300] = "UnparsedText";
4153         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 301] = "UnparsedInternalText";
4154         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 302] = "UnparsedSyntheticReference";
4155         // Top-level nodes
4156         SyntaxKind[SyntaxKind["SourceFile"] = 303] = "SourceFile";
4157         SyntaxKind[SyntaxKind["Bundle"] = 304] = "Bundle";
4158         SyntaxKind[SyntaxKind["UnparsedSource"] = 305] = "UnparsedSource";
4159         SyntaxKind[SyntaxKind["InputFiles"] = 306] = "InputFiles";
4160         // JSDoc nodes
4161         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 307] = "JSDocTypeExpression";
4162         SyntaxKind[SyntaxKind["JSDocNameReference"] = 308] = "JSDocNameReference";
4163         SyntaxKind[SyntaxKind["JSDocMemberName"] = 309] = "JSDocMemberName";
4164         SyntaxKind[SyntaxKind["JSDocAllType"] = 310] = "JSDocAllType";
4165         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 311] = "JSDocUnknownType";
4166         SyntaxKind[SyntaxKind["JSDocNullableType"] = 312] = "JSDocNullableType";
4167         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 313] = "JSDocNonNullableType";
4168         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 314] = "JSDocOptionalType";
4169         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 315] = "JSDocFunctionType";
4170         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 316] = "JSDocVariadicType";
4171         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 317] = "JSDocNamepathType";
4172         SyntaxKind[SyntaxKind["JSDocComment"] = 318] = "JSDocComment";
4173         SyntaxKind[SyntaxKind["JSDocText"] = 319] = "JSDocText";
4174         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 320] = "JSDocTypeLiteral";
4175         SyntaxKind[SyntaxKind["JSDocSignature"] = 321] = "JSDocSignature";
4176         SyntaxKind[SyntaxKind["JSDocLink"] = 322] = "JSDocLink";
4177         SyntaxKind[SyntaxKind["JSDocLinkCode"] = 323] = "JSDocLinkCode";
4178         SyntaxKind[SyntaxKind["JSDocLinkPlain"] = 324] = "JSDocLinkPlain";
4179         SyntaxKind[SyntaxKind["JSDocTag"] = 325] = "JSDocTag";
4180         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 326] = "JSDocAugmentsTag";
4181         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 327] = "JSDocImplementsTag";
4182         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 328] = "JSDocAuthorTag";
4183         SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 329] = "JSDocDeprecatedTag";
4184         SyntaxKind[SyntaxKind["JSDocClassTag"] = 330] = "JSDocClassTag";
4185         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 331] = "JSDocPublicTag";
4186         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 332] = "JSDocPrivateTag";
4187         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 333] = "JSDocProtectedTag";
4188         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 334] = "JSDocReadonlyTag";
4189         SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 335] = "JSDocOverrideTag";
4190         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 336] = "JSDocCallbackTag";
4191         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 337] = "JSDocEnumTag";
4192         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 338] = "JSDocParameterTag";
4193         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 339] = "JSDocReturnTag";
4194         SyntaxKind[SyntaxKind["JSDocThisTag"] = 340] = "JSDocThisTag";
4195         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 341] = "JSDocTypeTag";
4196         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 342] = "JSDocTemplateTag";
4197         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 343] = "JSDocTypedefTag";
4198         SyntaxKind[SyntaxKind["JSDocSeeTag"] = 344] = "JSDocSeeTag";
4199         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 345] = "JSDocPropertyTag";
4200         // Synthesized list
4201         SyntaxKind[SyntaxKind["SyntaxList"] = 346] = "SyntaxList";
4202         // Transformation nodes
4203         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 347] = "NotEmittedStatement";
4204         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 348] = "PartiallyEmittedExpression";
4205         SyntaxKind[SyntaxKind["CommaListExpression"] = 349] = "CommaListExpression";
4206         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 350] = "MergeDeclarationMarker";
4207         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 351] = "EndOfDeclarationMarker";
4208         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 352] = "SyntheticReferenceExpression";
4209         // Enum value count
4210         SyntaxKind[SyntaxKind["Count"] = 353] = "Count";
4211         // Markers
4212         SyntaxKind[SyntaxKind["FirstAssignment"] = 63] = "FirstAssignment";
4213         SyntaxKind[SyntaxKind["LastAssignment"] = 78] = "LastAssignment";
4214         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 64] = "FirstCompoundAssignment";
4215         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 78] = "LastCompoundAssignment";
4216         SyntaxKind[SyntaxKind["FirstReservedWord"] = 81] = "FirstReservedWord";
4217         SyntaxKind[SyntaxKind["LastReservedWord"] = 116] = "LastReservedWord";
4218         SyntaxKind[SyntaxKind["FirstKeyword"] = 81] = "FirstKeyword";
4219         SyntaxKind[SyntaxKind["LastKeyword"] = 159] = "LastKeyword";
4220         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 117] = "FirstFutureReservedWord";
4221         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 125] = "LastFutureReservedWord";
4222         SyntaxKind[SyntaxKind["FirstTypeNode"] = 176] = "FirstTypeNode";
4223         SyntaxKind[SyntaxKind["LastTypeNode"] = 199] = "LastTypeNode";
4224         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
4225         SyntaxKind[SyntaxKind["LastPunctuation"] = 78] = "LastPunctuation";
4226         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
4227         SyntaxKind[SyntaxKind["LastToken"] = 159] = "LastToken";
4228         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
4229         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
4230         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
4231         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
4232         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
4233         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
4234         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
4235         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 78] = "LastBinaryOperator";
4236         SyntaxKind[SyntaxKind["FirstStatement"] = 236] = "FirstStatement";
4237         SyntaxKind[SyntaxKind["LastStatement"] = 252] = "LastStatement";
4238         SyntaxKind[SyntaxKind["FirstNode"] = 160] = "FirstNode";
4239         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 307] = "FirstJSDocNode";
4240         SyntaxKind[SyntaxKind["LastJSDocNode"] = 345] = "LastJSDocNode";
4241         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 325] = "FirstJSDocTagNode";
4242         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 345] = "LastJSDocTagNode";
4243         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword";
4244         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 159] = "LastContextualKeyword";
4245     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
4246     var NodeFlags;
4247     (function (NodeFlags) {
4248         NodeFlags[NodeFlags["None"] = 0] = "None";
4249         NodeFlags[NodeFlags["Let"] = 1] = "Let";
4250         NodeFlags[NodeFlags["Const"] = 2] = "Const";
4251         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
4252         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
4253         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
4254         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
4255         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
4256         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
4257         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
4258         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
4259         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
4260         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
4261         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
4262         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
4263         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
4264         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
4265         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
4266         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
4267         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
4268         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
4269         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
4270         // walking the tree if the flags are not set. However, these flags are just a approximation
4271         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
4272         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
4273         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
4274         // However, the removal operation should not occur often and in the case of the
4275         // removal, it is likely that users will add the import anyway.
4276         // The advantage of this approach is its simplicity. For the case of batch compilation,
4277         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
4278         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
4279         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
4280         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
4281         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
4282         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
4283         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
4284         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
4285         /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
4286         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
4287         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
4288         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
4289         // Parsing context flags
4290         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
4291         // Exclude these flags when parsing a Type
4292         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
4293         // Represents all flags that are potentially set once and
4294         // never cleared on SourceFiles which get re-used in between incremental parses.
4295         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
4296         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
4297     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
4298     var ModifierFlags;
4299     (function (ModifierFlags) {
4300         ModifierFlags[ModifierFlags["None"] = 0] = "None";
4301         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
4302         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
4303         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
4304         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
4305         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
4306         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
4307         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
4308         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
4309         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
4310         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
4311         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
4312         ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
4313         ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
4314         ModifierFlags[ModifierFlags["Override"] = 16384] = "Override";
4315         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4316         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
4317         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
4318         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier";
4319         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
4320         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier";
4321         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
4322         ModifierFlags[ModifierFlags["All"] = 27647] = "All";
4323     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
4324     var JsxFlags;
4325     (function (JsxFlags) {
4326         JsxFlags[JsxFlags["None"] = 0] = "None";
4327         /** An element from a named property of the JSX.IntrinsicElements interface */
4328         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
4329         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
4330         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
4331         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
4332     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
4333     /* @internal */
4334     var RelationComparisonResult;
4335     (function (RelationComparisonResult) {
4336         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
4337         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
4338         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
4339         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
4340         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
4341         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
4342     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
4343     var GeneratedIdentifierFlags;
4344     (function (GeneratedIdentifierFlags) {
4345         // Kinds
4346         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
4347         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
4348         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
4349         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
4350         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
4351         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
4352         // Flags
4353         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
4354         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
4355         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
4356         GeneratedIdentifierFlags[GeneratedIdentifierFlags["AllowNameSubstitution"] = 64] = "AllowNameSubstitution";
4357     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
4358     var TokenFlags;
4359     (function (TokenFlags) {
4360         TokenFlags[TokenFlags["None"] = 0] = "None";
4361         /* @internal */
4362         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
4363         /* @internal */
4364         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
4365         /* @internal */
4366         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
4367         /* @internal */
4368         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
4369         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
4370         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
4371         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
4372         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
4373         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
4374         /* @internal */
4375         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
4376         /* @internal */
4377         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
4378         /* @internal */
4379         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
4380         /* @internal */
4381         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
4382         /* @internal */
4383         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
4384         /* @internal */
4385         TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
4386     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
4387     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
4388     var FlowFlags;
4389     (function (FlowFlags) {
4390         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
4391         FlowFlags[FlowFlags["Start"] = 2] = "Start";
4392         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
4393         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
4394         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
4395         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
4396         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
4397         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
4398         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
4399         FlowFlags[FlowFlags["Call"] = 512] = "Call";
4400         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
4401         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
4402         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
4403         FlowFlags[FlowFlags["Label"] = 12] = "Label";
4404         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
4405     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
4406     /* @internal */
4407     var CommentDirectiveType;
4408     (function (CommentDirectiveType) {
4409         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
4410         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
4411     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
4412     var OperationCanceledException = /** @class */ (function () {
4413         function OperationCanceledException() {
4414         }
4415         return OperationCanceledException;
4416     }());
4417     ts.OperationCanceledException = OperationCanceledException;
4418     /*@internal*/
4419     var FileIncludeKind;
4420     (function (FileIncludeKind) {
4421         FileIncludeKind[FileIncludeKind["RootFile"] = 0] = "RootFile";
4422         FileIncludeKind[FileIncludeKind["SourceFromProjectReference"] = 1] = "SourceFromProjectReference";
4423         FileIncludeKind[FileIncludeKind["OutputFromProjectReference"] = 2] = "OutputFromProjectReference";
4424         FileIncludeKind[FileIncludeKind["Import"] = 3] = "Import";
4425         FileIncludeKind[FileIncludeKind["ReferenceFile"] = 4] = "ReferenceFile";
4426         FileIncludeKind[FileIncludeKind["TypeReferenceDirective"] = 5] = "TypeReferenceDirective";
4427         FileIncludeKind[FileIncludeKind["LibFile"] = 6] = "LibFile";
4428         FileIncludeKind[FileIncludeKind["LibReferenceDirective"] = 7] = "LibReferenceDirective";
4429         FileIncludeKind[FileIncludeKind["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile";
4430     })(FileIncludeKind = ts.FileIncludeKind || (ts.FileIncludeKind = {}));
4431     /*@internal*/
4432     var FilePreprocessingDiagnosticsKind;
4433     (function (FilePreprocessingDiagnosticsKind) {
4434         FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic";
4435         FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic";
4436     })(FilePreprocessingDiagnosticsKind = ts.FilePreprocessingDiagnosticsKind || (ts.FilePreprocessingDiagnosticsKind = {}));
4437     /* @internal */
4438     var StructureIsReused;
4439     (function (StructureIsReused) {
4440         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
4441         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
4442         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
4443     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
4444     /** Return code used by getEmitOutput function to indicate status of the function */
4445     var ExitStatus;
4446     (function (ExitStatus) {
4447         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
4448         // when -version or -help was provided, or this was a normal compilation, no diagnostics
4449         // were produced, and all outputs were generated successfully.
4450         ExitStatus[ExitStatus["Success"] = 0] = "Success";
4451         // Diagnostics were produced and because of them no code was generated.
4452         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
4453         // Diagnostics were produced and outputs were generated in spite of them.
4454         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
4455         // When build skipped because passed in project is invalid
4456         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
4457         // When build is skipped because project references form cycle
4458         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
4459         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
4460         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
4461     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
4462     /* @internal */
4463     var MemberOverrideStatus;
4464     (function (MemberOverrideStatus) {
4465         MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok";
4466         MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride";
4467         MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride";
4468     })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {}));
4469     /* @internal */
4470     var UnionReduction;
4471     (function (UnionReduction) {
4472         UnionReduction[UnionReduction["None"] = 0] = "None";
4473         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
4474         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
4475     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
4476     /* @internal */
4477     var ContextFlags;
4478     (function (ContextFlags) {
4479         ContextFlags[ContextFlags["None"] = 0] = "None";
4480         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
4481         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
4482         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
4483         ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
4484     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
4485     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
4486     var NodeBuilderFlags;
4487     (function (NodeBuilderFlags) {
4488         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
4489         // Options
4490         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
4491         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4492         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
4493         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4494         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
4495         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4496         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4497         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
4498         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4499         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
4500         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4501         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4502         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4503         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4504         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4505         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4506         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4507         NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
4508         // Error handling
4509         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
4510         NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier";
4511         /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
4512         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
4513         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
4514         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
4515         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
4516         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4517         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
4518         // Errors (cont.)
4519         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
4520         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
4521         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
4522         // State
4523         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
4524         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4525         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
4526     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
4527     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
4528     var TypeFormatFlags;
4529     (function (TypeFormatFlags) {
4530         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
4531         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
4532         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4533         // hole because there's a hole in node builder flags
4534         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4535         // hole because there's a hole in node builder flags
4536         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4537         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4538         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
4539         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4540         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
4541         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4542         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4543         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4544         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4545         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4546         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4547         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4548         // Error Handling
4549         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4550         // TypeFormatFlags exclusive
4551         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
4552         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
4553         // State
4554         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
4555         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
4556         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
4557         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4558         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
4559         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
4560     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
4561     var SymbolFormatFlags;
4562     (function (SymbolFormatFlags) {
4563         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
4564         // Write symbols's type argument if it is instantiated symbol
4565         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
4566         //     var a: C<number>;
4567         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
4568         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
4569         // Use only external alias information to get the symbol name in the given context
4570         // eg.  module m { export class c { } } import x = m.c;
4571         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
4572         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
4573         // Build symbol name using any nodes needed, instead of just components of an entity name
4574         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
4575         // Prefer aliases which are not directly visible
4576         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
4577         // Skip building an accessible symbol chain
4578         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
4579     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
4580     /* @internal */
4581     var SymbolAccessibility;
4582     (function (SymbolAccessibility) {
4583         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
4584         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
4585         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
4586     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
4587     /* @internal */
4588     var SyntheticSymbolKind;
4589     (function (SyntheticSymbolKind) {
4590         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
4591         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
4592     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
4593     var TypePredicateKind;
4594     (function (TypePredicateKind) {
4595         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
4596         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
4597         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
4598         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
4599     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
4600     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
4601     /* @internal */
4602     var TypeReferenceSerializationKind;
4603     (function (TypeReferenceSerializationKind) {
4604         // The TypeReferenceNode could not be resolved.
4605         // The type name should be emitted using a safe fallback.
4606         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
4607         // The TypeReferenceNode resolves to a type with a constructor
4608         // function that can be reached at runtime (e.g. a `class`
4609         // declaration or a `var` declaration for the static side
4610         // of a type, such as the global `Promise` type in lib.d.ts).
4611         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
4612         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
4613         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
4614         // The TypeReferenceNode resolves to a Number-like type.
4615         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
4616         // The TypeReferenceNode resolves to a BigInt-like type.
4617         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
4618         // The TypeReferenceNode resolves to a String-like type.
4619         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
4620         // The TypeReferenceNode resolves to a Boolean-like type.
4621         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
4622         // The TypeReferenceNode resolves to an Array-like type.
4623         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
4624         // The TypeReferenceNode resolves to the ESSymbol type.
4625         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
4626         // The TypeReferenceNode resolved to the global Promise constructor symbol.
4627         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
4628         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
4629         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
4630         // The TypeReferenceNode resolves to any other type.
4631         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
4632     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
4633     var SymbolFlags;
4634     (function (SymbolFlags) {
4635         SymbolFlags[SymbolFlags["None"] = 0] = "None";
4636         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
4637         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
4638         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
4639         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
4640         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
4641         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
4642         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
4643         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
4644         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
4645         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
4646         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
4647         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
4648         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
4649         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
4650         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
4651         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
4652         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
4653         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
4654         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
4655         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
4656         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
4657         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
4658         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
4659         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
4660         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
4661         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
4662         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
4663         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
4664         /* @internal */
4665         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
4666         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
4667         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
4668         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
4669         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
4670         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
4671         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
4672         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
4673         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
4674         // same name, or any other value that is not a variable, e.g. ValueModule or Class
4675         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
4676         // Block-scoped declarations are not allowed to be re-declared
4677         // they can not merge with anything in the value space
4678         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
4679         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
4680         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
4681         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
4682         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
4683         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
4684         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
4685         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
4686         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
4687         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
4688         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
4689         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
4690         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
4691         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
4692         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
4693         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
4694         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
4695         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
4696         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
4697         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
4698         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
4699         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
4700         /* @internal */
4701         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
4702         /* @internal */
4703         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
4704         /* @internal */
4705         // The set of things we consider semantically classifiable.  Used to speed up the LS during
4706         // classification.
4707         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
4708         /* @internal */
4709         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
4710     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
4711     /* @internal */
4712     var EnumKind;
4713     (function (EnumKind) {
4714         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
4715         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
4716     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
4717     /* @internal */
4718     var CheckFlags;
4719     (function (CheckFlags) {
4720         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
4721         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
4722         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
4723         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
4724         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
4725         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
4726         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
4727         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
4728         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
4729         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
4730         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
4731         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
4732         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
4733         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
4734         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
4735         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
4736         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
4737         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
4738         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
4739         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
4740         CheckFlags[CheckFlags["Unresolved"] = 1048576] = "Unresolved";
4741         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
4742         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
4743         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
4744     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
4745     var InternalSymbolName;
4746     (function (InternalSymbolName) {
4747         InternalSymbolName["Call"] = "__call";
4748         InternalSymbolName["Constructor"] = "__constructor";
4749         InternalSymbolName["New"] = "__new";
4750         InternalSymbolName["Index"] = "__index";
4751         InternalSymbolName["ExportStar"] = "__export";
4752         InternalSymbolName["Global"] = "__global";
4753         InternalSymbolName["Missing"] = "__missing";
4754         InternalSymbolName["Type"] = "__type";
4755         InternalSymbolName["Object"] = "__object";
4756         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
4757         InternalSymbolName["Class"] = "__class";
4758         InternalSymbolName["Function"] = "__function";
4759         InternalSymbolName["Computed"] = "__computed";
4760         InternalSymbolName["Resolving"] = "__resolving__";
4761         InternalSymbolName["ExportEquals"] = "export=";
4762         InternalSymbolName["Default"] = "default";
4763         InternalSymbolName["This"] = "this";
4764     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
4765     /* @internal */
4766     var NodeCheckFlags;
4767     (function (NodeCheckFlags) {
4768         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
4769         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
4770         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
4771         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
4772         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
4773         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
4774         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
4775         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
4776         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
4777         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
4778         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
4779         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
4780         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
4781         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
4782         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
4783         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
4784         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
4785         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
4786         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
4787         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
4788         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
4789         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
4790         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4791         NodeCheckFlags[NodeCheckFlags["ContainsSuperPropertyInStaticInitializer"] = 134217728] = "ContainsSuperPropertyInStaticInitializer";
4792     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4793     var TypeFlags;
4794     (function (TypeFlags) {
4795         TypeFlags[TypeFlags["Any"] = 1] = "Any";
4796         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4797         TypeFlags[TypeFlags["String"] = 4] = "String";
4798         TypeFlags[TypeFlags["Number"] = 8] = "Number";
4799         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4800         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4801         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4802         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4803         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4804         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4805         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4806         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4807         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4808         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4809         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4810         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4811         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4812         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4813         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4814         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4815         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4816         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4817         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4818         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4819         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4820         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4821         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4822         TypeFlags[TypeFlags["TemplateLiteral"] = 134217728] = "TemplateLiteral";
4823         TypeFlags[TypeFlags["StringMapping"] = 268435456] = "StringMapping";
4824         /* @internal */
4825         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4826         /* @internal */
4827         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4828         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4829         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4830         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4831         /* @internal */
4832         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4833         /* @internal */
4834         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4835         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4836         /* @internal */
4837         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4838         /* @internal */
4839         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4840         TypeFlags[TypeFlags["StringLike"] = 402653316] = "StringLike";
4841         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4842         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4843         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4844         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4845         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4846         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4847         /* @internal */
4848         TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
4849         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4850         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4851         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4852         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4853         TypeFlags[TypeFlags["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive";
4854         TypeFlags[TypeFlags["Instantiable"] = 465829888] = "Instantiable";
4855         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable";
4856         /* @internal */
4857         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4858         /* @internal */
4859         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4860         /* @internal */
4861         TypeFlags[TypeFlags["Singleton"] = 67358815] = "Singleton";
4862         // 'Narrowable' types are types where narrowing actually narrows.
4863         // This *should* be every type other than null, undefined, void, and never
4864         TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
4865         // The following flags are aggregated during union and intersection type construction
4866         /* @internal */
4867         TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
4868         // The following flags are used for different purposes during union and intersection type construction
4869         /* @internal */
4870         TypeFlags[TypeFlags["IncludesMissingType"] = 262144] = "IncludesMissingType";
4871         /* @internal */
4872         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4873         /* @internal */
4874         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4875         /* @internal */
4876         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4877         /* @internal */
4878         TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable";
4879         /* @internal */
4880         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion";
4881     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4882     // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags
4883     // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check
4884     // for a certain TypeFlags value to determine their meaning.
4885     var ObjectFlags;
4886     (function (ObjectFlags) {
4887         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4888         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4889         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4890         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4891         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4892         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4893         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4894         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4895         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4896         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4897         ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped";
4898         ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes";
4899         ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType";
4900         ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral";
4901         ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral";
4902         ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral";
4903         /* @internal */
4904         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
4905         /* @internal */
4906         ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
4907         /* @internal */
4908         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral";
4909         /* @internal */
4910         ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
4911         /* @internal */
4912         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed";
4913         /* @internal */
4914         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables";
4915         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4916         /* @internal */
4917         ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
4918         /* @internal */
4919         ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
4920         // Object flags that uniquely identify the kind of ObjectType
4921         /* @internal */
4922         ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask";
4923         // Flags that require TypeFlags.Object
4924         ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread";
4925         ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType";
4926         /* @internal */
4927         ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone";
4928         // Flags that require TypeFlags.Object and ObjectFlags.Reference
4929         /* @internal */
4930         ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated";
4931         /* @internal */
4932         ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists";
4933         // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
4934         /* @internal */
4935         ObjectFlags[ObjectFlags["IsGenericTypeComputed"] = 4194304] = "IsGenericTypeComputed";
4936         /* @internal */
4937         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4938         /* @internal */
4939         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 16777216] = "IsGenericIndexType";
4940         /* @internal */
4941         ObjectFlags[ObjectFlags["IsGenericType"] = 25165824] = "IsGenericType";
4942         // Flags that require TypeFlags.Union
4943         /* @internal */
4944         ObjectFlags[ObjectFlags["ContainsIntersections"] = 33554432] = "ContainsIntersections";
4945         // Flags that require TypeFlags.Intersection
4946         /* @internal */
4947         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 33554432] = "IsNeverIntersectionComputed";
4948         /* @internal */
4949         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 67108864] = "IsNeverIntersection";
4950     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4951     /* @internal */
4952     var VarianceFlags;
4953     (function (VarianceFlags) {
4954         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4955         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4956         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4957         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4958         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4959         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4960         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4961         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4962         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4963     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4964     var ElementFlags;
4965     (function (ElementFlags) {
4966         ElementFlags[ElementFlags["Required"] = 1] = "Required";
4967         ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
4968         ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
4969         ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
4970         ElementFlags[ElementFlags["Fixed"] = 3] = "Fixed";
4971         ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
4972         ElementFlags[ElementFlags["NonRequired"] = 14] = "NonRequired";
4973         ElementFlags[ElementFlags["NonRest"] = 11] = "NonRest";
4974     })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
4975     /* @internal */
4976     var AccessFlags;
4977     (function (AccessFlags) {
4978         AccessFlags[AccessFlags["None"] = 0] = "None";
4979         AccessFlags[AccessFlags["IncludeUndefined"] = 1] = "IncludeUndefined";
4980         AccessFlags[AccessFlags["NoIndexSignatures"] = 2] = "NoIndexSignatures";
4981         AccessFlags[AccessFlags["Writing"] = 4] = "Writing";
4982         AccessFlags[AccessFlags["CacheSymbol"] = 8] = "CacheSymbol";
4983         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 16] = "NoTupleBoundsCheck";
4984         AccessFlags[AccessFlags["ExpressionPosition"] = 32] = "ExpressionPosition";
4985         AccessFlags[AccessFlags["ReportDeprecated"] = 64] = "ReportDeprecated";
4986         AccessFlags[AccessFlags["SuppressNoImplicitAnyError"] = 128] = "SuppressNoImplicitAnyError";
4987         AccessFlags[AccessFlags["Contextual"] = 256] = "Contextual";
4988         AccessFlags[AccessFlags["Persistent"] = 1] = "Persistent";
4989     })(AccessFlags = ts.AccessFlags || (ts.AccessFlags = {}));
4990     /* @internal */
4991     var JsxReferenceKind;
4992     (function (JsxReferenceKind) {
4993         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4994         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4995         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4996     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4997     var SignatureKind;
4998     (function (SignatureKind) {
4999         SignatureKind[SignatureKind["Call"] = 0] = "Call";
5000         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
5001     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
5002     /* @internal */
5003     var SignatureFlags;
5004     (function (SignatureFlags) {
5005         SignatureFlags[SignatureFlags["None"] = 0] = "None";
5006         // Propagating flags
5007         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
5008         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
5009         SignatureFlags[SignatureFlags["Abstract"] = 4] = "Abstract";
5010         // Non-propagating flags
5011         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 8] = "IsInnerCallChain";
5012         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 16] = "IsOuterCallChain";
5013         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile";
5014         // We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us
5015         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
5016         // instantiating the return type.
5017         SignatureFlags[SignatureFlags["PropagatingFlags"] = 39] = "PropagatingFlags";
5018         SignatureFlags[SignatureFlags["CallChainFlags"] = 24] = "CallChainFlags";
5019     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
5020     var IndexKind;
5021     (function (IndexKind) {
5022         IndexKind[IndexKind["String"] = 0] = "String";
5023         IndexKind[IndexKind["Number"] = 1] = "Number";
5024     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
5025     /* @internal */
5026     var TypeMapKind;
5027     (function (TypeMapKind) {
5028         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
5029         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
5030         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
5031         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
5032         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
5033     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
5034     var InferencePriority;
5035     (function (InferencePriority) {
5036         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
5037         InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
5038         InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource";
5039         InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType";
5040         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType";
5041         InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint";
5042         InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional";
5043         InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType";
5044         InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof";
5045         InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints";
5046         InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict";
5047         InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue";
5048         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination";
5049         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
5050     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
5051     /* @internal */
5052     var InferenceFlags;
5053     (function (InferenceFlags) {
5054         InferenceFlags[InferenceFlags["None"] = 0] = "None";
5055         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
5056         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
5057         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
5058     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
5059     /**
5060      * Ternary values are defined such that
5061      * x & y picks the lesser in the order False < Unknown < Maybe < True, and
5062      * x | y picks the greater in the order False < Unknown < Maybe < True.
5063      * Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
5064      * Ternary.Unknown is used as the result of a variance check that depends on itself. We make
5065      * a distinction because we don't want to cache circular variance check results.
5066      */
5067     /* @internal */
5068     var Ternary;
5069     (function (Ternary) {
5070         Ternary[Ternary["False"] = 0] = "False";
5071         Ternary[Ternary["Unknown"] = 1] = "Unknown";
5072         Ternary[Ternary["Maybe"] = 3] = "Maybe";
5073         Ternary[Ternary["True"] = -1] = "True";
5074     })(Ternary = ts.Ternary || (ts.Ternary = {}));
5075     /* @internal */
5076     var AssignmentDeclarationKind;
5077     (function (AssignmentDeclarationKind) {
5078         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
5079         /// exports.name = expr
5080         /// module.exports.name = expr
5081         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
5082         /// module.exports = expr
5083         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
5084         /// className.prototype.name = expr
5085         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
5086         /// this.name = expr
5087         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
5088         // F.name = expr
5089         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
5090         // F.prototype = { ... }
5091         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
5092         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
5093         // Object.defineProperty(x, 'name', { get: Function, set: Function });
5094         // Object.defineProperty(x, 'name', { get: Function });
5095         // Object.defineProperty(x, 'name', { set: Function });
5096         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
5097         // Object.defineProperty(exports || module.exports, 'name', ...);
5098         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
5099         // Object.defineProperty(Foo.prototype, 'name', ...);
5100         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
5101     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
5102     var DiagnosticCategory;
5103     (function (DiagnosticCategory) {
5104         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
5105         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
5106         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
5107         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
5108     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
5109     /* @internal */
5110     function diagnosticCategoryName(d, lowerCase) {
5111         if (lowerCase === void 0) { lowerCase = true; }
5112         var name = DiagnosticCategory[d.category];
5113         return lowerCase ? name.toLowerCase() : name;
5114     }
5115     ts.diagnosticCategoryName = diagnosticCategoryName;
5116     var ModuleResolutionKind;
5117     (function (ModuleResolutionKind) {
5118         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
5119         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
5120         // Starting with node12, node's module resolver has significant departures from traditional cjs resolution
5121         // to better support ecmascript modules and their use within node - more features are still being added, so
5122         // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12`
5123         // version-anchored resolution target
5124         ModuleResolutionKind[ModuleResolutionKind["Node12"] = 3] = "Node12";
5125         ModuleResolutionKind[ModuleResolutionKind["NodeNext"] = 99] = "NodeNext";
5126     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
5127     var WatchFileKind;
5128     (function (WatchFileKind) {
5129         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
5130         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
5131         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
5132         WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling";
5133         WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents";
5134         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory";
5135     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
5136     var WatchDirectoryKind;
5137     (function (WatchDirectoryKind) {
5138         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
5139         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
5140         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
5141         WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling";
5142     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
5143     var PollingWatchKind;
5144     (function (PollingWatchKind) {
5145         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
5146         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
5147         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
5148         PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize";
5149     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
5150     var ModuleKind;
5151     (function (ModuleKind) {
5152         ModuleKind[ModuleKind["None"] = 0] = "None";
5153         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
5154         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
5155         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
5156         ModuleKind[ModuleKind["System"] = 4] = "System";
5157         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
5158         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
5159         //       module kind).
5160         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
5161         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
5162         ModuleKind[ModuleKind["ES2022"] = 7] = "ES2022";
5163         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
5164         // Node12+ is an amalgam of commonjs (albeit updated) and es2020+, and represents a distinct module system from es2020/esnext
5165         ModuleKind[ModuleKind["Node12"] = 100] = "Node12";
5166         ModuleKind[ModuleKind["NodeNext"] = 199] = "NodeNext";
5167     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
5168     var JsxEmit;
5169     (function (JsxEmit) {
5170         JsxEmit[JsxEmit["None"] = 0] = "None";
5171         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
5172         JsxEmit[JsxEmit["React"] = 2] = "React";
5173         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
5174         JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
5175         JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
5176     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
5177     var ImportsNotUsedAsValues;
5178     (function (ImportsNotUsedAsValues) {
5179         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
5180         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
5181         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
5182     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
5183     var NewLineKind;
5184     (function (NewLineKind) {
5185         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
5186         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
5187     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
5188     var ScriptKind;
5189     (function (ScriptKind) {
5190         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
5191         ScriptKind[ScriptKind["JS"] = 1] = "JS";
5192         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
5193         ScriptKind[ScriptKind["TS"] = 3] = "TS";
5194         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
5195         ScriptKind[ScriptKind["External"] = 5] = "External";
5196         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
5197         /**
5198          * Used on extensions that doesn't define the ScriptKind but the content defines it.
5199          * Deferred extensions are going to be included in all project contexts.
5200          */
5201         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
5202     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
5203     var ScriptTarget;
5204     (function (ScriptTarget) {
5205         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
5206         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
5207         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
5208         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
5209         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
5210         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
5211         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
5212         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
5213         ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021";
5214         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
5215         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
5216         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
5217     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
5218     var LanguageVariant;
5219     (function (LanguageVariant) {
5220         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
5221         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
5222     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
5223     var WatchDirectoryFlags;
5224     (function (WatchDirectoryFlags) {
5225         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
5226         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
5227     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
5228     /* @internal */
5229     var CharacterCodes;
5230     (function (CharacterCodes) {
5231         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
5232         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
5233         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
5234         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
5235         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
5236         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
5237         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
5238         // Unicode 3.0 space characters
5239         CharacterCodes[CharacterCodes["space"] = 32] = "space";
5240         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
5241         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
5242         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
5243         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
5244         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
5245         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
5246         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
5247         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
5248         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
5249         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
5250         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
5251         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
5252         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
5253         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
5254         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
5255         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
5256         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
5257         CharacterCodes[CharacterCodes["_"] = 95] = "_";
5258         CharacterCodes[CharacterCodes["$"] = 36] = "$";
5259         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
5260         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
5261         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
5262         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
5263         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
5264         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
5265         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
5266         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
5267         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
5268         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
5269         CharacterCodes[CharacterCodes["a"] = 97] = "a";
5270         CharacterCodes[CharacterCodes["b"] = 98] = "b";
5271         CharacterCodes[CharacterCodes["c"] = 99] = "c";
5272         CharacterCodes[CharacterCodes["d"] = 100] = "d";
5273         CharacterCodes[CharacterCodes["e"] = 101] = "e";
5274         CharacterCodes[CharacterCodes["f"] = 102] = "f";
5275         CharacterCodes[CharacterCodes["g"] = 103] = "g";
5276         CharacterCodes[CharacterCodes["h"] = 104] = "h";
5277         CharacterCodes[CharacterCodes["i"] = 105] = "i";
5278         CharacterCodes[CharacterCodes["j"] = 106] = "j";
5279         CharacterCodes[CharacterCodes["k"] = 107] = "k";
5280         CharacterCodes[CharacterCodes["l"] = 108] = "l";
5281         CharacterCodes[CharacterCodes["m"] = 109] = "m";
5282         CharacterCodes[CharacterCodes["n"] = 110] = "n";
5283         CharacterCodes[CharacterCodes["o"] = 111] = "o";
5284         CharacterCodes[CharacterCodes["p"] = 112] = "p";
5285         CharacterCodes[CharacterCodes["q"] = 113] = "q";
5286         CharacterCodes[CharacterCodes["r"] = 114] = "r";
5287         CharacterCodes[CharacterCodes["s"] = 115] = "s";
5288         CharacterCodes[CharacterCodes["t"] = 116] = "t";
5289         CharacterCodes[CharacterCodes["u"] = 117] = "u";
5290         CharacterCodes[CharacterCodes["v"] = 118] = "v";
5291         CharacterCodes[CharacterCodes["w"] = 119] = "w";
5292         CharacterCodes[CharacterCodes["x"] = 120] = "x";
5293         CharacterCodes[CharacterCodes["y"] = 121] = "y";
5294         CharacterCodes[CharacterCodes["z"] = 122] = "z";
5295         CharacterCodes[CharacterCodes["A"] = 65] = "A";
5296         CharacterCodes[CharacterCodes["B"] = 66] = "B";
5297         CharacterCodes[CharacterCodes["C"] = 67] = "C";
5298         CharacterCodes[CharacterCodes["D"] = 68] = "D";
5299         CharacterCodes[CharacterCodes["E"] = 69] = "E";
5300         CharacterCodes[CharacterCodes["F"] = 70] = "F";
5301         CharacterCodes[CharacterCodes["G"] = 71] = "G";
5302         CharacterCodes[CharacterCodes["H"] = 72] = "H";
5303         CharacterCodes[CharacterCodes["I"] = 73] = "I";
5304         CharacterCodes[CharacterCodes["J"] = 74] = "J";
5305         CharacterCodes[CharacterCodes["K"] = 75] = "K";
5306         CharacterCodes[CharacterCodes["L"] = 76] = "L";
5307         CharacterCodes[CharacterCodes["M"] = 77] = "M";
5308         CharacterCodes[CharacterCodes["N"] = 78] = "N";
5309         CharacterCodes[CharacterCodes["O"] = 79] = "O";
5310         CharacterCodes[CharacterCodes["P"] = 80] = "P";
5311         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
5312         CharacterCodes[CharacterCodes["R"] = 82] = "R";
5313         CharacterCodes[CharacterCodes["S"] = 83] = "S";
5314         CharacterCodes[CharacterCodes["T"] = 84] = "T";
5315         CharacterCodes[CharacterCodes["U"] = 85] = "U";
5316         CharacterCodes[CharacterCodes["V"] = 86] = "V";
5317         CharacterCodes[CharacterCodes["W"] = 87] = "W";
5318         CharacterCodes[CharacterCodes["X"] = 88] = "X";
5319         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
5320         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
5321         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
5322         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
5323         CharacterCodes[CharacterCodes["at"] = 64] = "at";
5324         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
5325         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
5326         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
5327         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
5328         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
5329         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
5330         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
5331         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
5332         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
5333         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
5334         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
5335         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
5336         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
5337         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
5338         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
5339         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
5340         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
5341         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
5342         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
5343         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
5344         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
5345         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
5346         CharacterCodes[CharacterCodes["question"] = 63] = "question";
5347         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
5348         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
5349         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
5350         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
5351         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
5352         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
5353         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
5354         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
5355         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
5356     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
5357     var Extension;
5358     (function (Extension) {
5359         Extension["Ts"] = ".ts";
5360         Extension["Tsx"] = ".tsx";
5361         Extension["Dts"] = ".d.ts";
5362         Extension["Js"] = ".js";
5363         Extension["Jsx"] = ".jsx";
5364         Extension["Json"] = ".json";
5365         Extension["TsBuildInfo"] = ".tsbuildinfo";
5366         Extension["Mjs"] = ".mjs";
5367         Extension["Mts"] = ".mts";
5368         Extension["Dmts"] = ".d.mts";
5369         Extension["Cjs"] = ".cjs";
5370         Extension["Cts"] = ".cts";
5371         Extension["Dcts"] = ".d.cts";
5372     })(Extension = ts.Extension || (ts.Extension = {}));
5373     /* @internal */
5374     var TransformFlags;
5375     (function (TransformFlags) {
5376         TransformFlags[TransformFlags["None"] = 0] = "None";
5377         // Facts
5378         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
5379         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
5380         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
5381         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
5382         TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021";
5383         TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020";
5384         TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019";
5385         TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018";
5386         TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017";
5387         TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016";
5388         TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015";
5389         TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator";
5390         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
5391         // Markers
5392         // - Flags used to indicate that a subtree contains a specific transformation.
5393         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
5394         TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
5395         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread";
5396         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread";
5397         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName";
5398         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding";
5399         TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern";
5400         TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield";
5401         TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait";
5402         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion";
5403         TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport";
5404         TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields";
5405         TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait";
5406         TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper";
5407         TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier";
5408         // Please leave this as 1 << 29.
5409         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
5410         // It is a good reminder of how much room we have left
5411         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
5412         // Assertions
5413         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
5414         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
5415         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
5416         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
5417         TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021";
5418         TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020";
5419         TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019";
5420         TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018";
5421         TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017";
5422         TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016";
5423         TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015";
5424         TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator";
5425         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment";
5426         // Scope Exclusions
5427         // - Bitmasks that exclude flags from propagating out of a specific context
5428         //   into the subtree flags of their container.
5429         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
5430         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
5431         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
5432         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes";
5433         TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes";
5434         TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes";
5435         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes";
5436         TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes";
5437         TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes";
5438         TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes";
5439         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
5440         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes";
5441         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes";
5442         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes";
5443         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
5444         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes";
5445         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes";
5446         TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper";
5447         // Propagating flags
5448         // - Bitmasks for flags that should propagate from a child
5449         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags";
5450         // Masks
5451         // - Additional bitmasks
5452     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
5453     // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax
5454     /* @internal */
5455     var SnippetKind;
5456     (function (SnippetKind) {
5457         SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop";
5458         SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder";
5459         SnippetKind[SnippetKind["Choice"] = 2] = "Choice";
5460         SnippetKind[SnippetKind["Variable"] = 3] = "Variable";
5461     })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {}));
5462     var EmitFlags;
5463     (function (EmitFlags) {
5464         EmitFlags[EmitFlags["None"] = 0] = "None";
5465         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
5466         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
5467         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
5468         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
5469         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
5470         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
5471         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
5472         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
5473         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
5474         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
5475         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
5476         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
5477         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
5478         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
5479         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
5480         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
5481         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
5482         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
5483         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
5484         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
5485         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
5486         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
5487         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
5488         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
5489         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
5490         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
5491         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
5492         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
5493         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
5494         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
5495         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
5496         /*@internal*/ EmitFlags[EmitFlags["Immutable"] = 268435456] = "Immutable";
5497         /*@internal*/ EmitFlags[EmitFlags["IndirectCall"] = 536870912] = "IndirectCall";
5498     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
5499     /**
5500      * Used by the checker, this enum keeps track of external emit helpers that should be type
5501      * checked.
5502      */
5503     /* @internal */
5504     var ExternalEmitHelpers;
5505     (function (ExternalEmitHelpers) {
5506         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
5507         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
5508         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
5509         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
5510         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
5511         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
5512         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
5513         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
5514         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
5515         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
5516         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArray"] = 1024] = "SpreadArray";
5517         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
5518         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
5519         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
5520         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
5521         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
5522         ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 65536] = "ImportStar";
5523         ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 131072] = "ImportDefault";
5524         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 262144] = "MakeTemplateObject";
5525         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 524288] = "ClassPrivateFieldGet";
5526         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 1048576] = "ClassPrivateFieldSet";
5527         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldIn"] = 2097152] = "ClassPrivateFieldIn";
5528         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
5529         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
5530         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
5531         // Helpers included by ES2015 for..of
5532         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
5533         // Helpers included by ES2017 for..await..of
5534         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
5535         // Helpers included by ES2017 async generators
5536         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
5537         // Helpers included by yield* in ES2017 async generators
5538         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
5539         // Helpers included by ES2015 spread
5540         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
5541     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
5542     var EmitHint;
5543     (function (EmitHint) {
5544         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
5545         EmitHint[EmitHint["Expression"] = 1] = "Expression";
5546         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
5547         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
5548         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
5549         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
5550         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
5551     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
5552     var OuterExpressionKinds;
5553     (function (OuterExpressionKinds) {
5554         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
5555         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
5556         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
5557         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
5558         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
5559         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
5560         OuterExpressionKinds[OuterExpressionKinds["ExcludeJSDocTypeAssertion"] = 16] = "ExcludeJSDocTypeAssertion";
5561     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
5562     /* @internal */
5563     var LexicalEnvironmentFlags;
5564     (function (LexicalEnvironmentFlags) {
5565         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
5566         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
5567         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
5568     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
5569     /*@internal*/
5570     var BundleFileSectionKind;
5571     (function (BundleFileSectionKind) {
5572         BundleFileSectionKind["Prologue"] = "prologue";
5573         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
5574         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
5575         BundleFileSectionKind["Reference"] = "reference";
5576         BundleFileSectionKind["Type"] = "type";
5577         BundleFileSectionKind["Lib"] = "lib";
5578         BundleFileSectionKind["Prepend"] = "prepend";
5579         BundleFileSectionKind["Text"] = "text";
5580         BundleFileSectionKind["Internal"] = "internal";
5581         // comments?
5582     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
5583     var ListFormat;
5584     (function (ListFormat) {
5585         ListFormat[ListFormat["None"] = 0] = "None";
5586         // Line separators
5587         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
5588         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
5589         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
5590         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
5591         // Delimiters
5592         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
5593         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
5594         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
5595         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
5596         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
5597         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
5598         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
5599         // Whitespace
5600         ListFormat[ListFormat["Indented"] = 128] = "Indented";
5601         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
5602         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
5603         // Brackets/Braces
5604         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
5605         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
5606         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
5607         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
5608         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
5609         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
5610         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
5611         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
5612         // Other
5613         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
5614         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
5615         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
5616         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
5617         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
5618         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
5619         // Precomputed Formats
5620         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
5621         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
5622         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
5623         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
5624         ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
5625         ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
5626         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
5627         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
5628         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
5629         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
5630         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
5631         ListFormat[ListFormat["ImportClauseEntries"] = 526226] = "ImportClauseEntries";
5632         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
5633         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
5634         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
5635         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
5636         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
5637         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
5638         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
5639         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
5640         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
5641         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
5642         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
5643         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
5644         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
5645         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
5646         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
5647         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
5648         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
5649         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
5650         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
5651         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
5652         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
5653         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
5654         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
5655         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
5656         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
5657         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
5658         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
5659     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
5660     /* @internal */
5661     var PragmaKindFlags;
5662     (function (PragmaKindFlags) {
5663         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
5664         /**
5665          * Triple slash comment of the form
5666          * /// <pragma-name argname="value" />
5667          */
5668         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
5669         /**
5670          * Single line comment of the form
5671          * // @pragma-name argval1 argval2
5672          * or
5673          * /// @pragma-name argval1 argval2
5674          */
5675         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
5676         /**
5677          * Multiline non-jsdoc pragma of the form
5678          * /* @pragma-name argval1 argval2 * /
5679          */
5680         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
5681         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
5682         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
5683     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
5684     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
5685     //  fancy effectively defining it twice, once in value-space and once in type-space
5686     /* @internal */
5687     ts.commentPragmas = {
5688         "reference": {
5689             args: [
5690                 { name: "types", optional: true, captureSpan: true },
5691                 { name: "lib", optional: true, captureSpan: true },
5692                 { name: "path", optional: true, captureSpan: true },
5693                 { name: "no-default-lib", optional: true }
5694             ],
5695             kind: 1 /* TripleSlashXML */
5696         },
5697         "amd-dependency": {
5698             args: [{ name: "path" }, { name: "name", optional: true }],
5699             kind: 1 /* TripleSlashXML */
5700         },
5701         "amd-module": {
5702             args: [{ name: "name" }],
5703             kind: 1 /* TripleSlashXML */
5704         },
5705         "ts-check": {
5706             kind: 2 /* SingleLine */
5707         },
5708         "ts-nocheck": {
5709             kind: 2 /* SingleLine */
5710         },
5711         "jsx": {
5712             args: [{ name: "factory" }],
5713             kind: 4 /* MultiLine */
5714         },
5715         "jsxfrag": {
5716             args: [{ name: "factory" }],
5717             kind: 4 /* MultiLine */
5718         },
5719         "jsximportsource": {
5720             args: [{ name: "factory" }],
5721             kind: 4 /* MultiLine */
5722         },
5723         "jsxruntime": {
5724             args: [{ name: "factory" }],
5725             kind: 4 /* MultiLine */
5726         },
5727     };
5728 })(ts || (ts = {}));
5729 /* @internal */
5730 var ts;
5731 (function (ts) {
5732     /**
5733      * Internally, we represent paths as strings with '/' as the directory separator.
5734      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5735      * we expect the host to correctly handle paths in our specified format.
5736      */
5737     ts.directorySeparator = "/";
5738     ts.altDirectorySeparator = "\\";
5739     var urlSchemeSeparator = "://";
5740     var backslashRegExp = /\\/g;
5741     //// Path Tests
5742     /**
5743      * Determines whether a charCode corresponds to `/` or `\`.
5744      */
5745     function isAnyDirectorySeparator(charCode) {
5746         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5747     }
5748     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5749     /**
5750      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5751      */
5752     function isUrl(path) {
5753         return getEncodedRootLength(path) < 0;
5754     }
5755     ts.isUrl = isUrl;
5756     /**
5757      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5758      * like `c:`, `c:\` or `c:/`).
5759      */
5760     function isRootedDiskPath(path) {
5761         return getEncodedRootLength(path) > 0;
5762     }
5763     ts.isRootedDiskPath = isRootedDiskPath;
5764     /**
5765      * Determines whether a path consists only of a path root.
5766      */
5767     function isDiskPathRoot(path) {
5768         var rootLength = getEncodedRootLength(path);
5769         return rootLength > 0 && rootLength === path.length;
5770     }
5771     ts.isDiskPathRoot = isDiskPathRoot;
5772     /**
5773      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
5774      *
5775      * ```ts
5776      * // POSIX
5777      * pathIsAbsolute("/path/to/file.ext") === true
5778      * // DOS
5779      * pathIsAbsolute("c:/path/to/file.ext") === true
5780      * // URL
5781      * pathIsAbsolute("file:///path/to/file.ext") === true
5782      * // Non-absolute
5783      * pathIsAbsolute("path/to/file.ext") === false
5784      * pathIsAbsolute("./path/to/file.ext") === false
5785      * ```
5786      */
5787     function pathIsAbsolute(path) {
5788         return getEncodedRootLength(path) !== 0;
5789     }
5790     ts.pathIsAbsolute = pathIsAbsolute;
5791     /**
5792      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
5793      */
5794     function pathIsRelative(path) {
5795         return /^\.\.?($|[\\/])/.test(path);
5796     }
5797     ts.pathIsRelative = pathIsRelative;
5798     /**
5799      * Determines whether a path is neither relative nor absolute, e.g. "path/to/file".
5800      * Also known misleadingly as "non-relative".
5801      */
5802     function pathIsBareSpecifier(path) {
5803         return !pathIsAbsolute(path) && !pathIsRelative(path);
5804     }
5805     ts.pathIsBareSpecifier = pathIsBareSpecifier;
5806     function hasExtension(fileName) {
5807         return ts.stringContains(getBaseFileName(fileName), ".");
5808     }
5809     ts.hasExtension = hasExtension;
5810     function fileExtensionIs(path, extension) {
5811         return path.length > extension.length && ts.endsWith(path, extension);
5812     }
5813     ts.fileExtensionIs = fileExtensionIs;
5814     function fileExtensionIsOneOf(path, extensions) {
5815         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
5816             var extension = extensions_1[_i];
5817             if (fileExtensionIs(path, extension)) {
5818                 return true;
5819             }
5820         }
5821         return false;
5822     }
5823     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
5824     /**
5825      * Determines whether a path has a trailing separator (`/` or `\\`).
5826      */
5827     function hasTrailingDirectorySeparator(path) {
5828         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
5829     }
5830     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
5831     //// Path Parsing
5832     function isVolumeCharacter(charCode) {
5833         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
5834             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
5835     }
5836     function getFileUrlVolumeSeparatorEnd(url, start) {
5837         var ch0 = url.charCodeAt(start);
5838         if (ch0 === 58 /* colon */)
5839             return start + 1;
5840         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
5841             var ch2 = url.charCodeAt(start + 2);
5842             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
5843                 return start + 3;
5844         }
5845         return -1;
5846     }
5847     /**
5848      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5849      * If the root is part of a URL, the twos-complement of the root length is returned.
5850      */
5851     function getEncodedRootLength(path) {
5852         if (!path)
5853             return 0;
5854         var ch0 = path.charCodeAt(0);
5855         // POSIX or UNC
5856         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
5857             if (path.charCodeAt(1) !== ch0)
5858                 return 1; // POSIX: "/" (or non-normalized "\")
5859             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2);
5860             if (p1 < 0)
5861                 return path.length; // UNC: "//server" or "\\server"
5862             return p1 + 1; // UNC: "//server/" or "\\server\"
5863         }
5864         // DOS
5865         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
5866             var ch2 = path.charCodeAt(2);
5867             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
5868                 return 3; // DOS: "c:/" or "c:\"
5869             if (path.length === 2)
5870                 return 2; // DOS: "c:" (but not "c:d")
5871         }
5872         // URL
5873         var schemeEnd = path.indexOf(urlSchemeSeparator);
5874         if (schemeEnd !== -1) {
5875             var authorityStart = schemeEnd + urlSchemeSeparator.length;
5876             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
5877             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
5878                 // For local "file" URLs, include the leading DOS volume (if present).
5879                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
5880                 // special case interpreted as "the machine from which the URL is being interpreted".
5881                 var scheme = path.slice(0, schemeEnd);
5882                 var authority = path.slice(authorityStart, authorityEnd);
5883                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
5884                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
5885                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
5886                     if (volumeSeparatorEnd !== -1) {
5887                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
5888                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
5889                             return ~(volumeSeparatorEnd + 1);
5890                         }
5891                         if (volumeSeparatorEnd === path.length) {
5892                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
5893                             // but not "file:///c:d" or "file:///c%3ad"
5894                             return ~volumeSeparatorEnd;
5895                         }
5896                     }
5897                 }
5898                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
5899             }
5900             return ~path.length; // URL: "file://server", "http://server"
5901         }
5902         // relative
5903         return 0;
5904     }
5905     /**
5906      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5907      *
5908      * For example:
5909      * ```ts
5910      * getRootLength("a") === 0                   // ""
5911      * getRootLength("/") === 1                   // "/"
5912      * getRootLength("c:") === 2                  // "c:"
5913      * getRootLength("c:d") === 0                 // ""
5914      * getRootLength("c:/") === 3                 // "c:/"
5915      * getRootLength("c:\\") === 3                // "c:\\"
5916      * getRootLength("//server") === 7            // "//server"
5917      * getRootLength("//server/share") === 8      // "//server/"
5918      * getRootLength("\\\\server") === 7          // "\\\\server"
5919      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
5920      * getRootLength("file:///path") === 8        // "file:///"
5921      * getRootLength("file:///c:") === 10         // "file:///c:"
5922      * getRootLength("file:///c:d") === 8         // "file:///"
5923      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
5924      * getRootLength("file://server") === 13      // "file://server"
5925      * getRootLength("file://server/path") === 14 // "file://server/"
5926      * getRootLength("http://server") === 13      // "http://server"
5927      * getRootLength("http://server/path") === 14 // "http://server/"
5928      * ```
5929      */
5930     function getRootLength(path) {
5931         var rootLength = getEncodedRootLength(path);
5932         return rootLength < 0 ? ~rootLength : rootLength;
5933     }
5934     ts.getRootLength = getRootLength;
5935     function getDirectoryPath(path) {
5936         path = normalizeSlashes(path);
5937         // If the path provided is itself the root, then return it.
5938         var rootLength = getRootLength(path);
5939         if (rootLength === path.length)
5940             return path;
5941         // return the leading portion of the path up to the last (non-terminal) directory separator
5942         // but not including any trailing directory separator.
5943         path = removeTrailingDirectorySeparator(path);
5944         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
5945     }
5946     ts.getDirectoryPath = getDirectoryPath;
5947     function getBaseFileName(path, extensions, ignoreCase) {
5948         path = normalizeSlashes(path);
5949         // if the path provided is itself the root, then it has not file name.
5950         var rootLength = getRootLength(path);
5951         if (rootLength === path.length)
5952             return "";
5953         // return the trailing portion of the path starting after the last (non-terminal) directory
5954         // separator but not including any trailing directory separator.
5955         path = removeTrailingDirectorySeparator(path);
5956         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
5957         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
5958         return extension ? name.slice(0, name.length - extension.length) : name;
5959     }
5960     ts.getBaseFileName = getBaseFileName;
5961     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
5962         if (!ts.startsWith(extension, "."))
5963             extension = "." + extension;
5964         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
5965             var pathExtension = path.slice(path.length - extension.length);
5966             if (stringEqualityComparer(pathExtension, extension)) {
5967                 return pathExtension;
5968             }
5969         }
5970     }
5971     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
5972         if (typeof extensions === "string") {
5973             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
5974         }
5975         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
5976             var extension = extensions_2[_i];
5977             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
5978             if (result)
5979                 return result;
5980         }
5981         return "";
5982     }
5983     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
5984         // Retrieves any string from the final "." onwards from a base file name.
5985         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
5986         if (extensions) {
5987             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
5988         }
5989         var baseFileName = getBaseFileName(path);
5990         var extensionIndex = baseFileName.lastIndexOf(".");
5991         if (extensionIndex >= 0) {
5992             return baseFileName.substring(extensionIndex);
5993         }
5994         return "";
5995     }
5996     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
5997     function pathComponents(path, rootLength) {
5998         var root = path.substring(0, rootLength);
5999         var rest = path.substring(rootLength).split(ts.directorySeparator);
6000         if (rest.length && !ts.lastOrUndefined(rest))
6001             rest.pop();
6002         return __spreadArray([root], rest, true);
6003     }
6004     /**
6005      * Parse a path into an array containing a root component (at index 0) and zero or more path
6006      * components (at indices > 0). The result is not normalized.
6007      * If the path is relative, the root component is `""`.
6008      * If the path is absolute, the root component includes the first path separator (`/`).
6009      *
6010      * ```ts
6011      * // POSIX
6012      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6013      * getPathComponents("/path/to/") === ["/", "path", "to"]
6014      * getPathComponents("/") === ["/"]
6015      * // DOS
6016      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6017      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6018      * getPathComponents("c:/") === ["c:/"]
6019      * getPathComponents("c:") === ["c:"]
6020      * // URL
6021      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6022      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6023      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6024      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6025      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6026      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6027      * getPathComponents("file://server/") === ["file://server/"]
6028      * getPathComponents("file://server") === ["file://server"]
6029      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6030      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6031      * getPathComponents("file:///") === ["file:///"]
6032      * getPathComponents("file://") === ["file://"]
6033      */
6034     function getPathComponents(path, currentDirectory) {
6035         if (currentDirectory === void 0) { currentDirectory = ""; }
6036         path = combinePaths(currentDirectory, path);
6037         return pathComponents(path, getRootLength(path));
6038     }
6039     ts.getPathComponents = getPathComponents;
6040     //// Path Formatting
6041     /**
6042      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6043      * segments (at indices > 0).
6044      *
6045      * ```ts
6046      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6047      * ```
6048      */
6049     function getPathFromPathComponents(pathComponents) {
6050         if (pathComponents.length === 0)
6051             return "";
6052         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6053         return root + pathComponents.slice(1).join(ts.directorySeparator);
6054     }
6055     ts.getPathFromPathComponents = getPathFromPathComponents;
6056     //// Path Normalization
6057     /**
6058      * Normalize path separators, converting `\` into `/`.
6059      */
6060     function normalizeSlashes(path) {
6061         var index = path.indexOf("\\");
6062         if (index === -1) {
6063             return path;
6064         }
6065         backslashRegExp.lastIndex = index; // prime regex with known position
6066         return path.replace(backslashRegExp, ts.directorySeparator);
6067     }
6068     ts.normalizeSlashes = normalizeSlashes;
6069     /**
6070      * Reduce an array of path components to a more simplified path by navigating any
6071      * `"."` or `".."` entries in the path.
6072      */
6073     function reducePathComponents(components) {
6074         if (!ts.some(components))
6075             return [];
6076         var reduced = [components[0]];
6077         for (var i = 1; i < components.length; i++) {
6078             var component = components[i];
6079             if (!component)
6080                 continue;
6081             if (component === ".")
6082                 continue;
6083             if (component === "..") {
6084                 if (reduced.length > 1) {
6085                     if (reduced[reduced.length - 1] !== "..") {
6086                         reduced.pop();
6087                         continue;
6088                     }
6089                 }
6090                 else if (reduced[0])
6091                     continue;
6092             }
6093             reduced.push(component);
6094         }
6095         return reduced;
6096     }
6097     ts.reducePathComponents = reducePathComponents;
6098     /**
6099      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6100      *
6101      * ```ts
6102      * // Non-rooted
6103      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6104      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6105      * // POSIX
6106      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6107      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6108      * // DOS
6109      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6110      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6111      * // URL
6112      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6113      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6114      * ```
6115      */
6116     function combinePaths(path) {
6117         var paths = [];
6118         for (var _i = 1; _i < arguments.length; _i++) {
6119             paths[_i - 1] = arguments[_i];
6120         }
6121         if (path)
6122             path = normalizeSlashes(path);
6123         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6124             var relativePath = paths_1[_a];
6125             if (!relativePath)
6126                 continue;
6127             relativePath = normalizeSlashes(relativePath);
6128             if (!path || getRootLength(relativePath) !== 0) {
6129                 path = relativePath;
6130             }
6131             else {
6132                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6133             }
6134         }
6135         return path;
6136     }
6137     ts.combinePaths = combinePaths;
6138     /**
6139      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6140      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6141      *
6142      * ```ts
6143      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6144      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6145      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6146      * ```
6147      */
6148     function resolvePath(path) {
6149         var paths = [];
6150         for (var _i = 1; _i < arguments.length; _i++) {
6151             paths[_i - 1] = arguments[_i];
6152         }
6153         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path));
6154     }
6155     ts.resolvePath = resolvePath;
6156     /**
6157      * Parse a path into an array containing a root component (at index 0) and zero or more path
6158      * components (at indices > 0). The result is normalized.
6159      * If the path is relative, the root component is `""`.
6160      * If the path is absolute, the root component includes the first path separator (`/`).
6161      *
6162      * ```ts
6163      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6164      * ```
6165      */
6166     function getNormalizedPathComponents(path, currentDirectory) {
6167         return reducePathComponents(getPathComponents(path, currentDirectory));
6168     }
6169     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6170     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6171         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6172     }
6173     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6174     function normalizePath(path) {
6175         path = normalizeSlashes(path);
6176         // Most paths don't require normalization
6177         if (!relativePathSegmentRegExp.test(path)) {
6178             return path;
6179         }
6180         // Some paths only require cleanup of `/./` or leading `./`
6181         var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, "");
6182         if (simplified !== path) {
6183             path = simplified;
6184             if (!relativePathSegmentRegExp.test(path)) {
6185                 return path;
6186             }
6187         }
6188         // Other paths require full normalization
6189         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6190         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6191     }
6192     ts.normalizePath = normalizePath;
6193     function getPathWithoutRoot(pathComponents) {
6194         if (pathComponents.length === 0)
6195             return "";
6196         return pathComponents.slice(1).join(ts.directorySeparator);
6197     }
6198     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6199         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6200     }
6201     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6202     function toPath(fileName, basePath, getCanonicalFileName) {
6203         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6204             ? normalizePath(fileName)
6205             : getNormalizedAbsolutePath(fileName, basePath);
6206         return getCanonicalFileName(nonCanonicalizedPath);
6207     }
6208     ts.toPath = toPath;
6209     function normalizePathAndParts(path) {
6210         path = normalizeSlashes(path);
6211         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6212         if (parts.length) {
6213             var joinedParts = root + parts.join(ts.directorySeparator);
6214             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6215         }
6216         else {
6217             return { path: root, parts: parts };
6218         }
6219     }
6220     ts.normalizePathAndParts = normalizePathAndParts;
6221     function removeTrailingDirectorySeparator(path) {
6222         if (hasTrailingDirectorySeparator(path)) {
6223             return path.substr(0, path.length - 1);
6224         }
6225         return path;
6226     }
6227     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6228     function ensureTrailingDirectorySeparator(path) {
6229         if (!hasTrailingDirectorySeparator(path)) {
6230             return path + ts.directorySeparator;
6231         }
6232         return path;
6233     }
6234     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6235     /**
6236      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6237      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6238      *
6239      * ```ts
6240      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6241      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6242      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6243      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6244      * ```
6245      */
6246     function ensurePathIsNonModuleName(path) {
6247         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6248     }
6249     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6250     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6251         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6252         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6253     }
6254     ts.changeAnyExtension = changeAnyExtension;
6255     //// Path Comparisons
6256     // check path for these segments: '', '.'. '..'
6257     var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/;
6258     function comparePathsWorker(a, b, componentComparer) {
6259         if (a === b)
6260             return 0 /* EqualTo */;
6261         if (a === undefined)
6262             return -1 /* LessThan */;
6263         if (b === undefined)
6264             return 1 /* GreaterThan */;
6265         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6266         //       need to perform path reduction.
6267         var aRoot = a.substring(0, getRootLength(a));
6268         var bRoot = b.substring(0, getRootLength(b));
6269         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6270         if (result !== 0 /* EqualTo */) {
6271             return result;
6272         }
6273         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6274         //       the non-root portion of the path
6275         var aRest = a.substring(aRoot.length);
6276         var bRest = b.substring(bRoot.length);
6277         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6278             return componentComparer(aRest, bRest);
6279         }
6280         // The path contains a relative path segment. Normalize the paths and perform a slower component
6281         // by component comparison.
6282         var aComponents = reducePathComponents(getPathComponents(a));
6283         var bComponents = reducePathComponents(getPathComponents(b));
6284         var sharedLength = Math.min(aComponents.length, bComponents.length);
6285         for (var i = 1; i < sharedLength; i++) {
6286             var result_2 = componentComparer(aComponents[i], bComponents[i]);
6287             if (result_2 !== 0 /* EqualTo */) {
6288                 return result_2;
6289             }
6290         }
6291         return ts.compareValues(aComponents.length, bComponents.length);
6292     }
6293     /**
6294      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6295      */
6296     function comparePathsCaseSensitive(a, b) {
6297         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6298     }
6299     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6300     /**
6301      * Performs a case-insensitive comparison of two paths.
6302      */
6303     function comparePathsCaseInsensitive(a, b) {
6304         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6305     }
6306     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6307     function comparePaths(a, b, currentDirectory, ignoreCase) {
6308         if (typeof currentDirectory === "string") {
6309             a = combinePaths(currentDirectory, a);
6310             b = combinePaths(currentDirectory, b);
6311         }
6312         else if (typeof currentDirectory === "boolean") {
6313             ignoreCase = currentDirectory;
6314         }
6315         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6316     }
6317     ts.comparePaths = comparePaths;
6318     function containsPath(parent, child, currentDirectory, ignoreCase) {
6319         if (typeof currentDirectory === "string") {
6320             parent = combinePaths(currentDirectory, parent);
6321             child = combinePaths(currentDirectory, child);
6322         }
6323         else if (typeof currentDirectory === "boolean") {
6324             ignoreCase = currentDirectory;
6325         }
6326         if (parent === undefined || child === undefined)
6327             return false;
6328         if (parent === child)
6329             return true;
6330         var parentComponents = reducePathComponents(getPathComponents(parent));
6331         var childComponents = reducePathComponents(getPathComponents(child));
6332         if (childComponents.length < parentComponents.length) {
6333             return false;
6334         }
6335         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6336         for (var i = 0; i < parentComponents.length; i++) {
6337             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6338             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6339                 return false;
6340             }
6341         }
6342         return true;
6343     }
6344     ts.containsPath = containsPath;
6345     /**
6346      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6347      * Comparison is case-sensitive between the canonical paths.
6348      *
6349      * Use `containsPath` if file names are not already reduced and absolute.
6350      */
6351     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6352         var canonicalFileName = getCanonicalFileName(fileName);
6353         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6354         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6355     }
6356     ts.startsWithDirectory = startsWithDirectory;
6357     //// Relative Paths
6358     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6359         var fromComponents = reducePathComponents(getPathComponents(from));
6360         var toComponents = reducePathComponents(getPathComponents(to));
6361         var start;
6362         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6363             var fromComponent = getCanonicalFileName(fromComponents[start]);
6364             var toComponent = getCanonicalFileName(toComponents[start]);
6365             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6366             if (!comparer(fromComponent, toComponent))
6367                 break;
6368         }
6369         if (start === 0) {
6370             return toComponents;
6371         }
6372         var components = toComponents.slice(start);
6373         var relative = [];
6374         for (; start < fromComponents.length; start++) {
6375             relative.push("..");
6376         }
6377         return __spreadArray(__spreadArray([""], relative, true), components, true);
6378     }
6379     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6380     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6381         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6382         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6383         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6384         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6385         return getPathFromPathComponents(pathComponents);
6386     }
6387     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6388     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6389         return !isRootedDiskPath(absoluteOrRelativePath)
6390             ? absoluteOrRelativePath
6391             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6392     }
6393     ts.convertToRelativePath = convertToRelativePath;
6394     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6395         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6396     }
6397     ts.getRelativePathFromFile = getRelativePathFromFile;
6398     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6399         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6400         var firstComponent = pathComponents[0];
6401         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6402             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6403             pathComponents[0] = prefix + firstComponent;
6404         }
6405         return getPathFromPathComponents(pathComponents);
6406     }
6407     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6408     function forEachAncestorDirectory(directory, callback) {
6409         while (true) {
6410             var result = callback(directory);
6411             if (result !== undefined) {
6412                 return result;
6413             }
6414             var parentPath = getDirectoryPath(directory);
6415             if (parentPath === directory) {
6416                 return undefined;
6417             }
6418             directory = parentPath;
6419         }
6420     }
6421     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6422     function isNodeModulesDirectory(dirPath) {
6423         return ts.endsWith(dirPath, "/node_modules");
6424     }
6425     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6426 })(ts || (ts = {}));
6427 var ts;
6428 (function (ts) {
6429     /**
6430      * djb2 hashing algorithm
6431      * http://www.cse.yorku.ca/~oz/hash.html
6432      */
6433     /* @internal */
6434     function generateDjb2Hash(data) {
6435         var acc = 5381;
6436         for (var i = 0; i < data.length; i++) {
6437             acc = ((acc << 5) + acc) + data.charCodeAt(i);
6438         }
6439         return acc.toString();
6440     }
6441     ts.generateDjb2Hash = generateDjb2Hash;
6442     /**
6443      * Set a high stack trace limit to provide more information in case of an error.
6444      * Called for command-line and server use cases.
6445      * Not called if TypeScript is used as a library.
6446      */
6447     /* @internal */
6448     function setStackTraceLimit() {
6449         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
6450             Error.stackTraceLimit = 100;
6451         }
6452     }
6453     ts.setStackTraceLimit = setStackTraceLimit;
6454     var FileWatcherEventKind;
6455     (function (FileWatcherEventKind) {
6456         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
6457         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
6458         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
6459     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
6460     /* @internal */
6461     var PollingInterval;
6462     (function (PollingInterval) {
6463         PollingInterval[PollingInterval["High"] = 2000] = "High";
6464         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
6465         PollingInterval[PollingInterval["Low"] = 250] = "Low";
6466     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
6467     /* @internal */
6468     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
6469     /* @internal */
6470     function getModifiedTime(host, fileName) {
6471         return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
6472     }
6473     ts.getModifiedTime = getModifiedTime;
6474     function createPollingIntervalBasedLevels(levels) {
6475         var _a;
6476         return _a = {},
6477             _a[PollingInterval.Low] = levels.Low,
6478             _a[PollingInterval.Medium] = levels.Medium,
6479             _a[PollingInterval.High] = levels.High,
6480             _a;
6481     }
6482     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
6483     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
6484     /* @internal */
6485     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
6486     /* @internal */
6487     function setCustomPollingValues(system) {
6488         if (!system.getEnvironmentVariable) {
6489             return;
6490         }
6491         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
6492         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
6493         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
6494         function getLevel(envVar, level) {
6495             return system.getEnvironmentVariable("".concat(envVar, "_").concat(level.toUpperCase()));
6496         }
6497         function getCustomLevels(baseVariable) {
6498             var customLevels;
6499             setCustomLevel("Low");
6500             setCustomLevel("Medium");
6501             setCustomLevel("High");
6502             return customLevels;
6503             function setCustomLevel(level) {
6504                 var customLevel = getLevel(baseVariable, level);
6505                 if (customLevel) {
6506                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
6507                 }
6508             }
6509         }
6510         function setCustomLevels(baseVariable, levels) {
6511             var customLevels = getCustomLevels(baseVariable);
6512             if (customLevels) {
6513                 setLevel("Low");
6514                 setLevel("Medium");
6515                 setLevel("High");
6516                 return true;
6517             }
6518             return false;
6519             function setLevel(level) {
6520                 levels[level] = customLevels[level] || levels[level];
6521             }
6522         }
6523         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
6524             var customLevels = getCustomLevels(baseVariable);
6525             return (pollingIntervalChanged || customLevels) &&
6526                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
6527         }
6528     }
6529     ts.setCustomPollingValues = setCustomPollingValues;
6530     function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) {
6531         var definedValueCopyToIndex = pollIndex;
6532         // Max visit would be all elements of the queue
6533         for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) {
6534             var watchedFile = queue[pollIndex];
6535             if (!watchedFile) {
6536                 continue;
6537             }
6538             else if (watchedFile.isClosed) {
6539                 queue[pollIndex] = undefined;
6540                 continue;
6541             }
6542             // Only files polled count towards chunkSize
6543             chunkSize--;
6544             var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName));
6545             if (watchedFile.isClosed) {
6546                 // Closed watcher as part of callback
6547                 queue[pollIndex] = undefined;
6548                 continue;
6549             }
6550             callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged);
6551             // Defragment the queue while we are at it
6552             if (queue[pollIndex]) {
6553                 // Copy this file to the non hole location
6554                 if (definedValueCopyToIndex < pollIndex) {
6555                     queue[definedValueCopyToIndex] = watchedFile;
6556                     queue[pollIndex] = undefined;
6557                 }
6558                 definedValueCopyToIndex++;
6559             }
6560         }
6561         // Return next poll index
6562         return pollIndex;
6563         function nextPollIndex() {
6564             pollIndex++;
6565             if (pollIndex === queue.length) {
6566                 if (definedValueCopyToIndex < pollIndex) {
6567                     // There are holes from definedValueCopyToIndex to end of queue, change queue size
6568                     queue.length = definedValueCopyToIndex;
6569                 }
6570                 pollIndex = 0;
6571                 definedValueCopyToIndex = 0;
6572             }
6573         }
6574     }
6575     /* @internal */
6576     function createDynamicPriorityPollingWatchFile(host) {
6577         var watchedFiles = [];
6578         var changedFilesInLastPoll = [];
6579         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
6580         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
6581         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
6582         return watchFile;
6583         function watchFile(fileName, callback, defaultPollingInterval) {
6584             var file = {
6585                 fileName: fileName,
6586                 callback: callback,
6587                 unchangedPolls: 0,
6588                 mtime: getModifiedTime(host, fileName)
6589             };
6590             watchedFiles.push(file);
6591             addToPollingIntervalQueue(file, defaultPollingInterval);
6592             return {
6593                 close: function () {
6594                     file.isClosed = true;
6595                     // Remove from watchedFiles
6596                     ts.unorderedRemoveItem(watchedFiles, file);
6597                     // Do not update polling interval queue since that will happen as part of polling
6598                 }
6599             };
6600         }
6601         function createPollingIntervalQueue(pollingInterval) {
6602             var queue = [];
6603             queue.pollingInterval = pollingInterval;
6604             queue.pollIndex = 0;
6605             queue.pollScheduled = false;
6606             return queue;
6607         }
6608         function pollPollingIntervalQueue(queue) {
6609             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
6610             // Set the next polling index and timeout
6611             if (queue.length) {
6612                 scheduleNextPoll(queue.pollingInterval);
6613             }
6614             else {
6615                 ts.Debug.assert(queue.pollIndex === 0);
6616                 queue.pollScheduled = false;
6617             }
6618         }
6619         function pollLowPollingIntervalQueue(queue) {
6620             // Always poll complete list of changedFilesInLastPoll
6621             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
6622             // Finally do the actual polling of the queue
6623             pollPollingIntervalQueue(queue);
6624             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
6625             // as pollPollingIntervalQueue wont schedule for next poll
6626             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
6627                 scheduleNextPoll(PollingInterval.Low);
6628             }
6629         }
6630         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
6631             return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat);
6632             function onWatchFileStat(watchedFile, pollIndex, fileChanged) {
6633                 if (fileChanged) {
6634                     watchedFile.unchangedPolls = 0;
6635                     // Changed files go to changedFilesInLastPoll queue
6636                     if (queue !== changedFilesInLastPoll) {
6637                         queue[pollIndex] = undefined;
6638                         addChangedFileToLowPollingIntervalQueue(watchedFile);
6639                     }
6640                 }
6641                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
6642                     watchedFile.unchangedPolls++;
6643                 }
6644                 else if (queue === changedFilesInLastPoll) {
6645                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
6646                     watchedFile.unchangedPolls = 1;
6647                     queue[pollIndex] = undefined;
6648                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
6649                 }
6650                 else if (pollingInterval !== PollingInterval.High) {
6651                     watchedFile.unchangedPolls++;
6652                     queue[pollIndex] = undefined;
6653                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
6654                 }
6655             }
6656         }
6657         function pollingIntervalQueue(pollingInterval) {
6658             switch (pollingInterval) {
6659                 case PollingInterval.Low:
6660                     return lowPollingIntervalQueue;
6661                 case PollingInterval.Medium:
6662                     return mediumPollingIntervalQueue;
6663                 case PollingInterval.High:
6664                     return highPollingIntervalQueue;
6665             }
6666         }
6667         function addToPollingIntervalQueue(file, pollingInterval) {
6668             pollingIntervalQueue(pollingInterval).push(file);
6669             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
6670         }
6671         function addChangedFileToLowPollingIntervalQueue(file) {
6672             changedFilesInLastPoll.push(file);
6673             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
6674         }
6675         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
6676             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
6677                 scheduleNextPoll(pollingInterval);
6678             }
6679         }
6680         function scheduleNextPoll(pollingInterval) {
6681             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
6682         }
6683     }
6684     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
6685     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
6686         // One file can have multiple watchers
6687         var fileWatcherCallbacks = ts.createMultiMap();
6688         var dirWatchers = new ts.Map();
6689         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6690         return nonPollingWatchFile;
6691         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
6692             var filePath = toCanonicalName(fileName);
6693             fileWatcherCallbacks.add(filePath, callback);
6694             var dirPath = ts.getDirectoryPath(filePath) || ".";
6695             var watcher = dirWatchers.get(dirPath) ||
6696                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
6697             watcher.referenceCount++;
6698             return {
6699                 close: function () {
6700                     if (watcher.referenceCount === 1) {
6701                         watcher.close();
6702                         dirWatchers.delete(dirPath);
6703                     }
6704                     else {
6705                         watcher.referenceCount--;
6706                     }
6707                     fileWatcherCallbacks.remove(filePath, callback);
6708                 }
6709             };
6710         }
6711         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
6712             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
6713                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
6714                 if (!ts.isString(relativeFileName))
6715                     return;
6716                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
6717                 // Some applications save a working file via rename operations
6718                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
6719                 if (callbacks) {
6720                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
6721                         var fileCallback = callbacks_1[_i];
6722                         fileCallback(fileName, FileWatcherEventKind.Changed);
6723                     }
6724                 }
6725             }, 
6726             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
6727             watcher.referenceCount = 0;
6728             dirWatchers.set(dirPath, watcher);
6729             return watcher;
6730         }
6731     }
6732     function createFixedChunkSizePollingWatchFile(host) {
6733         var watchedFiles = [];
6734         var pollIndex = 0;
6735         var pollScheduled;
6736         return watchFile;
6737         function watchFile(fileName, callback) {
6738             var file = {
6739                 fileName: fileName,
6740                 callback: callback,
6741                 mtime: getModifiedTime(host, fileName)
6742             };
6743             watchedFiles.push(file);
6744             scheduleNextPoll();
6745             return {
6746                 close: function () {
6747                     file.isClosed = true;
6748                     ts.unorderedRemoveItem(watchedFiles, file);
6749                 }
6750             };
6751         }
6752         function pollQueue() {
6753             pollScheduled = undefined;
6754             pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]);
6755             scheduleNextPoll();
6756         }
6757         function scheduleNextPoll() {
6758             if (!watchedFiles.length || pollScheduled)
6759                 return;
6760             pollScheduled = host.setTimeout(pollQueue, PollingInterval.High);
6761         }
6762     }
6763     /* @internal */
6764     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
6765         var cache = new ts.Map();
6766         var callbacksCache = ts.createMultiMap();
6767         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6768         return function (fileName, callback, pollingInterval, options) {
6769             var path = toCanonicalFileName(fileName);
6770             var existing = cache.get(path);
6771             if (existing) {
6772                 existing.refCount++;
6773             }
6774             else {
6775                 cache.set(path, {
6776                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
6777                     refCount: 1
6778                 });
6779             }
6780             callbacksCache.add(path, callback);
6781             return {
6782                 close: function () {
6783                     var watcher = ts.Debug.checkDefined(cache.get(path));
6784                     callbacksCache.remove(path, callback);
6785                     watcher.refCount--;
6786                     if (watcher.refCount)
6787                         return;
6788                     cache.delete(path);
6789                     ts.closeFileWatcherOf(watcher);
6790                 }
6791             };
6792         };
6793     }
6794     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
6795     /**
6796      * Returns true if file status changed
6797      */
6798     /*@internal*/
6799     function onWatchedFileStat(watchedFile, modifiedTime) {
6800         var oldTime = watchedFile.mtime.getTime();
6801         var newTime = modifiedTime.getTime();
6802         if (oldTime !== newTime) {
6803             watchedFile.mtime = modifiedTime;
6804             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
6805             return true;
6806         }
6807         return false;
6808     }
6809     ts.onWatchedFileStat = onWatchedFileStat;
6810     /*@internal*/
6811     function getFileWatcherEventKind(oldTime, newTime) {
6812         return oldTime === 0
6813             ? FileWatcherEventKind.Created
6814             : newTime === 0
6815                 ? FileWatcherEventKind.Deleted
6816                 : FileWatcherEventKind.Changed;
6817     }
6818     ts.getFileWatcherEventKind = getFileWatcherEventKind;
6819     /*@internal*/
6820     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
6821     /*@internal*/
6822     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
6823     /*@internal*/
6824     function setSysLog(logger) {
6825         ts.sysLog = logger;
6826     }
6827     ts.setSysLog = setSysLog;
6828     /**
6829      * Watch the directory recursively using host provided method to watch child directories
6830      * that means if this is recursive watcher, watch the children directories as well
6831      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
6832      */
6833     /*@internal*/
6834     function createDirectoryWatcherSupportingRecursive(_a) {
6835         var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout;
6836         var cache = new ts.Map();
6837         var callbackCache = ts.createMultiMap();
6838         var cacheToUpdateChildWatches = new ts.Map();
6839         var timerToUpdateChildWatches;
6840         var filePathComparer = ts.getStringComparer(!useCaseSensitiveFileNames);
6841         var toCanonicalFilePath = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6842         return function (dirName, callback, recursive, options) { return recursive ?
6843             createDirectoryWatcher(dirName, options, callback) :
6844             watchDirectory(dirName, callback, recursive, options); };
6845         /**
6846          * Create the directory watcher for the dirPath.
6847          */
6848         function createDirectoryWatcher(dirName, options, callback) {
6849             var dirPath = toCanonicalFilePath(dirName);
6850             var directoryWatcher = cache.get(dirPath);
6851             if (directoryWatcher) {
6852                 directoryWatcher.refCount++;
6853             }
6854             else {
6855                 directoryWatcher = {
6856                     watcher: watchDirectory(dirName, function (fileName) {
6857                         if (isIgnoredPath(fileName, options))
6858                             return;
6859                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
6860                             // Call the actual callback
6861                             invokeCallbacks(dirPath, fileName);
6862                             // Iterate through existing children and update the watches if needed
6863                             updateChildWatches(dirName, dirPath, options);
6864                         }
6865                         else {
6866                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
6867                         }
6868                     }, /*recursive*/ false, options),
6869                     refCount: 1,
6870                     childWatches: ts.emptyArray
6871                 };
6872                 cache.set(dirPath, directoryWatcher);
6873                 updateChildWatches(dirName, dirPath, options);
6874             }
6875             var callbackToAdd = callback && { dirName: dirName, callback: callback };
6876             if (callbackToAdd) {
6877                 callbackCache.add(dirPath, callbackToAdd);
6878             }
6879             return {
6880                 dirName: dirName,
6881                 close: function () {
6882                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
6883                     if (callbackToAdd)
6884                         callbackCache.remove(dirPath, callbackToAdd);
6885                     directoryWatcher.refCount--;
6886                     if (directoryWatcher.refCount)
6887                         return;
6888                     cache.delete(dirPath);
6889                     ts.closeFileWatcherOf(directoryWatcher);
6890                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
6891                 }
6892             };
6893         }
6894         function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
6895             var fileName;
6896             var invokeMap;
6897             if (ts.isString(fileNameOrInvokeMap)) {
6898                 fileName = fileNameOrInvokeMap;
6899             }
6900             else {
6901                 invokeMap = fileNameOrInvokeMap;
6902             }
6903             // Call the actual callback
6904             callbackCache.forEach(function (callbacks, rootDirName) {
6905                 var _a;
6906                 if (invokeMap && invokeMap.get(rootDirName) === true)
6907                     return;
6908                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
6909                     if (invokeMap) {
6910                         if (fileNames) {
6911                             var existing = invokeMap.get(rootDirName);
6912                             if (existing) {
6913                                 (_a = existing).push.apply(_a, fileNames);
6914                             }
6915                             else {
6916                                 invokeMap.set(rootDirName, fileNames.slice());
6917                             }
6918                         }
6919                         else {
6920                             invokeMap.set(rootDirName, true);
6921                         }
6922                     }
6923                     else {
6924                         callbacks.forEach(function (_a) {
6925                             var callback = _a.callback;
6926                             return callback(fileName);
6927                         });
6928                     }
6929                 }
6930             });
6931         }
6932         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
6933             // Iterate through existing children and update the watches if needed
6934             var parentWatcher = cache.get(dirPath);
6935             if (parentWatcher && directoryExists(dirName)) {
6936                 // Schedule the update and postpone invoke for callbacks
6937                 scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
6938                 return;
6939             }
6940             // Call the actual callbacks and remove child watches
6941             invokeCallbacks(dirPath, fileName);
6942             removeChildWatches(parentWatcher);
6943         }
6944         function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
6945             var existing = cacheToUpdateChildWatches.get(dirPath);
6946             if (existing) {
6947                 existing.fileNames.push(fileName);
6948             }
6949             else {
6950                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
6951             }
6952             if (timerToUpdateChildWatches) {
6953                 clearTimeout(timerToUpdateChildWatches);
6954                 timerToUpdateChildWatches = undefined;
6955             }
6956             timerToUpdateChildWatches = setTimeout(onTimerToUpdateChildWatches, 1000);
6957         }
6958         function onTimerToUpdateChildWatches() {
6959             timerToUpdateChildWatches = undefined;
6960             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: ".concat(cacheToUpdateChildWatches.size));
6961             var start = ts.timestamp();
6962             var invokeMap = new ts.Map();
6963             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
6964                 var result = cacheToUpdateChildWatches.entries().next();
6965                 ts.Debug.assert(!result.done);
6966                 var _a = result.value, dirPath = _a[0], _b = _a[1], dirName = _b.dirName, options = _b.options, fileNames = _b.fileNames;
6967                 cacheToUpdateChildWatches.delete(dirPath);
6968                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
6969                 // to ensure that all the changes are reflected at this time
6970                 var hasChanges = updateChildWatches(dirName, dirPath, options);
6971                 invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
6972             }
6973             ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: ".concat(ts.timestamp() - start, "ms:: ").concat(cacheToUpdateChildWatches.size));
6974             callbackCache.forEach(function (callbacks, rootDirName) {
6975                 var existing = invokeMap.get(rootDirName);
6976                 if (existing) {
6977                     callbacks.forEach(function (_a) {
6978                         var callback = _a.callback, dirName = _a.dirName;
6979                         if (ts.isArray(existing)) {
6980                             existing.forEach(callback);
6981                         }
6982                         else {
6983                             callback(dirName);
6984                         }
6985                     });
6986                 }
6987             });
6988             var elapsed = ts.timestamp() - start;
6989             ts.sysLog("sysLog:: Elapsed:: ".concat(elapsed, "ms:: onTimerToUpdateChildWatches:: ").concat(cacheToUpdateChildWatches.size, " ").concat(timerToUpdateChildWatches));
6990         }
6991         function removeChildWatches(parentWatcher) {
6992             if (!parentWatcher)
6993                 return;
6994             var existingChildWatches = parentWatcher.childWatches;
6995             parentWatcher.childWatches = ts.emptyArray;
6996             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
6997                 var childWatcher = existingChildWatches_1[_i];
6998                 childWatcher.close();
6999                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
7000             }
7001         }
7002         function updateChildWatches(parentDir, parentDirPath, options) {
7003             // Iterate through existing children and update the watches if needed
7004             var parentWatcher = cache.get(parentDirPath);
7005             if (!parentWatcher)
7006                 return false;
7007             var newChildWatches;
7008             var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) {
7009                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
7010                 // Filter our the symbolic link directories since those arent included in recursive watch
7011                 // which is same behaviour when recursive: true is passed to fs.watch
7012                 return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, ts.normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
7013             }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
7014             parentWatcher.childWatches = newChildWatches || ts.emptyArray;
7015             return hasChanges;
7016             /**
7017              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
7018              */
7019             function createAndAddChildDirectoryWatcher(childName) {
7020                 var result = createDirectoryWatcher(childName, options);
7021                 addChildDirectoryWatcher(result);
7022             }
7023             /**
7024              * Add child directory watcher to the new ChildDirectoryWatcher list
7025              */
7026             function addChildDirectoryWatcher(childWatcher) {
7027                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
7028             }
7029         }
7030         function isIgnoredPath(path, options) {
7031             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); }) ||
7032                 isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory);
7033         }
7034         function isInPath(path, searchPath) {
7035             if (ts.stringContains(path, searchPath))
7036                 return true;
7037             if (useCaseSensitiveFileNames)
7038                 return false;
7039             return ts.stringContains(toCanonicalFilePath(path), searchPath);
7040         }
7041     }
7042     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
7043     /*@internal*/
7044     var FileSystemEntryKind;
7045     (function (FileSystemEntryKind) {
7046         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
7047         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
7048     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
7049     /*@internal*/
7050     function createFileWatcherCallback(callback) {
7051         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
7052     }
7053     ts.createFileWatcherCallback = createFileWatcherCallback;
7054     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
7055         return function (eventName) {
7056             if (eventName === "rename") {
7057                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
7058             }
7059             else {
7060                 // Change
7061                 callback(fileName, FileWatcherEventKind.Changed);
7062             }
7063         };
7064     }
7065     function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) {
7066         return ((options === null || options === void 0 ? void 0 : options.excludeDirectories) || (options === null || options === void 0 ? void 0 : options.excludeFiles)) && (ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) ||
7067             ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory()));
7068     }
7069     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) {
7070         return function (eventName, relativeFileName) {
7071             // In watchDirectory we only care about adding and removing files (when event name is
7072             // "rename"); changes made within files are handled by corresponding fileWatchers (when
7073             // event name is "change")
7074             if (eventName === "rename") {
7075                 // When deleting a file, the passed baseFileName is null
7076                 var fileName = !relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName));
7077                 if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) {
7078                     callback(fileName);
7079                 }
7080             }
7081         };
7082     }
7083     /*@internal*/
7084     function createSystemWatchFunctions(_a) {
7085         var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind;
7086         var dynamicPollingWatchFile;
7087         var fixedChunkSizePollingWatchFile;
7088         var nonPollingWatchFile;
7089         var hostRecursiveDirectoryWatcher;
7090         return {
7091             watchFile: watchFile,
7092             watchDirectory: watchDirectory
7093         };
7094         function watchFile(fileName, callback, pollingInterval, options) {
7095             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
7096             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
7097             switch (watchFileKind) {
7098                 case ts.WatchFileKind.FixedPollingInterval:
7099                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
7100                 case ts.WatchFileKind.PriorityPollingInterval:
7101                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
7102                 case ts.WatchFileKind.DynamicPriorityPolling:
7103                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
7104                 case ts.WatchFileKind.FixedChunkSizePolling:
7105                     return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined);
7106                 case ts.WatchFileKind.UseFsEvents:
7107                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
7108                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
7109                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
7110                     if (!nonPollingWatchFile) {
7111                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
7112                     }
7113                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
7114                 default:
7115                     ts.Debug.assertNever(watchFileKind);
7116             }
7117         }
7118         function ensureDynamicPollingWatchFile() {
7119             return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
7120         }
7121         function ensureFixedChunkSizePollingWatchFile() {
7122             return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
7123         }
7124         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
7125             if (options && options.watchFile !== undefined)
7126                 return options;
7127             switch (tscWatchFile) {
7128                 case "PriorityPollingInterval":
7129                     // Use polling interval based on priority when create watch using host.watchFile
7130                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
7131                 case "DynamicPriorityPolling":
7132                     // Use polling interval but change the interval depending on file changes and their default polling interval
7133                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
7134                 case "UseFsEvents":
7135                     // Use notifications from FS to watch with falling back to fs.watchFile
7136                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
7137                 case "UseFsEventsWithFallbackDynamicPolling":
7138                     // Use notifications from FS to watch with falling back to dynamic watch file
7139                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
7140                 case "UseFsEventsOnParentDirectory":
7141                     useNonPollingWatchers = true;
7142                 // fall through
7143                 default:
7144                     return useNonPollingWatchers ?
7145                         // Use notifications from FS to watch with falling back to fs.watchFile
7146                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
7147                         // Default to do not use fixed polling interval
7148                         { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval };
7149             }
7150         }
7151         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
7152             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
7153             return {
7154                 watchFile: watchFile,
7155                 fallbackPolling: defaultFallbackPolling === undefined ?
7156                     fallbackPolling :
7157                     defaultFallbackPolling
7158             };
7159         }
7160         function watchDirectory(directoryName, callback, recursive, options) {
7161             if (fsSupportsRecursiveFsWatch) {
7162                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
7163             }
7164             if (!hostRecursiveDirectoryWatcher) {
7165                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
7166                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
7167                     getCurrentDirectory: getCurrentDirectory,
7168                     directoryExists: directoryExists,
7169                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
7170                     watchDirectory: nonRecursiveWatchDirectory,
7171                     realpath: realpath,
7172                     setTimeout: setTimeout,
7173                     clearTimeout: clearTimeout
7174                 });
7175             }
7176             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
7177         }
7178         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
7179             ts.Debug.assert(!recursive);
7180             var watchDirectoryOptions = updateOptionsForWatchDirectory(options);
7181             var watchDirectoryKind = ts.Debug.checkDefined(watchDirectoryOptions.watchDirectory);
7182             switch (watchDirectoryKind) {
7183                 case ts.WatchDirectoryKind.FixedPollingInterval:
7184                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
7185                     /*options*/ undefined);
7186                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
7187                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
7188                     /*options*/ undefined);
7189                 case ts.WatchDirectoryKind.FixedChunkSizePolling:
7190                     return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, 
7191                     /* pollingInterval */ undefined, 
7192                     /*options*/ undefined);
7193                 case ts.WatchDirectoryKind.UseFsEvents:
7194                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions));
7195                 default:
7196                     ts.Debug.assertNever(watchDirectoryKind);
7197             }
7198         }
7199         function updateOptionsForWatchDirectory(options) {
7200             if (options && options.watchDirectory !== undefined)
7201                 return options;
7202             switch (tscWatchDirectory) {
7203                 case "RecursiveDirectoryUsingFsWatchFile":
7204                     // Use polling interval based on priority when create watch using host.watchFile
7205                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
7206                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
7207                     // Use polling interval but change the interval depending on file changes and their default polling interval
7208                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
7209                 default:
7210                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
7211                     return {
7212                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
7213                         fallbackPolling: defaultFallbackPolling !== undefined ?
7214                             defaultFallbackPolling :
7215                             undefined
7216                     };
7217             }
7218         }
7219     }
7220     ts.createSystemWatchFunctions = createSystemWatchFunctions;
7221     /**
7222      * patch writefile to create folder before writing the file
7223      */
7224     /*@internal*/
7225     function patchWriteFileEnsuringDirectory(sys) {
7226         // patch writefile to create folder before writing the file
7227         var originalWriteFile = sys.writeFile;
7228         sys.writeFile = function (path, data, writeBom) {
7229             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); });
7230         };
7231     }
7232     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
7233     function getNodeMajorVersion() {
7234         if (typeof process === "undefined") {
7235             return undefined;
7236         }
7237         var version = process.version;
7238         if (!version) {
7239             return undefined;
7240         }
7241         var dot = version.indexOf(".");
7242         if (dot === -1) {
7243             return undefined;
7244         }
7245         return parseInt(version.substring(1, dot));
7246     }
7247     ts.getNodeMajorVersion = getNodeMajorVersion;
7248     // TODO: GH#18217 this is used as if it's certainly defined in many places.
7249     // eslint-disable-next-line prefer-const
7250     ts.sys = (function () {
7251         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
7252         // byte order mark from the specified encoding. Using any other byte order mark does
7253         // not actually work.
7254         var byteOrderMarkIndicator = "\uFEFF";
7255         function getNodeSystem() {
7256             var _a;
7257             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
7258             var _fs = require("fs");
7259             var _path = require("path");
7260             var _os = require("os");
7261             // crypto can be absent on reduced node installations
7262             var _crypto;
7263             try {
7264                 _crypto = require("crypto");
7265             }
7266             catch (_b) {
7267                 _crypto = undefined;
7268             }
7269             var activeSession;
7270             var profilePath = "./profile.cpuprofile";
7271             var hitSystemWatcherLimit = false;
7272             var Buffer = require("buffer").Buffer;
7273             var nodeVersion = getNodeMajorVersion();
7274             var isNode4OrLater = nodeVersion >= 4;
7275             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
7276             var platform = _os.platform();
7277             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
7278             var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync;
7279             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
7280             var getCurrentDirectory = ts.memoize(function () { return process.cwd(); });
7281             var _c = createSystemWatchFunctions({
7282                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
7283                 getModifiedTime: getModifiedTime,
7284                 setTimeout: setTimeout,
7285                 clearTimeout: clearTimeout,
7286                 fsWatch: fsWatch,
7287                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
7288                 getCurrentDirectory: getCurrentDirectory,
7289                 fileExists: fileExists,
7290                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7291                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7292                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
7293                 directoryExists: directoryExists,
7294                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
7295                 realpath: realpath,
7296                 tscWatchFile: process.env.TSC_WATCHFILE,
7297                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
7298                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
7299                 defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); },
7300             }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory;
7301             var nodeSystem = {
7302                 args: process.argv.slice(2),
7303                 newLine: _os.EOL,
7304                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
7305                 write: function (s) {
7306                     process.stdout.write(s);
7307                 },
7308                 getWidthOfTerminal: function () {
7309                     return process.stdout.columns;
7310                 },
7311                 writeOutputIsTTY: function () {
7312                     return process.stdout.isTTY;
7313                 },
7314                 readFile: readFile,
7315                 writeFile: writeFile,
7316                 watchFile: watchFile,
7317                 watchDirectory: watchDirectory,
7318                 resolvePath: function (path) { return _path.resolve(path); },
7319                 fileExists: fileExists,
7320                 directoryExists: directoryExists,
7321                 createDirectory: function (directoryName) {
7322                     if (!nodeSystem.directoryExists(directoryName)) {
7323                         // Wrapped in a try-catch to prevent crashing if we are in a race
7324                         // with another copy of ourselves to create the same directory
7325                         try {
7326                             _fs.mkdirSync(directoryName);
7327                         }
7328                         catch (e) {
7329                             if (e.code !== "EEXIST") {
7330                                 // Failed for some other reason (access denied?); still throw
7331                                 throw e;
7332                             }
7333                         }
7334                     }
7335                 },
7336                 getExecutingFilePath: function () {
7337                     return __filename;
7338                 },
7339                 getCurrentDirectory: getCurrentDirectory,
7340                 getDirectories: getDirectories,
7341                 getEnvironmentVariable: function (name) {
7342                     return process.env[name] || "";
7343                 },
7344                 readDirectory: readDirectory,
7345                 getModifiedTime: getModifiedTime,
7346                 setModifiedTime: setModifiedTime,
7347                 deleteFile: deleteFile,
7348                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
7349                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
7350                 getMemoryUsage: function () {
7351                     if (global.gc) {
7352                         global.gc();
7353                     }
7354                     return process.memoryUsage().heapUsed;
7355                 },
7356                 getFileSize: function (path) {
7357                     try {
7358                         var stat = statSync(path);
7359                         if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
7360                             return stat.size;
7361                         }
7362                     }
7363                     catch ( /*ignore*/_a) { /*ignore*/ }
7364                     return 0;
7365                 },
7366                 exit: function (exitCode) {
7367                     disableCPUProfiler(function () { return process.exit(exitCode); });
7368                 },
7369                 enableCPUProfiler: enableCPUProfiler,
7370                 disableCPUProfiler: disableCPUProfiler,
7371                 cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); },
7372                 realpath: realpath,
7373                 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); }),
7374                 tryEnableSourceMapsForHost: function () {
7375                     try {
7376                         require("source-map-support").install();
7377                     }
7378                     catch (_a) {
7379                         // Could not enable source maps.
7380                     }
7381                 },
7382                 setTimeout: setTimeout,
7383                 clearTimeout: clearTimeout,
7384                 clearScreen: function () {
7385                     process.stdout.write("\x1Bc");
7386                 },
7387                 setBlocking: function () {
7388                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
7389                         process.stdout._handle.setBlocking(true);
7390                     }
7391                 },
7392                 bufferFrom: bufferFrom,
7393                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
7394                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
7395                 require: function (baseDir, moduleName) {
7396                     try {
7397                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
7398                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
7399                     }
7400                     catch (error) {
7401                         return { module: undefined, modulePath: undefined, error: error };
7402                     }
7403                 }
7404             };
7405             return nodeSystem;
7406             /**
7407              * `throwIfNoEntry` was added so recently that it's not in the node types.
7408              * This helper encapsulates the mitigating usage of `any`.
7409              * See https://github.com/nodejs/node/pull/33716
7410              */
7411             function statSync(path) {
7412                 // throwIfNoEntry will be ignored by older versions of node
7413                 return _fs.statSync(path, { throwIfNoEntry: false });
7414             }
7415             /**
7416              * Uses the builtin inspector APIs to capture a CPU profile
7417              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
7418              */
7419             function enableCPUProfiler(path, cb) {
7420                 if (activeSession) {
7421                     cb();
7422                     return false;
7423                 }
7424                 var inspector = require("inspector");
7425                 if (!inspector || !inspector.Session) {
7426                     cb();
7427                     return false;
7428                 }
7429                 var session = new inspector.Session();
7430                 session.connect();
7431                 session.post("Profiler.enable", function () {
7432                     session.post("Profiler.start", function () {
7433                         activeSession = session;
7434                         profilePath = path;
7435                         cb();
7436                     });
7437                 });
7438                 return true;
7439             }
7440             /**
7441              * Strips non-TS paths from the profile, so users with private projects shouldn't
7442              * need to worry about leaking paths by submitting a cpu profile to us
7443              */
7444             function cleanupPaths(profile) {
7445                 var externalFileCounter = 0;
7446                 var remappedPaths = new ts.Map();
7447                 var normalizedDir = ts.normalizeSlashes(__dirname);
7448                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
7449                 var fileUrlRoot = "file://".concat(ts.getRootLength(normalizedDir) === 1 ? "" : "/").concat(normalizedDir);
7450                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
7451                     var node = _a[_i];
7452                     if (node.callFrame.url) {
7453                         var url = ts.normalizeSlashes(node.callFrame.url);
7454                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
7455                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
7456                         }
7457                         else if (!nativePattern.test(url)) {
7458                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external".concat(externalFileCounter, ".js"))).get(url);
7459                             externalFileCounter++;
7460                         }
7461                     }
7462                 }
7463                 return profile;
7464             }
7465             function disableCPUProfiler(cb) {
7466                 if (activeSession && activeSession !== "stopping") {
7467                     var s_1 = activeSession;
7468                     activeSession.post("Profiler.stop", function (err, _a) {
7469                         var _b;
7470                         var profile = _a.profile;
7471                         if (!err) {
7472                             try {
7473                                 if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) {
7474                                     profilePath = _path.join(profilePath, "".concat((new Date()).toISOString().replace(/:/g, "-"), "+P").concat(process.pid, ".cpuprofile"));
7475                                 }
7476                             }
7477                             catch (_c) {
7478                                 // do nothing and ignore fallible fs operation
7479                             }
7480                             try {
7481                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
7482                             }
7483                             catch (_d) {
7484                                 // do nothing and ignore fallible fs operation
7485                             }
7486                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
7487                         }
7488                         activeSession = undefined;
7489                         s_1.disconnect();
7490                         cb();
7491                     });
7492                     activeSession = "stopping";
7493                     return true;
7494                 }
7495                 else {
7496                     cb();
7497                     return false;
7498                 }
7499             }
7500             function bufferFrom(input, encoding) {
7501                 // See https://github.com/Microsoft/TypeScript/issues/25652
7502                 return Buffer.from && Buffer.from !== Int8Array.from
7503                     ? Buffer.from(input, encoding)
7504                     : new Buffer(input, encoding);
7505             }
7506             function isFileSystemCaseSensitive() {
7507                 // win32\win64 are case insensitive platforms
7508                 if (platform === "win32" || platform === "win64") {
7509                     return false;
7510                 }
7511                 // If this file exists under a different case, we must be case-insensitve.
7512                 return !fileExists(swapCase(__filename));
7513             }
7514             /** Convert all lowercase chars to uppercase, and vice-versa */
7515             function swapCase(s) {
7516                 return s.replace(/\w/g, function (ch) {
7517                     var up = ch.toUpperCase();
7518                     return ch === up ? ch.toLowerCase() : up;
7519                 });
7520             }
7521             function fsWatchFileWorker(fileName, callback, pollingInterval) {
7522                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
7523                 var eventKind;
7524                 return {
7525                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
7526                 };
7527                 function fileChanged(curr, prev) {
7528                     // 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)
7529                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
7530                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
7531                     if (+curr.mtime === 0) {
7532                         if (isPreviouslyDeleted) {
7533                             // Already deleted file, no need to callback again
7534                             return;
7535                         }
7536                         eventKind = FileWatcherEventKind.Deleted;
7537                     }
7538                     else if (isPreviouslyDeleted) {
7539                         eventKind = FileWatcherEventKind.Created;
7540                     }
7541                     // If there is no change in modified time, ignore the event
7542                     else if (+curr.mtime === +prev.mtime) {
7543                         return;
7544                     }
7545                     else {
7546                         // File changed
7547                         eventKind = FileWatcherEventKind.Changed;
7548                     }
7549                     callback(fileName, eventKind);
7550                 }
7551             }
7552             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
7553                 var options;
7554                 var lastDirectoryPartWithDirectorySeparator;
7555                 var lastDirectoryPart;
7556                 if (isLinuxOrMacOs) {
7557                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
7558                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
7559                 }
7560                 /** Watcher for the file system entry depending on whether it is missing or present */
7561                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7562                     watchMissingFileSystemEntry() :
7563                     watchPresentFileSystemEntry();
7564                 return {
7565                     close: function () {
7566                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
7567                         watcher.close();
7568                         watcher = undefined;
7569                     }
7570                 };
7571                 /**
7572                  * Invoke the callback with rename and update the watcher if not closed
7573                  * @param createWatcher
7574                  */
7575                 function invokeCallbackAndUpdateWatcher(createWatcher) {
7576                     ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher"));
7577                     // Call the callback for current directory
7578                     callback("rename", "");
7579                     // If watcher is not closed, update it
7580                     if (watcher) {
7581                         watcher.close();
7582                         watcher = createWatcher();
7583                     }
7584                 }
7585                 /**
7586                  * Watch the file or directory that is currently present
7587                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
7588                  */
7589                 function watchPresentFileSystemEntry() {
7590                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7591                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7592                     if (options === undefined) {
7593                         if (fsSupportsRecursiveFsWatch) {
7594                             options = { persistent: true, recursive: !!recursive };
7595                         }
7596                         else {
7597                             options = { persistent: true };
7598                         }
7599                     }
7600                     if (hitSystemWatcherLimit) {
7601                         ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile"));
7602                         return watchPresentFileSystemEntryWithFsWatchFile();
7603                     }
7604                     try {
7605                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
7606                             callbackChangingToMissingFileSystemEntry :
7607                             callback);
7608                         // Watch the missing file or directory or error
7609                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
7610                         return presentWatcher;
7611                     }
7612                     catch (e) {
7613                         // Catch the exception and use polling instead
7614                         // 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
7615                         // so instead of throwing error, use fs.watchFile
7616                         hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC");
7617                         ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile"));
7618                         return watchPresentFileSystemEntryWithFsWatchFile();
7619                     }
7620                 }
7621                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
7622                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
7623                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
7624                     return event === "rename" &&
7625                         (!relativeName ||
7626                             relativeName === lastDirectoryPart ||
7627                             (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) &&
7628                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7629                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
7630                         callback(event, relativeName);
7631                 }
7632                 /**
7633                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
7634                  * 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
7635                  */
7636                 function watchPresentFileSystemEntryWithFsWatchFile() {
7637                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
7638                 }
7639                 /**
7640                  * Watch the file or directory that is missing
7641                  * and switch to existing file or directory when the missing filesystem entry is created
7642                  */
7643                 function watchMissingFileSystemEntry() {
7644                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
7645                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
7646                             // Call the callback for current file or directory
7647                             // For now it could be callback for the inner directory creation,
7648                             // but just return current directory, better than current no-op
7649                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
7650                         }
7651                     }, fallbackPollingInterval, fallbackOptions);
7652                 }
7653             }
7654             function readFileWorker(fileName, _encoding) {
7655                 var buffer;
7656                 try {
7657                     buffer = _fs.readFileSync(fileName);
7658                 }
7659                 catch (e) {
7660                     return undefined;
7661                 }
7662                 var len = buffer.length;
7663                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
7664                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
7665                     // flip all byte pairs and treat as little endian.
7666                     len &= ~1; // Round down to a multiple of 2
7667                     for (var i = 0; i < len; i += 2) {
7668                         var temp = buffer[i];
7669                         buffer[i] = buffer[i + 1];
7670                         buffer[i + 1] = temp;
7671                     }
7672                     return buffer.toString("utf16le", 2);
7673                 }
7674                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
7675                     // Little endian UTF-16 byte order mark detected
7676                     return buffer.toString("utf16le", 2);
7677                 }
7678                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
7679                     // UTF-8 byte order mark detected
7680                     return buffer.toString("utf8", 3);
7681                 }
7682                 // Default is UTF-8 with no byte order mark
7683                 return buffer.toString("utf8");
7684             }
7685             function readFile(fileName, _encoding) {
7686                 ts.perfLogger.logStartReadFile(fileName);
7687                 var file = readFileWorker(fileName, _encoding);
7688                 ts.perfLogger.logStopReadFile();
7689                 return file;
7690             }
7691             function writeFile(fileName, data, writeByteOrderMark) {
7692                 ts.perfLogger.logEvent("WriteFile: " + fileName);
7693                 // If a BOM is required, emit one
7694                 if (writeByteOrderMark) {
7695                     data = byteOrderMarkIndicator + data;
7696                 }
7697                 var fd;
7698                 try {
7699                     fd = _fs.openSync(fileName, "w");
7700                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
7701                 }
7702                 finally {
7703                     if (fd !== undefined) {
7704                         _fs.closeSync(fd);
7705                     }
7706                 }
7707             }
7708             function getAccessibleFileSystemEntries(path) {
7709                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
7710                 try {
7711                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
7712                     var files = [];
7713                     var directories = [];
7714                     for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7715                         var dirent = entries_1[_i];
7716                         // withFileTypes is not supported before Node 10.10.
7717                         var entry = typeof dirent === "string" ? dirent : dirent.name;
7718                         // This is necessary because on some file system node fails to exclude
7719                         // "." and "..". See https://github.com/nodejs/node/issues/4002
7720                         if (entry === "." || entry === "..") {
7721                             continue;
7722                         }
7723                         var stat = void 0;
7724                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
7725                             var name = ts.combinePaths(path, entry);
7726                             try {
7727                                 stat = statSync(name);
7728                                 if (!stat) {
7729                                     continue;
7730                                 }
7731                             }
7732                             catch (e) {
7733                                 continue;
7734                             }
7735                         }
7736                         else {
7737                             stat = dirent;
7738                         }
7739                         if (stat.isFile()) {
7740                             files.push(entry);
7741                         }
7742                         else if (stat.isDirectory()) {
7743                             directories.push(entry);
7744                         }
7745                     }
7746                     files.sort();
7747                     directories.sort();
7748                     return { files: files, directories: directories };
7749                 }
7750                 catch (e) {
7751                     return ts.emptyFileSystemEntries;
7752                 }
7753             }
7754             function readDirectory(path, extensions, excludes, includes, depth) {
7755                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
7756             }
7757             function fileSystemEntryExists(path, entryKind) {
7758                 // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
7759                 // the CPU time performance.
7760                 var originalStackTraceLimit = Error.stackTraceLimit;
7761                 Error.stackTraceLimit = 0;
7762                 try {
7763                     var stat = statSync(path);
7764                     if (!stat) {
7765                         return false;
7766                     }
7767                     switch (entryKind) {
7768                         case 0 /* File */: return stat.isFile();
7769                         case 1 /* Directory */: return stat.isDirectory();
7770                         default: return false;
7771                     }
7772                 }
7773                 catch (e) {
7774                     return false;
7775                 }
7776                 finally {
7777                     Error.stackTraceLimit = originalStackTraceLimit;
7778                 }
7779             }
7780             function fileExists(path) {
7781                 return fileSystemEntryExists(path, 0 /* File */);
7782             }
7783             function directoryExists(path) {
7784                 return fileSystemEntryExists(path, 1 /* Directory */);
7785             }
7786             function getDirectories(path) {
7787                 return getAccessibleFileSystemEntries(path).directories.slice();
7788             }
7789             function realpath(path) {
7790                 try {
7791                     return realpathSync(path);
7792                 }
7793                 catch (_a) {
7794                     return path;
7795                 }
7796             }
7797             function getModifiedTime(path) {
7798                 var _a;
7799                 try {
7800                     return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime;
7801                 }
7802                 catch (e) {
7803                     return undefined;
7804                 }
7805             }
7806             function setModifiedTime(path, time) {
7807                 try {
7808                     _fs.utimesSync(path, time, time);
7809                 }
7810                 catch (e) {
7811                     return;
7812                 }
7813             }
7814             function deleteFile(path) {
7815                 try {
7816                     return _fs.unlinkSync(path);
7817                 }
7818                 catch (e) {
7819                     return;
7820                 }
7821             }
7822             function createSHA256Hash(data) {
7823                 var hash = _crypto.createHash("sha256");
7824                 hash.update(data);
7825                 return hash.digest("hex");
7826             }
7827         }
7828         var sys;
7829         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
7830             // process and process.nextTick checks if current environment is node-like
7831             // process.browser check excludes webpack and browserify
7832             sys = getNodeSystem();
7833         }
7834         if (sys) {
7835             // patch writefile to create folder before writing the file
7836             patchWriteFileEnsuringDirectory(sys);
7837         }
7838         return sys;
7839     })();
7840     /*@internal*/
7841     function setSys(s) {
7842         ts.sys = s;
7843     }
7844     ts.setSys = setSys;
7845     if (ts.sys && ts.sys.getEnvironmentVariable) {
7846         setCustomPollingValues(ts.sys);
7847         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
7848             ? 1 /* Normal */
7849             : 0 /* None */);
7850     }
7851     if (ts.sys && ts.sys.debugMode) {
7852         ts.Debug.isDebugging = true;
7853     }
7854 })(ts || (ts = {}));
7855 // <auto-generated />
7856 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
7857 /* @internal */
7858 var ts;
7859 (function (ts) {
7860     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) {
7861         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
7862     }
7863     ts.Diagnostics = {
7864         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
7865         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
7866         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
7867         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."),
7868         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."),
7869         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
7870         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
7871         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."),
7872         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
7873         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."),
7874         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."),
7875         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."),
7876         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."),
7877         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."),
7878         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."),
7879         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."),
7880         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."),
7881         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."),
7882         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."),
7883         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."),
7884         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."),
7885         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
7886         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
7887         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
7888         _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."),
7889         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."),
7890         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."),
7891         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."),
7892         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."),
7893         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."),
7894         _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."),
7895         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
7896         _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."),
7897         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."),
7898         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
7899         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."),
7900         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."),
7901         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."),
7902         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."),
7903         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."),
7904         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
7905         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."),
7906         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."),
7907         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."),
7908         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."),
7909         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."),
7910         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
7911         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."),
7912         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."),
7913         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}>'?"),
7914         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."),
7915         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."),
7916         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."),
7917         _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."),
7918         _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."),
7919         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."),
7920         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
7921         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}'."),
7922         _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."),
7923         _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."),
7924         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."),
7925         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."),
7926         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."),
7927         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
7928         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."),
7929         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."),
7930         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
7931         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
7932         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
7933         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."),
7934         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."),
7935         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."),
7936         for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."),
7937         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."),
7938         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."),
7939         The_left_hand_side_of_a_for_of_statement_may_not_be_async: diag(1106, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106", "The left-hand side of a 'for...of' statement may not be 'async'."),
7940         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
7941         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."),
7942         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
7943         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
7944         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."),
7945         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
7946         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."),
7947         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."),
7948         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."),
7949         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."),
7950         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."),
7951         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
7952         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."),
7953         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
7954         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
7955         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
7956         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
7957         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
7958         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
7959         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
7960         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
7961         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
7962         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
7963         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
7964         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
7965         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
7966         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
7967         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
7968         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
7969         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
7970         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
7971         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
7972         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
7973         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
7974         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."),
7975         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'."),
7976         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."),
7977         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
7978         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."),
7979         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."),
7980         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
7981         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
7982         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."),
7983         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."),
7984         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."),
7985         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."),
7986         A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."),
7987         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."),
7988         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."),
7989         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."),
7990         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."),
7991         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
7992         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
7993         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."),
7994         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
7995         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
7996         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
7997         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
7998         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
7999         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
8000         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
8001         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."),
8002         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."),
8003         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
8004         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
8005         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."),
8006         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."),
8007         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."),
8008         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."),
8009         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."),
8010         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
8011         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
8012         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
8013         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."),
8014         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."),
8015         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."),
8016         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."),
8017         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."),
8018         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
8019         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
8020         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."),
8021         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."),
8022         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'."),
8023         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
8024         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."),
8025         _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."),
8026         Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."),
8027         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."),
8028         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."),
8029         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."),
8030         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."),
8031         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."),
8032         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."),
8033         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'."),
8034         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."),
8035         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."),
8036         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."),
8037         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
8038         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."),
8039         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
8040         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}'."),
8041         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}'."),
8042         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."),
8043         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."),
8044         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."),
8045         An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."),
8046         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."),
8047         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."),
8048         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."),
8049         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."),
8050         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'."),
8051         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'."),
8052         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."),
8053         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."),
8054         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."),
8055         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."),
8056         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."),
8057         _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."),
8058         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."),
8059         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."),
8060         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."),
8061         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."),
8062         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."),
8063         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."),
8064         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'."),
8065         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."),
8066         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."),
8067         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."),
8068         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."),
8069         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."),
8070         A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."),
8071         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"),
8072         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
8073         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."),
8074         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."),
8075         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."),
8076         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."),
8077         A_rest_element_cannot_follow_another_rest_element: diag(1265, ts.DiagnosticCategory.Error, "A_rest_element_cannot_follow_another_rest_element_1265", "A rest element cannot follow another rest element."),
8078         An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."),
8079         Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, ts.DiagnosticCategory.Error, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."),
8080         An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."),
8081         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."),
8082         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."),
8083         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."),
8084         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."),
8085         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."),
8086         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."),
8087         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."),
8088         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."),
8089         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."),
8090         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."),
8091         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."),
8092         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."),
8093         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."),
8094         Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node12_or_nodenext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12', or 'nodenext'."),
8095         Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext'."),
8096         Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."),
8097         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."),
8098         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
8099         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."),
8100         _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}()'?"),
8101         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'."),
8102         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'."),
8103         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'."),
8104         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."),
8105         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."),
8106         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."),
8107         An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337", "An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead."),
8108         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."),
8109         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."),
8110         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}')'?"),
8111         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
8112         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node12_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'."),
8113         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
8114         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."),
8115         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."),
8116         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."),
8117         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
8118         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
8119         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."),
8120         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."),
8121         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."),
8122         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."),
8123         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."),
8124         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."),
8125         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'?"),
8126         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 '}'."),
8127         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."),
8128         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."),
8129         _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'."),
8130         _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'."),
8131         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."),
8132         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
8133         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"),
8134         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
8135         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
8136         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
8137         This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371", "This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'."),
8138         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
8139         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"),
8140         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."),
8141         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
8142         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
8143         Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_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_es2022_esnext_system_o_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher."),
8144         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'."),
8145         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'."),
8146         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;`?"),
8147         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;`?"),
8148         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'."),
8149         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."),
8150         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."),
8151         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."),
8152         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."),
8153         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."),
8154         _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."),
8155         _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."),
8156         An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"),
8157         Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"),
8158         Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"),
8159         Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions: diag(1395, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395", "Imported via {0} from file '{1}' to import 'importHelpers' as specified in compilerOptions"),
8160         Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions: diag(1396, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396", "Imported via {0} from file '{1}' with packageId '{2}' to import 'importHelpers' as specified in compilerOptions"),
8161         Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions: diag(1397, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397", "Imported via {0} from file '{1}' to import 'jsx' and 'jsxs' factory functions"),
8162         Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions: diag(1398, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398", "Imported via {0} from file '{1}' with packageId '{2}' to import 'jsx' and 'jsxs' factory functions"),
8163         File_is_included_via_import_here: diag(1399, ts.DiagnosticCategory.Message, "File_is_included_via_import_here_1399", "File is included via import here."),
8164         Referenced_via_0_from_file_1: diag(1400, ts.DiagnosticCategory.Message, "Referenced_via_0_from_file_1_1400", "Referenced via '{0}' from file '{1}'"),
8165         File_is_included_via_reference_here: diag(1401, ts.DiagnosticCategory.Message, "File_is_included_via_reference_here_1401", "File is included via reference here."),
8166         Type_library_referenced_via_0_from_file_1: diag(1402, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_1402", "Type library referenced via '{0}' from file '{1}'"),
8167         Type_library_referenced_via_0_from_file_1_with_packageId_2: diag(1403, ts.DiagnosticCategory.Message, "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403", "Type library referenced via '{0}' from file '{1}' with packageId '{2}'"),
8168         File_is_included_via_type_library_reference_here: diag(1404, ts.DiagnosticCategory.Message, "File_is_included_via_type_library_reference_here_1404", "File is included via type library reference here."),
8169         Library_referenced_via_0_from_file_1: diag(1405, ts.DiagnosticCategory.Message, "Library_referenced_via_0_from_file_1_1405", "Library referenced via '{0}' from file '{1}'"),
8170         File_is_included_via_library_reference_here: diag(1406, ts.DiagnosticCategory.Message, "File_is_included_via_library_reference_here_1406", "File is included via library reference here."),
8171         Matched_by_include_pattern_0_in_1: diag(1407, ts.DiagnosticCategory.Message, "Matched_by_include_pattern_0_in_1_1407", "Matched by include pattern '{0}' in '{1}'"),
8172         File_is_matched_by_include_pattern_specified_here: diag(1408, ts.DiagnosticCategory.Message, "File_is_matched_by_include_pattern_specified_here_1408", "File is matched by include pattern specified here."),
8173         Part_of_files_list_in_tsconfig_json: diag(1409, ts.DiagnosticCategory.Message, "Part_of_files_list_in_tsconfig_json_1409", "Part of 'files' list in tsconfig.json"),
8174         File_is_matched_by_files_list_specified_here: diag(1410, ts.DiagnosticCategory.Message, "File_is_matched_by_files_list_specified_here_1410", "File is matched by 'files' list specified here."),
8175         Output_from_referenced_project_0_included_because_1_specified: diag(1411, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_1_specified_1411", "Output from referenced project '{0}' included because '{1}' specified"),
8176         Output_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1412, ts.DiagnosticCategory.Message, "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412", "Output from referenced project '{0}' included because '--module' is specified as 'none'"),
8177         File_is_output_from_referenced_project_specified_here: diag(1413, ts.DiagnosticCategory.Message, "File_is_output_from_referenced_project_specified_here_1413", "File is output from referenced project specified here."),
8178         Source_from_referenced_project_0_included_because_1_specified: diag(1414, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_1_specified_1414", "Source from referenced project '{0}' included because '{1}' specified"),
8179         Source_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1415, ts.DiagnosticCategory.Message, "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415", "Source from referenced project '{0}' included because '--module' is specified as 'none'"),
8180         File_is_source_from_referenced_project_specified_here: diag(1416, ts.DiagnosticCategory.Message, "File_is_source_from_referenced_project_specified_here_1416", "File is source from referenced project specified here."),
8181         Entry_point_of_type_library_0_specified_in_compilerOptions: diag(1417, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_1417", "Entry point of type library '{0}' specified in compilerOptions"),
8182         Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1: diag(1418, ts.DiagnosticCategory.Message, "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418", "Entry point of type library '{0}' specified in compilerOptions with packageId '{1}'"),
8183         File_is_entry_point_of_type_library_specified_here: diag(1419, ts.DiagnosticCategory.Message, "File_is_entry_point_of_type_library_specified_here_1419", "File is entry point of type library specified here."),
8184         Entry_point_for_implicit_type_library_0: diag(1420, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_1420", "Entry point for implicit type library '{0}'"),
8185         Entry_point_for_implicit_type_library_0_with_packageId_1: diag(1421, ts.DiagnosticCategory.Message, "Entry_point_for_implicit_type_library_0_with_packageId_1_1421", "Entry point for implicit type library '{0}' with packageId '{1}'"),
8186         Library_0_specified_in_compilerOptions: diag(1422, ts.DiagnosticCategory.Message, "Library_0_specified_in_compilerOptions_1422", "Library '{0}' specified in compilerOptions"),
8187         File_is_library_specified_here: diag(1423, ts.DiagnosticCategory.Message, "File_is_library_specified_here_1423", "File is library specified here."),
8188         Default_library: diag(1424, ts.DiagnosticCategory.Message, "Default_library_1424", "Default library"),
8189         Default_library_for_target_0: diag(1425, ts.DiagnosticCategory.Message, "Default_library_for_target_0_1425", "Default library for target '{0}'"),
8190         File_is_default_library_for_target_specified_here: diag(1426, ts.DiagnosticCategory.Message, "File_is_default_library_for_target_specified_here_1426", "File is default library for target specified here."),
8191         Root_file_specified_for_compilation: diag(1427, ts.DiagnosticCategory.Message, "Root_file_specified_for_compilation_1427", "Root file specified for compilation"),
8192         File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"),
8193         File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"),
8194         The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"),
8195         for_await_loops_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(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops 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."),
8196         Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher."),
8197         Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."),
8198         Unexpected_keyword_or_identifier: diag(1434, ts.DiagnosticCategory.Error, "Unexpected_keyword_or_identifier_1434", "Unexpected keyword or identifier."),
8199         Unknown_keyword_or_identifier_Did_you_mean_0: diag(1435, ts.DiagnosticCategory.Error, "Unknown_keyword_or_identifier_Did_you_mean_0_1435", "Unknown keyword or identifier. Did you mean '{0}'?"),
8200         Decorators_must_precede_the_name_and_all_keywords_of_property_declarations: diag(1436, ts.DiagnosticCategory.Error, "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436", "Decorators must precede the name and all keywords of property declarations."),
8201         Namespace_must_be_given_a_name: diag(1437, ts.DiagnosticCategory.Error, "Namespace_must_be_given_a_name_1437", "Namespace must be given a name."),
8202         Interface_must_be_given_a_name: diag(1438, ts.DiagnosticCategory.Error, "Interface_must_be_given_a_name_1438", "Interface must be given a name."),
8203         Type_alias_must_be_given_a_name: diag(1439, ts.DiagnosticCategory.Error, "Type_alias_must_be_given_a_name_1439", "Type alias must be given a name."),
8204         Variable_declaration_not_allowed_at_this_location: diag(1440, ts.DiagnosticCategory.Error, "Variable_declaration_not_allowed_at_this_location_1440", "Variable declaration not allowed at this location."),
8205         Cannot_start_a_function_call_in_a_type_annotation: diag(1441, ts.DiagnosticCategory.Error, "Cannot_start_a_function_call_in_a_type_annotation_1441", "Cannot start a function call in a type annotation."),
8206         Expected_for_property_initializer: diag(1442, ts.DiagnosticCategory.Error, "Expected_for_property_initializer_1442", "Expected '=' for property initializer."),
8207         Module_declaration_names_may_only_use_or_quoted_strings: diag(1443, ts.DiagnosticCategory.Error, "Module_declaration_names_may_only_use_or_quoted_strings_1443", "Module declaration names may only use ' or \" quoted strings."),
8208         _0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled: diag(1444, ts.DiagnosticCategory.Error, "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444", "'{0}' is a type and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled."),
8209         _0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled: diag(1446, ts.DiagnosticCategory.Error, "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveVa_1446", "'{0}' resolves to a type-only declaration and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled."),
8210         _0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_isolatedModules_is_enabled: diag(1448, ts.DiagnosticCategory.Error, "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_isol_1448", "'{0}' resolves to a type-only declaration and must be re-exported using a type-only re-export when 'isolatedModules' is enabled."),
8211         Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."),
8212         Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"),
8213         Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"),
8214         The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."),
8215         Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."),
8216         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."),
8217         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."),
8218         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),
8219         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),
8220         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),
8221         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),
8222         The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."),
8223         The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."),
8224         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
8225         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."),
8226         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."),
8227         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
8228         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
8229         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}'."),
8230         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
8231         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."),
8232         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."),
8233         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."),
8234         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."),
8235         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."),
8236         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."),
8237         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)."),
8238         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
8239         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."),
8240         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)."),
8241         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
8242         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."),
8243         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}'."),
8244         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}'."),
8245         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}'."),
8246         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
8247         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}'."),
8248         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}'."),
8249         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
8250         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}'."),
8251         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."),
8252         Index_signature_for_type_0_is_missing_in_type_1: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_for_type_0_is_missing_in_type_1_2329", "Index signature for type '{0}' is missing in type '{1}'."),
8253         _0_and_1_index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "_0_and_1_index_signatures_are_incompatible_2330", "'{0}' and '{1}' index signatures are incompatible."),
8254         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."),
8255         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."),
8256         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."),
8257         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."),
8258         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."),
8259         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."),
8260         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."),
8261         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."),
8262         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}'."),
8263         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."),
8264         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}'."),
8265         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}'."),
8266         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}'."),
8267         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}'."),
8268         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."),
8269         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."),
8270         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'?"),
8271         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
8272         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."),
8273         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
8274         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."),
8275         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}'."),
8276         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."),
8277         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."),
8278         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."),
8279         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."),
8280         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."),
8281         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."),
8282         The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360", "The left-hand side of an 'in' expression must be a private identifier or of type 'any', 'string', 'number', or 'symbol'."),
8283         The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."),
8284         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."),
8285         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."),
8286         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."),
8287         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}'."),
8288         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'."),
8289         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."),
8290         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
8291         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."),
8292         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."),
8293         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."),
8294         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
8295         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."),
8296         Duplicate_index_signature_for_type_0: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_index_signature_for_type_0_2374", "Duplicate index signature for type '{0}'."),
8297         Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2375, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."),
8298         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."),
8299         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."),
8300         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."),
8301         Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."),
8302         The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"),
8303         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."),
8304         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."),
8305         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."),
8306         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."),
8307         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
8308         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
8309         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
8310         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
8311         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."),
8312         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
8313         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
8314         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."),
8315         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."),
8316         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."),
8317         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}'."),
8318         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."),
8319         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."),
8320         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."),
8321         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."),
8322         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}'."),
8323         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."),
8324         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'."),
8325         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."),
8326         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}'."),
8327         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
8328         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."),
8329         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'."),
8330         Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target: diag(2412, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target."),
8331         Property_0_of_type_1_is_not_assignable_to_2_index_type_3: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411", "Property '{0}' of type '{1}' is not assignable to '{2}' index type '{3}'."),
8332         _0_index_type_1_is_not_assignable_to_2_index_type_3: diag(2413, ts.DiagnosticCategory.Error, "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413", "'{0}' index type '{1}' is not assignable to '{2}' index type '{3}'."),
8333         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
8334         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}'."),
8335         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}'."),
8336         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}'."),
8337         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}'."),
8338         Types_of_construct_signatures_are_incompatible: diag(2419, ts.DiagnosticCategory.Error, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."),
8339         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
8340         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."),
8341         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."),
8342         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."),
8343         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."),
8344         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
8345         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."),
8346         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
8347         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
8348         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."),
8349         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."),
8350         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."),
8351         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."),
8352         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."),
8353         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."),
8354         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
8355         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."),
8356         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}'."),
8357         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."),
8358         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}'."),
8359         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}'."),
8360         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}'."),
8361         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."),
8362         Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."),
8363         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."),
8364         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."),
8365         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
8366         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
8367         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
8368         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."),
8369         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."),
8370         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
8371         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
8372         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."),
8373         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."),
8374         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}'."),
8375         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."),
8376         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."),
8377         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."),
8378         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'."),
8379         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."),
8380         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."),
8381         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."),
8382         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
8383         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'."),
8384         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."),
8385         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."),
8386         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."),
8387         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."),
8388         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."),
8389         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."),
8390         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'."),
8391         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."),
8392         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}'."),
8393         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."),
8394         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}'."),
8395         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."),
8396         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."),
8397         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."),
8398         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."),
8399         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."),
8400         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."),
8401         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}'."),
8402         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."),
8403         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."),
8404         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."),
8405         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."),
8406         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 *'."),
8407         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."),
8408         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."),
8409         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."),
8410         _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."),
8411         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
8412         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."),
8413         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."),
8414         _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."),
8415         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."),
8416         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."),
8417         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."),
8418         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."),
8419         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."),
8420         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."),
8421         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."),
8422         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}'."),
8423         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."),
8424         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."),
8425         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."),
8426         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."),
8427         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."),
8428         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."),
8429         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."),
8430         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."),
8431         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."),
8432         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."),
8433         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."),
8434         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."),
8435         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."),
8436         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."),
8437         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
8438         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
8439         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
8440         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."),
8441         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."),
8442         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}'."),
8443         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}'."),
8444         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."),
8445         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."),
8446         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."),
8447         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."),
8448         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."),
8449         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."),
8450         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[]'."),
8451         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."),
8452         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."),
8453         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."),
8454         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."),
8455         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}'?"),
8456         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}'?"),
8457         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."),
8458         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
8459         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}."),
8460         A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."),
8461         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}."),
8462         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}'."),
8463         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?"),
8464         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}'?"),
8465         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."),
8466         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."),
8467         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."),
8468         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."),
8469         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."),
8470         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."),
8471         Property_0_may_not_exist_on_type_1_Did_you_mean_2: diag(2568, ts.DiagnosticCategory.Error, "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568", "Property '{0}' may not exist on type '{1}'. Did you mean '{2}'?"),
8472         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."),
8473         Could_not_find_name_0_Did_you_mean_1: diag(2570, ts.DiagnosticCategory.Error, "Could_not_find_name_0_Did_you_mean_1_2570", "Could not find name '{0}'. Did you mean '{1}'?"),
8474         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
8475         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."),
8476         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."),
8477         Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead: diag(2576, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576", "Property '{0}' does not exist on type '{1}'. Did you mean to access the static member '{2}' instead?"),
8478         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
8479         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
8480         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`."),
8481         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`."),
8482         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`."),
8483         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."),
8484         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'."),
8485         _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."),
8486         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."),
8487         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."),
8488         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."),
8489         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."),
8490         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."),
8491         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."),
8492         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."),
8493         _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."),
8494         _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."),
8495         _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."),
8496         _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."),
8497         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."),
8498         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}'."),
8499         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."),
8500         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."),
8501         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."),
8502         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."),
8503         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."),
8504         _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."),
8505         _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."),
8506         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."),
8507         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?"),
8508         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?"),
8509         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}'."),
8510         _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."),
8511         _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."),
8512         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}."),
8513         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}."),
8514         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."),
8515         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."),
8516         Source_provides_no_match_for_required_element_at_position_0_in_target: diag(2623, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_required_element_at_position_0_in_target_2623", "Source provides no match for required element at position {0} in target."),
8517         Source_provides_no_match_for_variadic_element_at_position_0_in_target: diag(2624, ts.DiagnosticCategory.Error, "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624", "Source provides no match for variadic element at position {0} in target."),
8518         Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."),
8519         Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."),
8520         Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."),
8521         Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."),
8522         Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."),
8523         Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."),
8524         Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."),
8525         Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."),
8526         JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"),
8527         _0_index_signatures_are_incompatible: diag(2634, ts.DiagnosticCategory.Error, "_0_index_signatures_are_incompatible_2634", "'{0}' index signatures are incompatible."),
8528         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."),
8529         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."),
8530         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."),
8531         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}'."),
8532         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."),
8533         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}'."),
8534         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."),
8535         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."),
8536         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."),
8537         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}'?"),
8538         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}'?"),
8539         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."),
8540         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."),
8541         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."),
8542         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."),
8543         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."),
8544         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."),
8545         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."),
8546         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."),
8547         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."),
8548         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."),
8549         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."),
8550         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."),
8551         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."),
8552         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."),
8553         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}'."),
8554         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'."),
8555         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."),
8556         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."),
8557         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."),
8558         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}'."),
8559         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."),
8560         _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."),
8561         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."),
8562         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}'."),
8563         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'?"),
8564         _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}'?"),
8565         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."),
8566         _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."),
8567         _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."),
8568         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}'."),
8569         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),
8570         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?"),
8571         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."),
8572         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."),
8573         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}'."),
8574         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."),
8575         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."),
8576         _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."),
8577         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."),
8578         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."),
8579         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."),
8580         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."),
8581         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."),
8582         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."),
8583         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."),
8584         _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."),
8585         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."),
8586         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."),
8587         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}\"]'?"),
8588         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."),
8589         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."),
8590         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."),
8591         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}'."),
8592         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
8593         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."),
8594         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?"),
8595         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'."),
8596         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'."),
8597         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'."),
8598         _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}'?"),
8599         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}."),
8600         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
8601         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}'?"),
8602         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
8603         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."),
8604         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."),
8605         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(...)'."),
8606         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."),
8607         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
8608         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
8609         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}'?"),
8610         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}'."),
8611         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."),
8612         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."),
8613         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}"),
8614         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."),
8615         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}'."),
8616         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."),
8617         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."),
8618         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."),
8619         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."),
8620         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."),
8621         _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}'."),
8622         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."),
8623         _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}'?"),
8624         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
8625         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."),
8626         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
8627         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
8628         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
8629         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."),
8630         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."),
8631         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
8632         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."),
8633         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."),
8634         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."),
8635         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
8636         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."),
8637         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}'."),
8638         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}'."),
8639         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}'."),
8640         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}'."),
8641         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."),
8642         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."),
8643         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
8644         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."),
8645         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
8646         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."),
8647         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
8648         This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"),
8649         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."),
8650         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."),
8651         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."),
8652         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."),
8653         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."),
8654         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."),
8655         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."),
8656         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
8657         _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."),
8658         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."),
8659         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
8660         _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."),
8661         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."),
8662         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."),
8663         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."),
8664         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."),
8665         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."),
8666         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?"),
8667         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."),
8668         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'?"),
8669         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."),
8670         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."),
8671         A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."),
8672         The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."),
8673         Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."),
8674         Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."),
8675         This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."),
8676         Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."),
8677         Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."),
8678         Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."),
8679         Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."),
8680         Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."),
8681         This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."),
8682         A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"),
8683         Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."),
8684         Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."),
8685         Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"),
8686         Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."),
8687         Class_declaration_cannot_implement_overload_list_for_0: diag(2813, ts.DiagnosticCategory.Error, "Class_declaration_cannot_implement_overload_list_for_0_2813", "Class declaration cannot implement overload list for '{0}'."),
8688         Function_with_bodies_can_only_merge_with_classes_that_are_ambient: diag(2814, ts.DiagnosticCategory.Error, "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814", "Function with bodies can only merge with classes that are ambient."),
8689         arguments_cannot_be_referenced_in_property_initializers: diag(2815, ts.DiagnosticCategory.Error, "arguments_cannot_be_referenced_in_property_initializers_2815", "'arguments' cannot be referenced in property initializers."),
8690         Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class: diag(2816, ts.DiagnosticCategory.Error, "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816", "Cannot use 'this' in a static property initializer of a decorated class."),
8691         Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block: diag(2817, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817", "Property '{0}' has no initializer and is not definitely assigned in a class static block."),
8692         Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers: diag(2818, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818", "Duplicate identifier '{0}'. Compiler reserves name '{1}' when emitting 'super' references in static initializers."),
8693         Namespace_name_cannot_be_0: diag(2819, ts.DiagnosticCategory.Error, "Namespace_name_cannot_be_0_2819", "Namespace name cannot be '{0}'."),
8694         Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"),
8695         Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."),
8696         Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."),
8697         Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"),
8698         Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."),
8699         Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"),
8700         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}'."),
8701         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}'."),
8702         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}'."),
8703         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}'."),
8704         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}'."),
8705         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}'."),
8706         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}'."),
8707         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}'."),
8708         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}'."),
8709         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}'."),
8710         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}'."),
8711         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}'."),
8712         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}'."),
8713         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."),
8714         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}'."),
8715         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}'."),
8716         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."),
8717         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}'."),
8718         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}'."),
8719         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."),
8720         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}'."),
8721         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}'."),
8722         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}'."),
8723         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}'."),
8724         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}'."),
8725         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}'."),
8726         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}'."),
8727         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}'."),
8728         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."),
8729         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}'."),
8730         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}'."),
8731         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."),
8732         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}'."),
8733         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}'."),
8734         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}'."),
8735         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}'."),
8736         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}'."),
8737         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}'."),
8738         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}'."),
8739         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}'."),
8740         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."),
8741         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}'."),
8742         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}'."),
8743         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."),
8744         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}'."),
8745         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}'."),
8746         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}'."),
8747         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}'."),
8748         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."),
8749         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}'."),
8750         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}'."),
8751         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."),
8752         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}'."),
8753         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}'."),
8754         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}'."),
8755         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}'."),
8756         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}'."),
8757         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}'."),
8758         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."),
8759         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}'."),
8760         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}'."),
8761         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."),
8762         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}'."),
8763         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}'."),
8764         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}'."),
8765         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}'."),
8766         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."),
8767         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}'."),
8768         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}'."),
8769         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}'."),
8770         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}'."),
8771         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}'."),
8772         Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."),
8773         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."),
8774         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}'."),
8775         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}'."),
8776         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."),
8777         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."),
8778         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}'."),
8779         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}'."),
8780         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."),
8781         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}'."),
8782         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}'."),
8783         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}'."),
8784         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}'."),
8785         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}'."),
8786         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}'."),
8787         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."),
8788         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}'."),
8789         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}'."),
8790         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."),
8791         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."),
8792         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
8793         Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."),
8794         This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."),
8795         This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."),
8796         This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."),
8797         This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."),
8798         This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."),
8799         This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4117, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'. Did you mean '{1}'?"),
8800         The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized: diag(4118, ts.DiagnosticCategory.Error, "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118", "The type of this node cannot be serialized because its property '{0}' cannot be serialized."),
8801         This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4119, ts.DiagnosticCategory.Error, "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119", "This member must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."),
8802         This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4120, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120", "This parameter property must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."),
8803         This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."),
8804         This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."),
8805         This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"),
8806         Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."),
8807         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."),
8808         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."),
8809         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}'."),
8810         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
8811         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}."),
8812         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
8813         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}."),
8814         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}'?"),
8815         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}."),
8816         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."),
8817         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."),
8818         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'."),
8819         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."),
8820         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}'."),
8821         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}'."),
8822         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}'."),
8823         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."),
8824         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."),
8825         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}'."),
8826         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}'."),
8827         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."),
8828         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."),
8829         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."),
8830         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."),
8831         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}'."),
8832         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}'."),
8833         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."),
8834         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."),
8835         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."),
8836         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}'."),
8837         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."),
8838         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'."),
8839         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
8840         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}."),
8841         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."),
8842         _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}'."),
8843         _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."),
8844         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}'?"),
8845         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
8846         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}'?"),
8847         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}."),
8848         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}."),
8849         _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}'."),
8850         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
8851         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."),
8852         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."),
8853         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."),
8854         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."),
8855         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."),
8856         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}'."),
8857         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 './'?"),
8858         Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."),
8859         The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."),
8860         Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."),
8861         Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."),
8862         Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later: diag(5095, ts.DiagnosticCategory.Error, "Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later_5095", "Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later."),
8863         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."),
8864         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."),
8865         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
8866         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."),
8867         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
8868         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
8869         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."),
8870         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."),
8871         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
8872         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
8873         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."),
8874         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
8875         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."),
8876         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
8877         Specify_ECMAScript_target_version: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_6015", "Specify ECMAScript target version."),
8878         Specify_module_code_generation: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_6016", "Specify module code generation."),
8879         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
8880         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
8881         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'."),
8882         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
8883         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
8884         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
8885         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
8886         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
8887         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
8888         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."),
8889         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
8890         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
8891         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
8892         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
8893         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
8894         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
8895         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
8896         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
8897         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
8898         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
8899         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
8900         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}'."),
8901         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}."),
8902         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}'."),
8903         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
8904         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
8905         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."),
8906         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
8907         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}."),
8908         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."),
8909         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."),
8910         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."),
8911         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."),
8912         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)."),
8913         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
8914         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."),
8915         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
8916         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."),
8917         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)."),
8918         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."),
8919         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
8920         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."),
8921         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)."),
8922         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."),
8923         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."),
8924         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."),
8925         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."),
8926         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."),
8927         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."),
8928         Specify_JSX_code_generation: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_6080", "Specify JSX code generation."),
8929         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."),
8930         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}."),
8931         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."),
8932         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"),
8933         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."),
8934         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
8935         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}'."),
8936         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}'."),
8937         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}'. ========"),
8938         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
8939         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}'."),
8940         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
8941         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}'."),
8942         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}'."),
8943         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}'."),
8944         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
8945         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."),
8946         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}'."),
8947         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
8948         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."),
8949         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}'."),
8950         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
8951         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}'."),
8952         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}'."),
8953         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}'."),
8954         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}'."),
8955         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}'."),
8956         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}'."),
8957         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
8958         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
8959         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."),
8960         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
8961         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'?"),
8962         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."),
8963         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}'. ========"),
8964         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}. ========"),
8965         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. ========"),
8966         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
8967         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."),
8968         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. ========"),
8969         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."),
8970         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}'."),
8971         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."),
8972         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}'. ========"),
8973         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. ========"),
8974         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}'."),
8975         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'."),
8976         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."),
8977         _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),
8978         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
8979         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
8980         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."),
8981         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}'."),
8982         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),
8983         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
8984         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}'."),
8985         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."),
8986         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."),
8987         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}'."),
8988         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."),
8989         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'."),
8990         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}'."),
8991         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."),
8992         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
8993         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
8994         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."),
8995         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."),
8996         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')."),
8997         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."),
8998         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."),
8999         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')"),
9000         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."),
9001         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)."),
9002         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."),
9003         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."),
9004         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."),
9005         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
9006         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."),
9007         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
9008         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
9009         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'."),
9010         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."),
9011         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
9012         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"),
9013         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
9014         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'."),
9015         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
9016         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
9017         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
9018         Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."),
9019         Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6184, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."),
9020         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
9021         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."),
9022         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
9023         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."),
9024         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."),
9025         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),
9026         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."),
9027         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."),
9028         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)."),
9029         _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),
9030         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
9031         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
9032         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
9033         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}"),
9034         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
9035         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}"),
9036         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
9037         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
9038         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused."),
9039         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."),
9040         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}'."),
9041         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}'."),
9042         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."),
9043         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."),
9044         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."),
9045         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?"),
9046         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?"),
9047         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."),
9048         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}'."),
9049         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
9050         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
9051         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}'. ========"),
9052         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}. ========"),
9053         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."),
9054         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."),
9055         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."),
9056         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
9057         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
9058         Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_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', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
9059         Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: 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', 'FixedChunkSizePolling'."),
9060         Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: 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', 'FixedChunkSize'."),
9061         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}'."),
9062         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."),
9063         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}."),
9064         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."),
9065         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."),
9066         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 '()'?"),
9067         Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
9068         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."),
9069         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."),
9070         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"),
9071         File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."),
9072         File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."),
9073         Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."),
9074         Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"),
9075         Interpret_optional_property_types_as_written_rather_than_adding_undefined: diag(6243, ts.DiagnosticCategory.Message, "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243", "Interpret optional property types as written, rather than adding 'undefined'."),
9076         Modules: diag(6244, ts.DiagnosticCategory.Message, "Modules_6244", "Modules"),
9077         File_Management: diag(6245, ts.DiagnosticCategory.Message, "File_Management_6245", "File Management"),
9078         Emit: diag(6246, ts.DiagnosticCategory.Message, "Emit_6246", "Emit"),
9079         JavaScript_Support: diag(6247, ts.DiagnosticCategory.Message, "JavaScript_Support_6247", "JavaScript Support"),
9080         Type_Checking: diag(6248, ts.DiagnosticCategory.Message, "Type_Checking_6248", "Type Checking"),
9081         Editor_Support: diag(6249, ts.DiagnosticCategory.Message, "Editor_Support_6249", "Editor Support"),
9082         Watch_and_Build_Modes: diag(6250, ts.DiagnosticCategory.Message, "Watch_and_Build_Modes_6250", "Watch and Build Modes"),
9083         Compiler_Diagnostics: diag(6251, ts.DiagnosticCategory.Message, "Compiler_Diagnostics_6251", "Compiler Diagnostics"),
9084         Interop_Constraints: diag(6252, ts.DiagnosticCategory.Message, "Interop_Constraints_6252", "Interop Constraints"),
9085         Backwards_Compatibility: diag(6253, ts.DiagnosticCategory.Message, "Backwards_Compatibility_6253", "Backwards Compatibility"),
9086         Language_and_Environment: diag(6254, ts.DiagnosticCategory.Message, "Language_and_Environment_6254", "Language and Environment"),
9087         Projects: diag(6255, ts.DiagnosticCategory.Message, "Projects_6255", "Projects"),
9088         Output_Formatting: diag(6256, ts.DiagnosticCategory.Message, "Output_Formatting_6256", "Output Formatting"),
9089         Completeness: diag(6257, ts.DiagnosticCategory.Message, "Completeness_6257", "Completeness"),
9090         _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, ts.DiagnosticCategory.Error, "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"),
9091         Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, ts.DiagnosticCategory.Message, "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."),
9092         Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, ts.DiagnosticCategory.Message, "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."),
9093         Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, ts.DiagnosticCategory.Message, "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."),
9094         package_json_scope_0_has_no_imports_defined: diag(6273, ts.DiagnosticCategory.Message, "package_json_scope_0_has_no_imports_defined_6273", "package.json scope '{0}' has no imports defined."),
9095         package_json_scope_0_explicitly_maps_specifier_1_to_null: diag(6274, ts.DiagnosticCategory.Message, "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274", "package.json scope '{0}' explicitly maps specifier '{1}' to null."),
9096         package_json_scope_0_has_invalid_type_for_target_of_specifier_1: diag(6275, ts.DiagnosticCategory.Message, "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275", "package.json scope '{0}' has invalid type for target of specifier '{1}'"),
9097         Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6276, ts.DiagnosticCategory.Message, "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276", "Export specifier '{0}' does not exist in package.json scope at path '{1}'."),
9098         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
9099         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."),
9100         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}'."),
9101         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."),
9102         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."),
9103         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"),
9104         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"),
9105         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."),
9106         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}'"),
9107         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}'"),
9108         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"),
9109         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"),
9110         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"),
9111         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
9112         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}"),
9113         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}'"),
9114         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
9115         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
9116         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
9117         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"),
9118         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"),
9119         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"),
9120         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
9121         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')"),
9122         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."),
9123         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."),
9124         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}'..."),
9125         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"),
9126         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
9127         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}'"),
9128         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}'"),
9129         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}'"),
9130         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}'"),
9131         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
9132         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."),
9133         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"),
9134         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}'"),
9135         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"),
9136         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"),
9137         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."),
9138         _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
9139         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."),
9140         The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
9141         Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"),
9142         Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved: diag(6389, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389", "Reusing resolution of module '{0}' from '{1}' of old program, it was not resolved."),
9143         Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6390, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."),
9144         Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6391, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."),
9145         Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved: diag(6392, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was not resolved."),
9146         Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6393, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."),
9147         Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6394, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."),
9148         Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6395, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was not resolved."),
9149         Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."),
9150         Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."),
9151         Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."),
9152         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}'"),
9153         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."),
9154         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."),
9155         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."),
9156         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?"),
9157         Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."),
9158         Consider_adding_a_declare_modifier_to_this_class: diag(6506, ts.DiagnosticCategory.Message, "Consider_adding_a_declare_modifier_to_this_class_6506", "Consider adding a 'declare' modifier to this class."),
9159         Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files: diag(6600, ts.DiagnosticCategory.Message, "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600", "Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files."),
9160         Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export: diag(6601, ts.DiagnosticCategory.Message, "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601", "Allow 'import x from y' when a module doesn't have a default export."),
9161         Allow_accessing_UMD_globals_from_modules: diag(6602, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_6602", "Allow accessing UMD globals from modules."),
9162         Disable_error_reporting_for_unreachable_code: diag(6603, ts.DiagnosticCategory.Message, "Disable_error_reporting_for_unreachable_code_6603", "Disable error reporting for unreachable code."),
9163         Disable_error_reporting_for_unused_labels: diag(6604, ts.DiagnosticCategory.Message, "Disable_error_reporting_for_unused_labels_6604", "Disable error reporting for unused labels."),
9164         Ensure_use_strict_is_always_emitted: diag(6605, ts.DiagnosticCategory.Message, "Ensure_use_strict_is_always_emitted_6605", "Ensure 'use strict' is always emitted."),
9165         Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6606, ts.DiagnosticCategory.Message, "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606", "Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it."),
9166         Specify_the_base_directory_to_resolve_non_relative_module_names: diag(6607, ts.DiagnosticCategory.Message, "Specify_the_base_directory_to_resolve_non_relative_module_names_6607", "Specify the base directory to resolve non-relative module names."),
9167         No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files: diag(6608, ts.DiagnosticCategory.Message, "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608", "No longer supported. In early versions, manually set the text encoding for reading files."),
9168         Enable_error_reporting_in_type_checked_JavaScript_files: diag(6609, ts.DiagnosticCategory.Message, "Enable_error_reporting_in_type_checked_JavaScript_files_6609", "Enable error reporting in type-checked JavaScript files."),
9169         Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references: diag(6611, ts.DiagnosticCategory.Message, "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611", "Enable constraints that allow a TypeScript project to be used with project references."),
9170         Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project: diag(6612, ts.DiagnosticCategory.Message, "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612", "Generate .d.ts files from TypeScript and JavaScript files in your project."),
9171         Specify_the_output_directory_for_generated_declaration_files: diag(6613, ts.DiagnosticCategory.Message, "Specify_the_output_directory_for_generated_declaration_files_6613", "Specify the output directory for generated declaration files."),
9172         Create_sourcemaps_for_d_ts_files: diag(6614, ts.DiagnosticCategory.Message, "Create_sourcemaps_for_d_ts_files_6614", "Create sourcemaps for d.ts files."),
9173         Output_compiler_performance_information_after_building: diag(6615, ts.DiagnosticCategory.Message, "Output_compiler_performance_information_after_building_6615", "Output compiler performance information after building."),
9174         Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project: diag(6616, ts.DiagnosticCategory.Message, "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616", "Disables inference for type acquisition by looking at filenames in a project."),
9175         Reduce_the_number_of_projects_loaded_automatically_by_TypeScript: diag(6617, ts.DiagnosticCategory.Message, "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617", "Reduce the number of projects loaded automatically by TypeScript."),
9176         Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server: diag(6618, ts.DiagnosticCategory.Message, "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618", "Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server."),
9177         Opt_a_project_out_of_multi_project_reference_checking_when_editing: diag(6619, ts.DiagnosticCategory.Message, "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619", "Opt a project out of multi-project reference checking when editing."),
9178         Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects: diag(6620, ts.DiagnosticCategory.Message, "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620", "Disable preferring source files instead of declaration files when referencing composite projects"),
9179         Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration: diag(6621, ts.DiagnosticCategory.Message, "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621", "Emit more compliant, but verbose and less performant JavaScript for iteration."),
9180         Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6622, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
9181         Only_output_d_ts_files_and_not_JavaScript_files: diag(6623, ts.DiagnosticCategory.Message, "Only_output_d_ts_files_and_not_JavaScript_files_6623", "Only output d.ts files and not JavaScript files."),
9182         Emit_design_type_metadata_for_decorated_declarations_in_source_files: diag(6624, ts.DiagnosticCategory.Message, "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624", "Emit design-type metadata for decorated declarations in source files."),
9183         Disable_the_type_acquisition_for_JavaScript_projects: diag(6625, ts.DiagnosticCategory.Message, "Disable_the_type_acquisition_for_JavaScript_projects_6625", "Disable the type acquisition for JavaScript projects"),
9184         Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility: diag(6626, ts.DiagnosticCategory.Message, "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626", "Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility."),
9185         Filters_results_from_the_include_option: diag(6627, ts.DiagnosticCategory.Message, "Filters_results_from_the_include_option_6627", "Filters results from the `include` option."),
9186         Remove_a_list_of_directories_from_the_watch_process: diag(6628, ts.DiagnosticCategory.Message, "Remove_a_list_of_directories_from_the_watch_process_6628", "Remove a list of directories from the watch process."),
9187         Remove_a_list_of_files_from_the_watch_mode_s_processing: diag(6629, ts.DiagnosticCategory.Message, "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629", "Remove a list of files from the watch mode's processing."),
9188         Enable_experimental_support_for_TC39_stage_2_draft_decorators: diag(6630, ts.DiagnosticCategory.Message, "Enable_experimental_support_for_TC39_stage_2_draft_decorators_6630", "Enable experimental support for TC39 stage 2 draft decorators."),
9189         Print_files_read_during_the_compilation_including_why_it_was_included: diag(6631, ts.DiagnosticCategory.Message, "Print_files_read_during_the_compilation_including_why_it_was_included_6631", "Print files read during the compilation including why it was included."),
9190         Output_more_detailed_compiler_performance_information_after_building: diag(6632, ts.DiagnosticCategory.Message, "Output_more_detailed_compiler_performance_information_after_building_6632", "Output more detailed compiler performance information after building."),
9191         Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_are_inherited: diag(6633, ts.DiagnosticCategory.Message, "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633", "Specify one or more path or node module references to base configuration files from which settings are inherited."),
9192         Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers: diag(6634, ts.DiagnosticCategory.Message, "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634", "Specify what approach the watcher should use if the system runs out of native file watchers."),
9193         Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include: diag(6635, ts.DiagnosticCategory.Message, "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635", "Include a list of files. This does not support glob patterns, as opposed to `include`."),
9194         Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6636, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636", "Build all projects, including those that appear to be up to date"),
9195         Ensure_that_casing_is_correct_in_imports: diag(6637, ts.DiagnosticCategory.Message, "Ensure_that_casing_is_correct_in_imports_6637", "Ensure that casing is correct in imports."),
9196         Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging: diag(6638, ts.DiagnosticCategory.Message, "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638", "Emit a v8 CPU profile of the compiler run for debugging."),
9197         Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file: diag(6639, ts.DiagnosticCategory.Message, "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639", "Allow importing helper functions from tslib once per project, instead of including them per-file."),
9198         Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation: diag(6641, ts.DiagnosticCategory.Message, "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641", "Specify a list of glob patterns that match files to be included in compilation."),
9199         Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects: diag(6642, ts.DiagnosticCategory.Message, "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642", "Save .tsbuildinfo files to allow for incremental compilation of projects."),
9200         Include_sourcemap_files_inside_the_emitted_JavaScript: diag(6643, ts.DiagnosticCategory.Message, "Include_sourcemap_files_inside_the_emitted_JavaScript_6643", "Include sourcemap files inside the emitted JavaScript."),
9201         Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript: diag(6644, ts.DiagnosticCategory.Message, "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644", "Include source code in the sourcemaps inside the emitted JavaScript."),
9202         Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports: diag(6645, ts.DiagnosticCategory.Message, "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645", "Ensure that each file can be safely transpiled without relying on other imports."),
9203         Specify_what_JSX_code_is_generated: diag(6646, ts.DiagnosticCategory.Message, "Specify_what_JSX_code_is_generated_6646", "Specify what JSX code is generated."),
9204         Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h: diag(6647, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647", "Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'"),
9205         Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment: diag(6648, ts.DiagnosticCategory.Message, "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648", "Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'."),
9206         Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk: diag(6649, ts.DiagnosticCategory.Message, "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649", "Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`"),
9207         Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option: diag(6650, ts.DiagnosticCategory.Message, "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650", "Make keyof only return strings instead of string, numbers or symbols. Legacy option."),
9208         Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment: diag(6651, ts.DiagnosticCategory.Message, "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651", "Specify a set of bundled library declaration files that describe the target runtime environment."),
9209         Print_the_names_of_emitted_files_after_a_compilation: diag(6652, ts.DiagnosticCategory.Message, "Print_the_names_of_emitted_files_after_a_compilation_6652", "Print the names of emitted files after a compilation."),
9210         Print_all_of_the_files_read_during_the_compilation: diag(6653, ts.DiagnosticCategory.Message, "Print_all_of_the_files_read_during_the_compilation_6653", "Print all of the files read during the compilation."),
9211         Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit: diag(6654, ts.DiagnosticCategory.Message, "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654", "Set the language of the messaging from TypeScript. This does not affect emit."),
9212         Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6655, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655", "Specify the location where debugger should locate map files instead of generated locations."),
9213         Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs: diag(6656, ts.DiagnosticCategory.Message, "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656", "Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`."),
9214         Specify_what_module_code_is_generated: diag(6657, ts.DiagnosticCategory.Message, "Specify_what_module_code_is_generated_6657", "Specify what module code is generated."),
9215         Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier: diag(6658, ts.DiagnosticCategory.Message, "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658", "Specify how TypeScript looks up a file from a given module specifier."),
9216         Set_the_newline_character_for_emitting_files: diag(6659, ts.DiagnosticCategory.Message, "Set_the_newline_character_for_emitting_files_6659", "Set the newline character for emitting files."),
9217         Disable_emitting_files_from_a_compilation: diag(6660, ts.DiagnosticCategory.Message, "Disable_emitting_files_from_a_compilation_6660", "Disable emitting files from a compilation."),
9218         Disable_generating_custom_helper_functions_like_extends_in_compiled_output: diag(6661, ts.DiagnosticCategory.Message, "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661", "Disable generating custom helper functions like `__extends` in compiled output."),
9219         Disable_emitting_files_if_any_type_checking_errors_are_reported: diag(6662, ts.DiagnosticCategory.Message, "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662", "Disable emitting files if any type checking errors are reported."),
9220         Disable_truncating_types_in_error_messages: diag(6663, ts.DiagnosticCategory.Message, "Disable_truncating_types_in_error_messages_6663", "Disable truncating types in error messages."),
9221         Enable_error_reporting_for_fallthrough_cases_in_switch_statements: diag(6664, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664", "Enable error reporting for fallthrough cases in switch statements."),
9222         Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type: diag(6665, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665", "Enable error reporting for expressions and declarations with an implied `any` type.."),
9223         Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6666, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666", "Ensure overriding members in derived classes are marked with an override modifier."),
9224         Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function: diag(6667, ts.DiagnosticCategory.Message, "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667", "Enable error reporting for codepaths that do not explicitly return in a function."),
9225         Enable_error_reporting_when_this_is_given_the_type_any: diag(6668, ts.DiagnosticCategory.Message, "Enable_error_reporting_when_this_is_given_the_type_any_6668", "Enable error reporting when `this` is given the type `any`."),
9226         Disable_adding_use_strict_directives_in_emitted_JavaScript_files: diag(6669, ts.DiagnosticCategory.Message, "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669", "Disable adding 'use strict' directives in emitted JavaScript files."),
9227         Disable_including_any_library_files_including_the_default_lib_d_ts: diag(6670, ts.DiagnosticCategory.Message, "Disable_including_any_library_files_including_the_default_lib_d_ts_6670", "Disable including any library files, including the default lib.d.ts."),
9228         Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type: diag(6671, ts.DiagnosticCategory.Message, "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671", "Enforces using indexed accessors for keys declared using an indexed type"),
9229         Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project: diag(6672, ts.DiagnosticCategory.Message, "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672", "Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project."),
9230         Disable_strict_checking_of_generic_signatures_in_function_types: diag(6673, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6673", "Disable strict checking of generic signatures in function types."),
9231         Add_undefined_to_a_type_when_accessed_using_an_index: diag(6674, ts.DiagnosticCategory.Message, "Add_undefined_to_a_type_when_accessed_using_an_index_6674", "Add `undefined` to a type when accessed using an index."),
9232         Enable_error_reporting_when_a_local_variables_aren_t_read: diag(6675, ts.DiagnosticCategory.Message, "Enable_error_reporting_when_a_local_variables_aren_t_read_6675", "Enable error reporting when a local variables aren't read."),
9233         Raise_an_error_when_a_function_parameter_isn_t_read: diag(6676, ts.DiagnosticCategory.Message, "Raise_an_error_when_a_function_parameter_isn_t_read_6676", "Raise an error when a function parameter isn't read"),
9234         Deprecated_setting_Use_outFile_instead: diag(6677, ts.DiagnosticCategory.Message, "Deprecated_setting_Use_outFile_instead_6677", "Deprecated setting. Use `outFile` instead."),
9235         Specify_an_output_folder_for_all_emitted_files: diag(6678, ts.DiagnosticCategory.Message, "Specify_an_output_folder_for_all_emitted_files_6678", "Specify an output folder for all emitted files."),
9236         Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output: diag(6679, ts.DiagnosticCategory.Message, "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679", "Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output."),
9237         Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations: diag(6680, ts.DiagnosticCategory.Message, "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680", "Specify a set of entries that re-map imports to additional lookup locations."),
9238         Specify_a_list_of_language_service_plugins_to_include: diag(6681, ts.DiagnosticCategory.Message, "Specify_a_list_of_language_service_plugins_to_include_6681", "Specify a list of language service plugins to include."),
9239         Disable_erasing_const_enum_declarations_in_generated_code: diag(6682, ts.DiagnosticCategory.Message, "Disable_erasing_const_enum_declarations_in_generated_code_6682", "Disable erasing `const enum` declarations in generated code."),
9240         Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node: diag(6683, ts.DiagnosticCategory.Message, "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683", "Disable resolving symlinks to their realpath. This correlates to the same flag in node."),
9241         Disable_wiping_the_console_in_watch_mode: diag(6684, ts.DiagnosticCategory.Message, "Disable_wiping_the_console_in_watch_mode_6684", "Disable wiping the console in watch mode"),
9242         Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read: diag(6685, ts.DiagnosticCategory.Message, "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685", "Enable color and formatting in TypeScript's output to make compiler errors easier to read"),
9243         Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit: diag(6686, ts.DiagnosticCategory.Message, "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686", "Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit."),
9244         Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references: diag(6687, ts.DiagnosticCategory.Message, "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687", "Specify an array of objects that specify paths for projects. Used in project references."),
9245         Disable_emitting_comments: diag(6688, ts.DiagnosticCategory.Message, "Disable_emitting_comments_6688", "Disable emitting comments."),
9246         Enable_importing_json_files: diag(6689, ts.DiagnosticCategory.Message, "Enable_importing_json_files_6689", "Enable importing .json files"),
9247         Specify_the_root_folder_within_your_source_files: diag(6690, ts.DiagnosticCategory.Message, "Specify_the_root_folder_within_your_source_files_6690", "Specify the root folder within your source files."),
9248         Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules: diag(6691, ts.DiagnosticCategory.Message, "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691", "Allow multiple folders to be treated as one when resolving modules."),
9249         Skip_type_checking_d_ts_files_that_are_included_with_TypeScript: diag(6692, ts.DiagnosticCategory.Message, "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692", "Skip type checking .d.ts files that are included with TypeScript."),
9250         Skip_type_checking_all_d_ts_files: diag(6693, ts.DiagnosticCategory.Message, "Skip_type_checking_all_d_ts_files_6693", "Skip type checking all .d.ts files."),
9251         Create_source_map_files_for_emitted_JavaScript_files: diag(6694, ts.DiagnosticCategory.Message, "Create_source_map_files_for_emitted_JavaScript_files_6694", "Create source map files for emitted JavaScript files."),
9252         Specify_the_root_path_for_debuggers_to_find_the_reference_source_code: diag(6695, ts.DiagnosticCategory.Message, "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695", "Specify the root path for debuggers to find the reference source code."),
9253         Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function: diag(6697, ts.DiagnosticCategory.Message, "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697", "Check that the arguments for `bind`, `call`, and `apply` methods match the original function."),
9254         When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible: diag(6698, ts.DiagnosticCategory.Message, "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698", "When assigning functions, check to ensure parameters and the return values are subtype-compatible."),
9255         When_type_checking_take_into_account_null_and_undefined: diag(6699, ts.DiagnosticCategory.Message, "When_type_checking_take_into_account_null_and_undefined_6699", "When type checking, take into account `null` and `undefined`."),
9256         Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor: diag(6700, ts.DiagnosticCategory.Message, "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700", "Check for class properties that are declared but not set in the constructor."),
9257         Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments: diag(6701, ts.DiagnosticCategory.Message, "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701", "Disable emitting declarations that have `@internal` in their JSDoc comments."),
9258         Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals: diag(6702, ts.DiagnosticCategory.Message, "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702", "Disable reporting of excess property errors during the creation of object literals."),
9259         Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures: diag(6703, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703", "Suppress `noImplicitAny` errors when indexing objects that lack index signatures."),
9260         Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6704, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704", "Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively."),
9261         Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations: diag(6705, ts.DiagnosticCategory.Message, "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705", "Set the JavaScript language version for emitted JavaScript and include compatible library declarations."),
9262         Log_paths_used_during_the_moduleResolution_process: diag(6706, ts.DiagnosticCategory.Message, "Log_paths_used_during_the_moduleResolution_process_6706", "Log paths used during the `moduleResolution` process."),
9263         Specify_the_folder_for_tsbuildinfo_incremental_compilation_files: diag(6707, ts.DiagnosticCategory.Message, "Specify_the_folder_for_tsbuildinfo_incremental_compilation_files_6707", "Specify the folder for .tsbuildinfo incremental compilation files."),
9264         Specify_options_for_automatic_acquisition_of_declaration_files: diag(6709, ts.DiagnosticCategory.Message, "Specify_options_for_automatic_acquisition_of_declaration_files_6709", "Specify options for automatic acquisition of declaration files."),
9265         Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types: diag(6710, ts.DiagnosticCategory.Message, "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710", "Specify multiple folders that act like `./node_modules/@types`."),
9266         Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file: diag(6711, ts.DiagnosticCategory.Message, "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711", "Specify type package names to be included without being referenced in a source file."),
9267         Emit_ECMAScript_standard_compliant_class_fields: diag(6712, ts.DiagnosticCategory.Message, "Emit_ECMAScript_standard_compliant_class_fields_6712", "Emit ECMAScript-standard-compliant class fields."),
9268         Enable_verbose_logging: diag(6713, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6713", "Enable verbose logging"),
9269         Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality: diag(6714, ts.DiagnosticCategory.Message, "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714", "Specify how directories are watched on systems that lack recursive file-watching functionality."),
9270         Specify_how_the_TypeScript_watch_mode_works: diag(6715, ts.DiagnosticCategory.Message, "Specify_how_the_TypeScript_watch_mode_works_6715", "Specify how the TypeScript watch mode works."),
9271         Include_undefined_in_index_signature_results: diag(6716, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6716", "Include 'undefined' in index signature results"),
9272         Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6717, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717", "Require undeclared properties from index signatures to use element accesses."),
9273         Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(6718, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718", "Specify emit/checking behavior for imports that are only used for types"),
9274         Type_catch_clause_variables_as_unknown_instead_of_any: diag(6803, ts.DiagnosticCategory.Message, "Type_catch_clause_variables_as_unknown_instead_of_any_6803", "Type catch clause variables as 'unknown' instead of 'any'."),
9275         one_of_Colon: diag(6900, ts.DiagnosticCategory.Message, "one_of_Colon_6900", "one of:"),
9276         one_or_more_Colon: diag(6901, ts.DiagnosticCategory.Message, "one_or_more_Colon_6901", "one or more:"),
9277         type_Colon: diag(6902, ts.DiagnosticCategory.Message, "type_Colon_6902", "type:"),
9278         default_Colon: diag(6903, ts.DiagnosticCategory.Message, "default_Colon_6903", "default:"),
9279         module_system_or_esModuleInterop: diag(6904, ts.DiagnosticCategory.Message, "module_system_or_esModuleInterop_6904", "module === \"system\" or esModuleInterop"),
9280         false_unless_strict_is_set: diag(6905, ts.DiagnosticCategory.Message, "false_unless_strict_is_set_6905", "`false`, unless `strict` is set"),
9281         false_unless_composite_is_set: diag(6906, ts.DiagnosticCategory.Message, "false_unless_composite_is_set_6906", "`false`, unless `composite` is set"),
9282         node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified: diag(6907, ts.DiagnosticCategory.Message, "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907", "`[\"node_modules\", \"bower_components\", \"jspm_packages\"]`, plus the value of `outDir` if one is specified."),
9283         if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk: diag(6908, ts.DiagnosticCategory.Message, "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908", "`[]` if `files` is specified, otherwise `[\"**/*\"]`"),
9284         true_if_composite_false_otherwise: diag(6909, ts.DiagnosticCategory.Message, "true_if_composite_false_otherwise_6909", "`true` if `composite`, `false` otherwise"),
9285         module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node: diag(69010, ts.DiagnosticCategory.Message, "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010", "module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Otherwise `Node`"),
9286         Computed_from_the_list_of_input_files: diag(6911, ts.DiagnosticCategory.Message, "Computed_from_the_list_of_input_files_6911", "Computed from the list of input files"),
9287         Platform_specific: diag(6912, ts.DiagnosticCategory.Message, "Platform_specific_6912", "Platform specific"),
9288         You_can_learn_about_all_of_the_compiler_options_at_0: diag(6913, ts.DiagnosticCategory.Message, "You_can_learn_about_all_of_the_compiler_options_at_0_6913", "You can learn about all of the compiler options at {0}"),
9289         Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon: diag(6914, ts.DiagnosticCategory.Message, "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914", "Including --watch, -w will start watching the current project for the file changes. Once set, you can config watch mode with:"),
9290         Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0: diag(6915, ts.DiagnosticCategory.Message, "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915", "Using --build, -b will make tsc behave more like a build orchestrator than a compiler. This is used to trigger building composite projects which you can learn more about at {0}"),
9291         COMMON_COMMANDS: diag(6916, ts.DiagnosticCategory.Message, "COMMON_COMMANDS_6916", "COMMON COMMANDS"),
9292         ALL_COMPILER_OPTIONS: diag(6917, ts.DiagnosticCategory.Message, "ALL_COMPILER_OPTIONS_6917", "ALL COMPILER OPTIONS"),
9293         WATCH_OPTIONS: diag(6918, ts.DiagnosticCategory.Message, "WATCH_OPTIONS_6918", "WATCH OPTIONS"),
9294         BUILD_OPTIONS: diag(6919, ts.DiagnosticCategory.Message, "BUILD_OPTIONS_6919", "BUILD OPTIONS"),
9295         COMMON_COMPILER_OPTIONS: diag(6920, ts.DiagnosticCategory.Message, "COMMON_COMPILER_OPTIONS_6920", "COMMON COMPILER OPTIONS"),
9296         COMMAND_LINE_FLAGS: diag(6921, ts.DiagnosticCategory.Message, "COMMAND_LINE_FLAGS_6921", "COMMAND LINE FLAGS"),
9297         tsc_Colon_The_TypeScript_Compiler: diag(6922, ts.DiagnosticCategory.Message, "tsc_Colon_The_TypeScript_Compiler_6922", "tsc: The TypeScript Compiler"),
9298         Compiles_the_current_project_tsconfig_json_in_the_working_directory: diag(6923, ts.DiagnosticCategory.Message, "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923", "Compiles the current project (tsconfig.json in the working directory.)"),
9299         Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options: diag(6924, ts.DiagnosticCategory.Message, "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924", "Ignoring tsconfig.json, compiles the specified files with default compiler options."),
9300         Build_a_composite_project_in_the_working_directory: diag(6925, ts.DiagnosticCategory.Message, "Build_a_composite_project_in_the_working_directory_6925", "Build a composite project in the working directory."),
9301         Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory: diag(6926, ts.DiagnosticCategory.Message, "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926", "Creates a tsconfig.json with the recommended settings in the working directory."),
9302         Compiles_the_TypeScript_project_located_at_the_specified_path: diag(6927, ts.DiagnosticCategory.Message, "Compiles_the_TypeScript_project_located_at_the_specified_path_6927", "Compiles the TypeScript project located at the specified path."),
9303         An_expanded_version_of_this_information_showing_all_possible_compiler_options: diag(6928, ts.DiagnosticCategory.Message, "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928", "An expanded version of this information, showing all possible compiler options"),
9304         Compiles_the_current_project_with_additional_settings: diag(6929, ts.DiagnosticCategory.Message, "Compiles_the_current_project_with_additional_settings_6929", "Compiles the current project, with additional settings."),
9305         true_for_ES2022_and_above_including_ESNext: diag(6930, ts.DiagnosticCategory.Message, "true_for_ES2022_and_above_including_ESNext_6930", "`true` for ES2022 and above, including ESNext."),
9306         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."),
9307         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."),
9308         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."),
9309         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."),
9310         _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."),
9311         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."),
9312         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."),
9313         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."),
9314         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'."),
9315         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."),
9316         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."),
9317         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."),
9318         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."),
9319         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."),
9320         _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."),
9321         _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."),
9322         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."),
9323         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."),
9324         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."),
9325         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
9326         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
9327         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
9328         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."),
9329         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."),
9330         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."),
9331         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."),
9332         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."),
9333         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}';`"),
9334         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}'."),
9335         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'."),
9336         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."),
9337         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."),
9338         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}'"),
9339         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'."),
9340         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."),
9341         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."),
9342         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."),
9343         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."),
9344         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."),
9345         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."),
9346         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."),
9347         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."),
9348         _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."),
9349         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}'?"),
9350         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}'?"),
9351         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}'."),
9352         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}'."),
9353         _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."),
9354         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."),
9355         yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation: diag(7057, ts.DiagnosticCategory.Error, "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057", "'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation."),
9356         If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"),
9357         This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."),
9358         This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."),
9359         A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."),
9360         JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."),
9361         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
9362         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."),
9363         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."),
9364         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."),
9365         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."),
9366         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."),
9367         _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."),
9368         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."),
9369         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."),
9370         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."),
9371         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."),
9372         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."),
9373         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."),
9374         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."),
9375         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}'."),
9376         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}'."),
9377         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
9378         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."),
9379         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."),
9380         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."),
9381         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."),
9382         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."),
9383         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."),
9384         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."),
9385         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."),
9386         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."),
9387         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."),
9388         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."),
9389         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."),
9390         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}'."),
9391         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."),
9392         The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
9393         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."),
9394         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."),
9395         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'."),
9396         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."),
9397         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}'."),
9398         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."),
9399         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'."),
9400         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."),
9401         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."),
9402         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."),
9403         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."),
9404         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
9405         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."),
9406         _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}'?"),
9407         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."),
9408         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."),
9409         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."),
9410         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."),
9411         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."),
9412         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}'?"),
9413         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}"),
9414         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."),
9415         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}'."),
9416         File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."),
9417         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."),
9418         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."),
9419         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."),
9420         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."),
9421         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."),
9422         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."),
9423         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."),
9424         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
9425         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"),
9426         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
9427         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
9428         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
9429         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
9430         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
9431         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
9432         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
9433         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
9434         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
9435         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
9436         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
9437         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}\""),
9438         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
9439         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
9440         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
9441         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
9442         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
9443         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
9444         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
9445         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
9446         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
9447         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
9448         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}'"),
9449         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
9450         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
9451         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
9452         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
9453         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
9454         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
9455         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}\""),
9456         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
9457         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
9458         Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
9459         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"),
9460         Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
9461         Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
9462         Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
9463         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
9464         Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"),
9465         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
9466         Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"),
9467         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
9468         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
9469         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
9470         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
9471         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
9472         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
9473         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
9474         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
9475         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
9476         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
9477         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
9478         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
9479         Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"),
9480         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
9481         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
9482         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}'"),
9483         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"),
9484         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
9485         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
9486         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
9487         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"),
9488         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
9489         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
9490         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"),
9491         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"),
9492         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"),
9493         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)"),
9494         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
9495         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
9496         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
9497         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
9498         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"),
9499         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"),
9500         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
9501         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
9502         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
9503         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
9504         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"),
9505         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
9506         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
9507         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
9508         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
9509         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
9510         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
9511         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
9512         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
9513         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
9514         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
9515         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
9516         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
9517         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
9518         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
9519         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
9520         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"),
9521         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
9522         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
9523         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
9524         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
9525         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
9526         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
9527         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
9528         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
9529         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
9530         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
9531         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"),
9532         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"),
9533         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
9534         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"),
9535         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"),
9536         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"),
9537         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
9538         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
9539         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
9540         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
9541         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"),
9542         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
9543         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
9544         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
9545         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
9546         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
9547         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
9548         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
9549         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"),
9550         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
9551         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
9552         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
9553         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
9554         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
9555         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
9556         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'"),
9557         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
9558         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"),
9559         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}'"),
9560         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}'"),
9561         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"),
9562         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"),
9563         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"),
9564         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"),
9565         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
9566         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"),
9567         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"),
9568         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"),
9569         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
9570         Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
9571         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"),
9572         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
9573         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"),
9574         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
9575         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"),
9576         Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
9577         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"),
9578         Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
9579         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"),
9580         Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
9581         Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
9582         Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
9583         Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
9584         Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
9585         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"),
9586         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"),
9587         Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
9588         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"),
9589         Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
9590         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"),
9591         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"),
9592         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"),
9593         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"),
9594         Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
9595         Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
9596         Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
9597         Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
9598         Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
9599         Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
9600         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"),
9601         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"),
9602         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"),
9603         Use_element_access_for_0: diag(95145, ts.DiagnosticCategory.Message, "Use_element_access_for_0_95145", "Use element access for '{0}'"),
9604         Use_element_access_for_all_undeclared_properties: diag(95146, ts.DiagnosticCategory.Message, "Use_element_access_for_all_undeclared_properties_95146", "Use element access for all undeclared properties."),
9605         Delete_all_unused_imports: diag(95147, ts.DiagnosticCategory.Message, "Delete_all_unused_imports_95147", "Delete all unused imports"),
9606         Infer_function_return_type: diag(95148, ts.DiagnosticCategory.Message, "Infer_function_return_type_95148", "Infer function return type"),
9607         Return_type_must_be_inferred_from_a_function: diag(95149, ts.DiagnosticCategory.Message, "Return_type_must_be_inferred_from_a_function_95149", "Return type must be inferred from a function"),
9608         Could_not_determine_function_return_type: diag(95150, ts.DiagnosticCategory.Message, "Could_not_determine_function_return_type_95150", "Could not determine function return type"),
9609         Could_not_convert_to_arrow_function: diag(95151, ts.DiagnosticCategory.Message, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"),
9610         Could_not_convert_to_named_function: diag(95152, ts.DiagnosticCategory.Message, "Could_not_convert_to_named_function_95152", "Could not convert to named function"),
9611         Could_not_convert_to_anonymous_function: diag(95153, ts.DiagnosticCategory.Message, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"),
9612         Can_only_convert_string_concatenation: diag(95154, ts.DiagnosticCategory.Message, "Can_only_convert_string_concatenation_95154", "Can only convert string concatenation"),
9613         Selection_is_not_a_valid_statement_or_statements: diag(95155, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_statement_or_statements_95155", "Selection is not a valid statement or statements"),
9614         Add_missing_function_declaration_0: diag(95156, ts.DiagnosticCategory.Message, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"),
9615         Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"),
9616         Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."),
9617         Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."),
9618         Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"),
9619         Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"),
9620         Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"),
9621         Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"),
9622         Can_only_convert_named_export: diag(95164, ts.DiagnosticCategory.Message, "Can_only_convert_named_export_95164", "Can only convert named export"),
9623         Add_missing_properties: diag(95165, ts.DiagnosticCategory.Message, "Add_missing_properties_95165", "Add missing properties"),
9624         Add_all_missing_properties: diag(95166, ts.DiagnosticCategory.Message, "Add_all_missing_properties_95166", "Add all missing properties"),
9625         Add_missing_attributes: diag(95167, ts.DiagnosticCategory.Message, "Add_missing_attributes_95167", "Add missing attributes"),
9626         Add_all_missing_attributes: diag(95168, ts.DiagnosticCategory.Message, "Add_all_missing_attributes_95168", "Add all missing attributes"),
9627         Add_undefined_to_optional_property_type: diag(95169, ts.DiagnosticCategory.Message, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"),
9628         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."),
9629         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'."),
9630         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?"),
9631         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."),
9632         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."),
9633         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."),
9634         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
9635         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."),
9636         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."),
9637         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}'."),
9638         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."),
9639         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"),
9640         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"),
9641         _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."),
9642         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."),
9643         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."),
9644         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."),
9645         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."),
9646         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."),
9647         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."),
9648         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."),
9649         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."),
9650         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."),
9651         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'."),
9652         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."),
9653         Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."),
9654         Await_expression_cannot_be_used_inside_a_class_static_block: diag(18037, ts.DiagnosticCategory.Error, "Await_expression_cannot_be_used_inside_a_class_static_block_18037", "Await expression cannot be used inside a class static block."),
9655         For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."),
9656         Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."),
9657         A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."),
9658     };
9659 })(ts || (ts = {}));
9660 var ts;
9661 (function (ts) {
9662     var _a;
9663     /* @internal */
9664     function tokenIsIdentifierOrKeyword(token) {
9665         return token >= 79 /* Identifier */;
9666     }
9667     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
9668     /* @internal */
9669     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
9670         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
9671     }
9672     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
9673     /** @internal */
9674     ts.textToKeywordObj = (_a = {
9675             abstract: 126 /* AbstractKeyword */,
9676             any: 130 /* AnyKeyword */,
9677             as: 127 /* AsKeyword */,
9678             asserts: 128 /* AssertsKeyword */,
9679             assert: 129 /* AssertKeyword */,
9680             bigint: 157 /* BigIntKeyword */,
9681             boolean: 133 /* BooleanKeyword */,
9682             break: 81 /* BreakKeyword */,
9683             case: 82 /* CaseKeyword */,
9684             catch: 83 /* CatchKeyword */,
9685             class: 84 /* ClassKeyword */,
9686             continue: 86 /* ContinueKeyword */,
9687             const: 85 /* ConstKeyword */
9688         },
9689         _a["" + "constructor"] = 134 /* ConstructorKeyword */,
9690         _a.debugger = 87 /* DebuggerKeyword */,
9691         _a.declare = 135 /* DeclareKeyword */,
9692         _a.default = 88 /* DefaultKeyword */,
9693         _a.delete = 89 /* DeleteKeyword */,
9694         _a.do = 90 /* DoKeyword */,
9695         _a.else = 91 /* ElseKeyword */,
9696         _a.enum = 92 /* EnumKeyword */,
9697         _a.export = 93 /* ExportKeyword */,
9698         _a.extends = 94 /* ExtendsKeyword */,
9699         _a.false = 95 /* FalseKeyword */,
9700         _a.finally = 96 /* FinallyKeyword */,
9701         _a.for = 97 /* ForKeyword */,
9702         _a.from = 155 /* FromKeyword */,
9703         _a.function = 98 /* FunctionKeyword */,
9704         _a.get = 136 /* GetKeyword */,
9705         _a.if = 99 /* IfKeyword */,
9706         _a.implements = 117 /* ImplementsKeyword */,
9707         _a.import = 100 /* ImportKeyword */,
9708         _a.in = 101 /* InKeyword */,
9709         _a.infer = 137 /* InferKeyword */,
9710         _a.instanceof = 102 /* InstanceOfKeyword */,
9711         _a.interface = 118 /* InterfaceKeyword */,
9712         _a.intrinsic = 138 /* IntrinsicKeyword */,
9713         _a.is = 139 /* IsKeyword */,
9714         _a.keyof = 140 /* KeyOfKeyword */,
9715         _a.let = 119 /* LetKeyword */,
9716         _a.module = 141 /* ModuleKeyword */,
9717         _a.namespace = 142 /* NamespaceKeyword */,
9718         _a.never = 143 /* NeverKeyword */,
9719         _a.new = 103 /* NewKeyword */,
9720         _a.null = 104 /* NullKeyword */,
9721         _a.number = 146 /* NumberKeyword */,
9722         _a.object = 147 /* ObjectKeyword */,
9723         _a.package = 120 /* PackageKeyword */,
9724         _a.private = 121 /* PrivateKeyword */,
9725         _a.protected = 122 /* ProtectedKeyword */,
9726         _a.public = 123 /* PublicKeyword */,
9727         _a.override = 158 /* OverrideKeyword */,
9728         _a.readonly = 144 /* ReadonlyKeyword */,
9729         _a.require = 145 /* RequireKeyword */,
9730         _a.global = 156 /* GlobalKeyword */,
9731         _a.return = 105 /* ReturnKeyword */,
9732         _a.set = 148 /* SetKeyword */,
9733         _a.static = 124 /* StaticKeyword */,
9734         _a.string = 149 /* StringKeyword */,
9735         _a.super = 106 /* SuperKeyword */,
9736         _a.switch = 107 /* SwitchKeyword */,
9737         _a.symbol = 150 /* SymbolKeyword */,
9738         _a.this = 108 /* ThisKeyword */,
9739         _a.throw = 109 /* ThrowKeyword */,
9740         _a.true = 110 /* TrueKeyword */,
9741         _a.try = 111 /* TryKeyword */,
9742         _a.type = 151 /* TypeKeyword */,
9743         _a.typeof = 112 /* TypeOfKeyword */,
9744         _a.undefined = 152 /* UndefinedKeyword */,
9745         _a.unique = 153 /* UniqueKeyword */,
9746         _a.unknown = 154 /* UnknownKeyword */,
9747         _a.var = 113 /* VarKeyword */,
9748         _a.void = 114 /* VoidKeyword */,
9749         _a.while = 115 /* WhileKeyword */,
9750         _a.with = 116 /* WithKeyword */,
9751         _a.yield = 125 /* YieldKeyword */,
9752         _a.async = 131 /* AsyncKeyword */,
9753         _a.await = 132 /* AwaitKeyword */,
9754         _a.of = 159 /* OfKeyword */,
9755         _a);
9756     var textToKeyword = new ts.Map(ts.getEntries(ts.textToKeywordObj));
9757     var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, ts.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 */, "=": 63 /* EqualsToken */, "+=": 64 /* PlusEqualsToken */, "-=": 65 /* MinusEqualsToken */, "*=": 66 /* AsteriskEqualsToken */, "**=": 67 /* AsteriskAsteriskEqualsToken */, "/=": 68 /* SlashEqualsToken */, "%=": 69 /* PercentEqualsToken */, "<<=": 70 /* LessThanLessThanEqualsToken */, ">>=": 71 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 73 /* AmpersandEqualsToken */, "|=": 74 /* BarEqualsToken */, "^=": 78 /* CaretEqualsToken */, "||=": 75 /* BarBarEqualsToken */, "&&=": 76 /* AmpersandAmpersandEqualsToken */, "??=": 77 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "#": 62 /* HashToken */, "`": 61 /* BacktickToken */ })));
9758     /*
9759         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
9760         IdentifierStart ::
9761             Can contain Unicode 3.0.0 categories:
9762             Uppercase letter (Lu),
9763             Lowercase letter (Ll),
9764             Titlecase letter (Lt),
9765             Modifier letter (Lm),
9766             Other letter (Lo), or
9767             Letter number (Nl).
9768         IdentifierPart :: =
9769             Can contain IdentifierStart + Unicode 3.0.0 categories:
9770             Non-spacing mark (Mn),
9771             Combining spacing mark (Mc),
9772             Decimal number (Nd), or
9773             Connector punctuation (Pc).
9774
9775         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
9776         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
9777     */
9778     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,];
9779     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,];
9780     /*
9781         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
9782         IdentifierStart ::
9783             Can contain Unicode 6.2 categories:
9784             Uppercase letter (Lu),
9785             Lowercase letter (Ll),
9786             Titlecase letter (Lt),
9787             Modifier letter (Lm),
9788             Other letter (Lo), or
9789             Letter number (Nl).
9790         IdentifierPart ::
9791             Can contain IdentifierStart + Unicode 6.2 categories:
9792             Non-spacing mark (Mn),
9793             Combining spacing mark (Mc),
9794             Decimal number (Nd),
9795             Connector punctuation (Pc),
9796             <ZWNJ>, or
9797             <ZWJ>.
9798
9799         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
9800         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
9801     */
9802     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,];
9803     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,];
9804     /**
9805      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
9806      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
9807      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
9808      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
9809      */
9810     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];
9811     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];
9812     /**
9813      * Test for whether a single line comment with leading whitespace trimmed's text contains a directive.
9814      */
9815     var commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
9816     /**
9817      * Test for whether a multi-line comment with leading whitespace trimmed's last line contains a directive.
9818      */
9819     var commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
9820     function lookupInUnicodeMap(code, map) {
9821         // Bail out quickly if it couldn't possibly be in the map.
9822         if (code < map[0]) {
9823             return false;
9824         }
9825         // Perform binary search in one of the Unicode range maps
9826         var lo = 0;
9827         var hi = map.length;
9828         var mid;
9829         while (lo + 1 < hi) {
9830             mid = lo + (hi - lo) / 2;
9831             // mid has to be even to catch a range's beginning
9832             mid -= mid % 2;
9833             if (map[mid] <= code && code <= map[mid + 1]) {
9834                 return true;
9835             }
9836             if (code < map[mid]) {
9837                 hi = mid;
9838             }
9839             else {
9840                 lo = mid + 2;
9841             }
9842         }
9843         return false;
9844     }
9845     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
9846         return languageVersion >= 2 /* ES2015 */ ?
9847             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
9848             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
9849                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
9850     }
9851     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
9852     function isUnicodeIdentifierPart(code, languageVersion) {
9853         return languageVersion >= 2 /* ES2015 */ ?
9854             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
9855             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
9856                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
9857     }
9858     function makeReverseMap(source) {
9859         var result = [];
9860         source.forEach(function (value, name) {
9861             result[value] = name;
9862         });
9863         return result;
9864     }
9865     var tokenStrings = makeReverseMap(textToToken);
9866     function tokenToString(t) {
9867         return tokenStrings[t];
9868     }
9869     ts.tokenToString = tokenToString;
9870     /* @internal */
9871     function stringToToken(s) {
9872         return textToToken.get(s);
9873     }
9874     ts.stringToToken = stringToToken;
9875     /* @internal */
9876     function computeLineStarts(text) {
9877         var result = new Array();
9878         var pos = 0;
9879         var lineStart = 0;
9880         while (pos < text.length) {
9881             var ch = text.charCodeAt(pos);
9882             pos++;
9883             switch (ch) {
9884                 case 13 /* carriageReturn */:
9885                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
9886                         pos++;
9887                     }
9888                 // falls through
9889                 case 10 /* lineFeed */:
9890                     result.push(lineStart);
9891                     lineStart = pos;
9892                     break;
9893                 default:
9894                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
9895                         result.push(lineStart);
9896                         lineStart = pos;
9897                     }
9898                     break;
9899             }
9900         }
9901         result.push(lineStart);
9902         return result;
9903     }
9904     ts.computeLineStarts = computeLineStarts;
9905     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
9906         return sourceFile.getPositionOfLineAndCharacter ?
9907             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
9908             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
9909     }
9910     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
9911     /* @internal */
9912     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
9913         if (line < 0 || line >= lineStarts.length) {
9914             if (allowEdits) {
9915                 // Clamp line to nearest allowable value
9916                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
9917             }
9918             else {
9919                 ts.Debug.fail("Bad line number. Line: ".concat(line, ", lineStarts.length: ").concat(lineStarts.length, " , line map is correct? ").concat(debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
9920             }
9921         }
9922         var res = lineStarts[line] + character;
9923         if (allowEdits) {
9924             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
9925             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
9926             // apply them to the computed position to improve accuracy
9927             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
9928         }
9929         if (line < lineStarts.length - 1) {
9930             ts.Debug.assert(res < lineStarts[line + 1]);
9931         }
9932         else if (debugText !== undefined) {
9933             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
9934         }
9935         return res;
9936     }
9937     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
9938     /* @internal */
9939     function getLineStarts(sourceFile) {
9940         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
9941     }
9942     ts.getLineStarts = getLineStarts;
9943     /* @internal */
9944     function computeLineAndCharacterOfPosition(lineStarts, position) {
9945         var lineNumber = computeLineOfPosition(lineStarts, position);
9946         return {
9947             line: lineNumber,
9948             character: position - lineStarts[lineNumber]
9949         };
9950     }
9951     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
9952     /**
9953      * @internal
9954      * We assume the first line starts at position 0 and 'position' is non-negative.
9955      */
9956     function computeLineOfPosition(lineStarts, position, lowerBound) {
9957         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
9958         if (lineNumber < 0) {
9959             // If the actual position was not found,
9960             // the binary search returns the 2's-complement of the next line start
9961             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
9962             // then the search will return -2.
9963             //
9964             // We want the index of the previous line start, so we subtract 1.
9965             // Review 2's-complement if this is confusing.
9966             lineNumber = ~lineNumber - 1;
9967             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
9968         }
9969         return lineNumber;
9970     }
9971     ts.computeLineOfPosition = computeLineOfPosition;
9972     /** @internal */
9973     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
9974         if (pos1 === pos2)
9975             return 0;
9976         var lineStarts = getLineStarts(sourceFile);
9977         var lower = Math.min(pos1, pos2);
9978         var isNegative = lower === pos2;
9979         var upper = isNegative ? pos1 : pos2;
9980         var lowerLine = computeLineOfPosition(lineStarts, lower);
9981         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
9982         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
9983     }
9984     ts.getLinesBetweenPositions = getLinesBetweenPositions;
9985     function getLineAndCharacterOfPosition(sourceFile, position) {
9986         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
9987     }
9988     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
9989     function isWhiteSpaceLike(ch) {
9990         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
9991     }
9992     ts.isWhiteSpaceLike = isWhiteSpaceLike;
9993     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
9994     function isWhiteSpaceSingleLine(ch) {
9995         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
9996         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
9997         return ch === 32 /* space */ ||
9998             ch === 9 /* tab */ ||
9999             ch === 11 /* verticalTab */ ||
10000             ch === 12 /* formFeed */ ||
10001             ch === 160 /* nonBreakingSpace */ ||
10002             ch === 133 /* nextLine */ ||
10003             ch === 5760 /* ogham */ ||
10004             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
10005             ch === 8239 /* narrowNoBreakSpace */ ||
10006             ch === 8287 /* mathematicalSpace */ ||
10007             ch === 12288 /* ideographicSpace */ ||
10008             ch === 65279 /* byteOrderMark */;
10009     }
10010     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
10011     function isLineBreak(ch) {
10012         // ES5 7.3:
10013         // The ECMAScript line terminator characters are listed in Table 3.
10014         //     Table 3: Line Terminator Characters
10015         //     Code Unit Value     Name                    Formal Name
10016         //     \u000A              Line Feed               <LF>
10017         //     \u000D              Carriage Return         <CR>
10018         //     \u2028              Line separator          <LS>
10019         //     \u2029              Paragraph separator     <PS>
10020         // Only the characters in Table 3 are treated as line terminators. Other new line or line
10021         // breaking characters are treated as white space but not as line terminators.
10022         return ch === 10 /* lineFeed */ ||
10023             ch === 13 /* carriageReturn */ ||
10024             ch === 8232 /* lineSeparator */ ||
10025             ch === 8233 /* paragraphSeparator */;
10026     }
10027     ts.isLineBreak = isLineBreak;
10028     function isDigit(ch) {
10029         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
10030     }
10031     function isHexDigit(ch) {
10032         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
10033     }
10034     function isCodePoint(code) {
10035         return code <= 0x10FFFF;
10036     }
10037     /* @internal */
10038     function isOctalDigit(ch) {
10039         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
10040     }
10041     ts.isOctalDigit = isOctalDigit;
10042     function couldStartTrivia(text, pos) {
10043         // Keep in sync with skipTrivia
10044         var ch = text.charCodeAt(pos);
10045         switch (ch) {
10046             case 13 /* carriageReturn */:
10047             case 10 /* lineFeed */:
10048             case 9 /* tab */:
10049             case 11 /* verticalTab */:
10050             case 12 /* formFeed */:
10051             case 32 /* space */:
10052             case 47 /* slash */:
10053             // starts of normal trivia
10054             // falls through
10055             case 60 /* lessThan */:
10056             case 124 /* bar */:
10057             case 61 /* equals */:
10058             case 62 /* greaterThan */:
10059                 // Starts of conflict marker trivia
10060                 return true;
10061             case 35 /* hash */:
10062                 // Only if its the beginning can we have #! trivia
10063                 return pos === 0;
10064             default:
10065                 return ch > 127 /* maxAsciiCharacter */;
10066         }
10067     }
10068     ts.couldStartTrivia = couldStartTrivia;
10069     /* @internal */
10070     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) {
10071         if (ts.positionIsSynthesized(pos)) {
10072             return pos;
10073         }
10074         var canConsumeStar = false;
10075         // Keep in sync with couldStartTrivia
10076         while (true) {
10077             var ch = text.charCodeAt(pos);
10078             switch (ch) {
10079                 case 13 /* carriageReturn */:
10080                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
10081                         pos++;
10082                     }
10083                 // falls through
10084                 case 10 /* lineFeed */:
10085                     pos++;
10086                     if (stopAfterLineBreak) {
10087                         return pos;
10088                     }
10089                     canConsumeStar = !!inJSDoc;
10090                     continue;
10091                 case 9 /* tab */:
10092                 case 11 /* verticalTab */:
10093                 case 12 /* formFeed */:
10094                 case 32 /* space */:
10095                     pos++;
10096                     continue;
10097                 case 47 /* slash */:
10098                     if (stopAtComments) {
10099                         break;
10100                     }
10101                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10102                         pos += 2;
10103                         while (pos < text.length) {
10104                             if (isLineBreak(text.charCodeAt(pos))) {
10105                                 break;
10106                             }
10107                             pos++;
10108                         }
10109                         canConsumeStar = false;
10110                         continue;
10111                     }
10112                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10113                         pos += 2;
10114                         while (pos < text.length) {
10115                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
10116                                 pos += 2;
10117                                 break;
10118                             }
10119                             pos++;
10120                         }
10121                         canConsumeStar = false;
10122                         continue;
10123                     }
10124                     break;
10125                 case 60 /* lessThan */:
10126                 case 124 /* bar */:
10127                 case 61 /* equals */:
10128                 case 62 /* greaterThan */:
10129                     if (isConflictMarkerTrivia(text, pos)) {
10130                         pos = scanConflictMarkerTrivia(text, pos);
10131                         canConsumeStar = false;
10132                         continue;
10133                     }
10134                     break;
10135                 case 35 /* hash */:
10136                     if (pos === 0 && isShebangTrivia(text, pos)) {
10137                         pos = scanShebangTrivia(text, pos);
10138                         canConsumeStar = false;
10139                         continue;
10140                     }
10141                     break;
10142                 case 42 /* asterisk */:
10143                     if (canConsumeStar) {
10144                         pos++;
10145                         canConsumeStar = false;
10146                         continue;
10147                     }
10148                     break;
10149                 default:
10150                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
10151                         pos++;
10152                         continue;
10153                     }
10154                     break;
10155             }
10156             return pos;
10157         }
10158     }
10159     ts.skipTrivia = skipTrivia;
10160     // All conflict markers consist of the same character repeated seven times.  If it is
10161     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
10162     var mergeConflictMarkerLength = "<<<<<<<".length;
10163     function isConflictMarkerTrivia(text, pos) {
10164         ts.Debug.assert(pos >= 0);
10165         // Conflict markers must be at the start of a line.
10166         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
10167             var ch = text.charCodeAt(pos);
10168             if ((pos + mergeConflictMarkerLength) < text.length) {
10169                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
10170                     if (text.charCodeAt(pos + i) !== ch) {
10171                         return false;
10172                     }
10173                 }
10174                 return ch === 61 /* equals */ ||
10175                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
10176             }
10177         }
10178         return false;
10179     }
10180     function scanConflictMarkerTrivia(text, pos, error) {
10181         if (error) {
10182             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
10183         }
10184         var ch = text.charCodeAt(pos);
10185         var len = text.length;
10186         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
10187             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
10188                 pos++;
10189             }
10190         }
10191         else {
10192             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
10193             // Consume everything from the start of a ||||||| or ======= marker to the start
10194             // of the next ======= or >>>>>>> marker.
10195             while (pos < len) {
10196                 var currentChar = text.charCodeAt(pos);
10197                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
10198                     break;
10199                 }
10200                 pos++;
10201             }
10202         }
10203         return pos;
10204     }
10205     var shebangTriviaRegex = /^#!.*/;
10206     /*@internal*/
10207     function isShebangTrivia(text, pos) {
10208         // Shebangs check must only be done at the start of the file
10209         ts.Debug.assert(pos === 0);
10210         return shebangTriviaRegex.test(text);
10211     }
10212     ts.isShebangTrivia = isShebangTrivia;
10213     /*@internal*/
10214     function scanShebangTrivia(text, pos) {
10215         var shebang = shebangTriviaRegex.exec(text)[0];
10216         pos = pos + shebang.length;
10217         return pos;
10218     }
10219     ts.scanShebangTrivia = scanShebangTrivia;
10220     /**
10221      * Invokes a callback for each comment range following the provided position.
10222      *
10223      * Single-line comment ranges include the leading double-slash characters but not the ending
10224      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
10225      * asterisk-slash characters.
10226      *
10227      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
10228      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
10229      * @param text The source text to scan.
10230      * @param pos The position at which to start scanning.
10231      * @param trailing If false, whitespace is skipped until the first line break and comments
10232      *      between that location and the next token are returned. If true, comments occurring
10233      *      between the given position and the next line break are returned.
10234      * @param cb The callback to execute as each comment range is encountered.
10235      * @param state A state value to pass to each iteration of the callback.
10236      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
10237      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
10238      *      return value of the callback.
10239      */
10240     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
10241         var pendingPos;
10242         var pendingEnd;
10243         var pendingKind;
10244         var pendingHasTrailingNewLine;
10245         var hasPendingCommentRange = false;
10246         var collecting = trailing;
10247         var accumulator = initial;
10248         if (pos === 0) {
10249             collecting = true;
10250             var shebang = getShebang(text);
10251             if (shebang) {
10252                 pos = shebang.length;
10253             }
10254         }
10255         scan: while (pos >= 0 && pos < text.length) {
10256             var ch = text.charCodeAt(pos);
10257             switch (ch) {
10258                 case 13 /* carriageReturn */:
10259                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
10260                         pos++;
10261                     }
10262                 // falls through
10263                 case 10 /* lineFeed */:
10264                     pos++;
10265                     if (trailing) {
10266                         break scan;
10267                     }
10268                     collecting = true;
10269                     if (hasPendingCommentRange) {
10270                         pendingHasTrailingNewLine = true;
10271                     }
10272                     continue;
10273                 case 9 /* tab */:
10274                 case 11 /* verticalTab */:
10275                 case 12 /* formFeed */:
10276                 case 32 /* space */:
10277                     pos++;
10278                     continue;
10279                 case 47 /* slash */:
10280                     var nextChar = text.charCodeAt(pos + 1);
10281                     var hasTrailingNewLine = false;
10282                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
10283                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
10284                         var startPos = pos;
10285                         pos += 2;
10286                         if (nextChar === 47 /* slash */) {
10287                             while (pos < text.length) {
10288                                 if (isLineBreak(text.charCodeAt(pos))) {
10289                                     hasTrailingNewLine = true;
10290                                     break;
10291                                 }
10292                                 pos++;
10293                             }
10294                         }
10295                         else {
10296                             while (pos < text.length) {
10297                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
10298                                     pos += 2;
10299                                     break;
10300                                 }
10301                                 pos++;
10302                             }
10303                         }
10304                         if (collecting) {
10305                             if (hasPendingCommentRange) {
10306                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
10307                                 if (!reduce && accumulator) {
10308                                     // If we are not reducing and we have a truthy result, return it.
10309                                     return accumulator;
10310                                 }
10311                             }
10312                             pendingPos = startPos;
10313                             pendingEnd = pos;
10314                             pendingKind = kind;
10315                             pendingHasTrailingNewLine = hasTrailingNewLine;
10316                             hasPendingCommentRange = true;
10317                         }
10318                         continue;
10319                     }
10320                     break scan;
10321                 default:
10322                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
10323                         if (hasPendingCommentRange && isLineBreak(ch)) {
10324                             pendingHasTrailingNewLine = true;
10325                         }
10326                         pos++;
10327                         continue;
10328                     }
10329                     break scan;
10330             }
10331         }
10332         if (hasPendingCommentRange) {
10333             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
10334         }
10335         return accumulator;
10336     }
10337     function forEachLeadingCommentRange(text, pos, cb, state) {
10338         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
10339     }
10340     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
10341     function forEachTrailingCommentRange(text, pos, cb, state) {
10342         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
10343     }
10344     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
10345     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
10346         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
10347     }
10348     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
10349     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
10350         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
10351     }
10352     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
10353     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
10354         if (!comments) {
10355             comments = [];
10356         }
10357         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
10358         return comments;
10359     }
10360     function getLeadingCommentRanges(text, pos) {
10361         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
10362     }
10363     ts.getLeadingCommentRanges = getLeadingCommentRanges;
10364     function getTrailingCommentRanges(text, pos) {
10365         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
10366     }
10367     ts.getTrailingCommentRanges = getTrailingCommentRanges;
10368     /** Optionally, get the shebang */
10369     function getShebang(text) {
10370         var match = shebangTriviaRegex.exec(text);
10371         if (match) {
10372             return match[0];
10373         }
10374     }
10375     ts.getShebang = getShebang;
10376     function isIdentifierStart(ch, languageVersion) {
10377         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
10378             ch === 36 /* $ */ || ch === 95 /* _ */ ||
10379             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
10380     }
10381     ts.isIdentifierStart = isIdentifierStart;
10382     function isIdentifierPart(ch, languageVersion, identifierVariant) {
10383         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
10384             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
10385             // "-" and ":" are valid in JSX Identifiers
10386             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
10387             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
10388     }
10389     ts.isIdentifierPart = isIdentifierPart;
10390     /* @internal */
10391     function isIdentifierText(name, languageVersion, identifierVariant) {
10392         var ch = codePointAt(name, 0);
10393         if (!isIdentifierStart(ch, languageVersion)) {
10394             return false;
10395         }
10396         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
10397             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
10398                 return false;
10399             }
10400         }
10401         return true;
10402     }
10403     ts.isIdentifierText = isIdentifierText;
10404     // Creates a scanner over a (possibly unspecified) range of a piece of text.
10405     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
10406         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
10407         var text = textInitial;
10408         // Current position (end position of text of current token)
10409         var pos;
10410         // end of text
10411         var end;
10412         // Start position of whitespace before current token
10413         var startPos;
10414         // Start position of text of current token
10415         var tokenPos;
10416         var token;
10417         var tokenValue;
10418         var tokenFlags;
10419         var commentDirectives;
10420         var inJSDocType = 0;
10421         setText(text, start, length);
10422         var scanner = {
10423             getStartPos: function () { return startPos; },
10424             getTextPos: function () { return pos; },
10425             getToken: function () { return token; },
10426             getTokenPos: function () { return tokenPos; },
10427             getTokenText: function () { return text.substring(tokenPos, pos); },
10428             getTokenValue: function () { return tokenValue; },
10429             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
10430             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
10431             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
10432             hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
10433             isIdentifier: function () { return token === 79 /* Identifier */ || token > 116 /* LastReservedWord */; },
10434             isReservedWord: function () { return token >= 81 /* FirstReservedWord */ && token <= 116 /* LastReservedWord */; },
10435             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
10436             getCommentDirectives: function () { return commentDirectives; },
10437             getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
10438             getTokenFlags: function () { return tokenFlags; },
10439             reScanGreaterToken: reScanGreaterToken,
10440             reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
10441             reScanSlashToken: reScanSlashToken,
10442             reScanTemplateToken: reScanTemplateToken,
10443             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
10444             scanJsxIdentifier: scanJsxIdentifier,
10445             scanJsxAttributeValue: scanJsxAttributeValue,
10446             reScanJsxAttributeValue: reScanJsxAttributeValue,
10447             reScanJsxToken: reScanJsxToken,
10448             reScanLessThanToken: reScanLessThanToken,
10449             reScanHashToken: reScanHashToken,
10450             reScanQuestionToken: reScanQuestionToken,
10451             reScanInvalidIdentifier: reScanInvalidIdentifier,
10452             scanJsxToken: scanJsxToken,
10453             scanJsDocToken: scanJsDocToken,
10454             scan: scan,
10455             getText: getText,
10456             clearCommentDirectives: clearCommentDirectives,
10457             setText: setText,
10458             setScriptTarget: setScriptTarget,
10459             setLanguageVariant: setLanguageVariant,
10460             setOnError: setOnError,
10461             setTextPos: setTextPos,
10462             setInJSDocType: setInJSDocType,
10463             tryScan: tryScan,
10464             lookAhead: lookAhead,
10465             scanRange: scanRange,
10466         };
10467         if (ts.Debug.isDebugging) {
10468             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
10469                 get: function () {
10470                     var text = scanner.getText();
10471                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
10472                 },
10473             });
10474         }
10475         return scanner;
10476         function error(message, errPos, length) {
10477             if (errPos === void 0) { errPos = pos; }
10478             if (onError) {
10479                 var oldPos = pos;
10480                 pos = errPos;
10481                 onError(message, length || 0);
10482                 pos = oldPos;
10483             }
10484         }
10485         function scanNumberFragment() {
10486             var start = pos;
10487             var allowSeparator = false;
10488             var isPreviousTokenSeparator = false;
10489             var result = "";
10490             while (true) {
10491                 var ch = text.charCodeAt(pos);
10492                 if (ch === 95 /* _ */) {
10493                     tokenFlags |= 512 /* ContainsSeparator */;
10494                     if (allowSeparator) {
10495                         allowSeparator = false;
10496                         isPreviousTokenSeparator = true;
10497                         result += text.substring(start, pos);
10498                     }
10499                     else if (isPreviousTokenSeparator) {
10500                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10501                     }
10502                     else {
10503                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10504                     }
10505                     pos++;
10506                     start = pos;
10507                     continue;
10508                 }
10509                 if (isDigit(ch)) {
10510                     allowSeparator = true;
10511                     isPreviousTokenSeparator = false;
10512                     pos++;
10513                     continue;
10514                 }
10515                 break;
10516             }
10517             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10518                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10519             }
10520             return result + text.substring(start, pos);
10521         }
10522         function scanNumber() {
10523             var start = pos;
10524             var mainFragment = scanNumberFragment();
10525             var decimalFragment;
10526             var scientificFragment;
10527             if (text.charCodeAt(pos) === 46 /* dot */) {
10528                 pos++;
10529                 decimalFragment = scanNumberFragment();
10530             }
10531             var end = pos;
10532             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
10533                 pos++;
10534                 tokenFlags |= 16 /* Scientific */;
10535                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
10536                     pos++;
10537                 var preNumericPart = pos;
10538                 var finalFragment = scanNumberFragment();
10539                 if (!finalFragment) {
10540                     error(ts.Diagnostics.Digit_expected);
10541                 }
10542                 else {
10543                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
10544                     end = pos;
10545                 }
10546             }
10547             var result;
10548             if (tokenFlags & 512 /* ContainsSeparator */) {
10549                 result = mainFragment;
10550                 if (decimalFragment) {
10551                     result += "." + decimalFragment;
10552                 }
10553                 if (scientificFragment) {
10554                     result += scientificFragment;
10555                 }
10556             }
10557             else {
10558                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
10559             }
10560             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
10561                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
10562                 return {
10563                     type: 8 /* NumericLiteral */,
10564                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
10565                 };
10566             }
10567             else {
10568                 tokenValue = result;
10569                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
10570                 checkForIdentifierStartAfterNumericLiteral(start);
10571                 return { type: type, value: tokenValue };
10572             }
10573         }
10574         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
10575             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
10576                 return;
10577             }
10578             var identifierStart = pos;
10579             var length = scanIdentifierParts().length;
10580             if (length === 1 && text[identifierStart] === "n") {
10581                 if (isScientific) {
10582                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
10583                 }
10584                 else {
10585                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
10586                 }
10587             }
10588             else {
10589                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
10590                 pos = identifierStart;
10591             }
10592         }
10593         function scanOctalDigits() {
10594             var start = pos;
10595             while (isOctalDigit(text.charCodeAt(pos))) {
10596                 pos++;
10597             }
10598             return +(text.substring(start, pos));
10599         }
10600         /**
10601          * Scans the given number of hexadecimal digits in the text,
10602          * returning -1 if the given number is unavailable.
10603          */
10604         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
10605             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
10606             return valueString ? parseInt(valueString, 16) : -1;
10607         }
10608         /**
10609          * Scans as many hexadecimal digits as are available in the text,
10610          * returning "" if the given number of digits was unavailable.
10611          */
10612         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
10613             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
10614         }
10615         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
10616             var valueChars = [];
10617             var allowSeparator = false;
10618             var isPreviousTokenSeparator = false;
10619             while (valueChars.length < minCount || scanAsManyAsPossible) {
10620                 var ch = text.charCodeAt(pos);
10621                 if (canHaveSeparators && ch === 95 /* _ */) {
10622                     tokenFlags |= 512 /* ContainsSeparator */;
10623                     if (allowSeparator) {
10624                         allowSeparator = false;
10625                         isPreviousTokenSeparator = true;
10626                     }
10627                     else if (isPreviousTokenSeparator) {
10628                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10629                     }
10630                     else {
10631                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10632                     }
10633                     pos++;
10634                     continue;
10635                 }
10636                 allowSeparator = canHaveSeparators;
10637                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
10638                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
10639                 }
10640                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
10641                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
10642                     break;
10643                 }
10644                 valueChars.push(ch);
10645                 pos++;
10646                 isPreviousTokenSeparator = false;
10647             }
10648             if (valueChars.length < minCount) {
10649                 valueChars = [];
10650             }
10651             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10652                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10653             }
10654             return String.fromCharCode.apply(String, valueChars);
10655         }
10656         function scanString(jsxAttributeString) {
10657             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
10658             var quote = text.charCodeAt(pos);
10659             pos++;
10660             var result = "";
10661             var start = pos;
10662             while (true) {
10663                 if (pos >= end) {
10664                     result += text.substring(start, pos);
10665                     tokenFlags |= 4 /* Unterminated */;
10666                     error(ts.Diagnostics.Unterminated_string_literal);
10667                     break;
10668                 }
10669                 var ch = text.charCodeAt(pos);
10670                 if (ch === quote) {
10671                     result += text.substring(start, pos);
10672                     pos++;
10673                     break;
10674                 }
10675                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
10676                     result += text.substring(start, pos);
10677                     result += scanEscapeSequence();
10678                     start = pos;
10679                     continue;
10680                 }
10681                 if (isLineBreak(ch) && !jsxAttributeString) {
10682                     result += text.substring(start, pos);
10683                     tokenFlags |= 4 /* Unterminated */;
10684                     error(ts.Diagnostics.Unterminated_string_literal);
10685                     break;
10686                 }
10687                 pos++;
10688             }
10689             return result;
10690         }
10691         /**
10692          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
10693          * a literal component of a TemplateExpression.
10694          */
10695         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
10696             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
10697             pos++;
10698             var start = pos;
10699             var contents = "";
10700             var resultingToken;
10701             while (true) {
10702                 if (pos >= end) {
10703                     contents += text.substring(start, pos);
10704                     tokenFlags |= 4 /* Unterminated */;
10705                     error(ts.Diagnostics.Unterminated_template_literal);
10706                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10707                     break;
10708                 }
10709                 var currChar = text.charCodeAt(pos);
10710                 // '`'
10711                 if (currChar === 96 /* backtick */) {
10712                     contents += text.substring(start, pos);
10713                     pos++;
10714                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10715                     break;
10716                 }
10717                 // '${'
10718                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
10719                     contents += text.substring(start, pos);
10720                     pos += 2;
10721                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
10722                     break;
10723                 }
10724                 // Escape character
10725                 if (currChar === 92 /* backslash */) {
10726                     contents += text.substring(start, pos);
10727                     contents += scanEscapeSequence(isTaggedTemplate);
10728                     start = pos;
10729                     continue;
10730                 }
10731                 // Speculated ECMAScript 6 Spec 11.8.6.1:
10732                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
10733                 if (currChar === 13 /* carriageReturn */) {
10734                     contents += text.substring(start, pos);
10735                     pos++;
10736                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10737                         pos++;
10738                     }
10739                     contents += "\n";
10740                     start = pos;
10741                     continue;
10742                 }
10743                 pos++;
10744             }
10745             ts.Debug.assert(resultingToken !== undefined);
10746             tokenValue = contents;
10747             return resultingToken;
10748         }
10749         function scanEscapeSequence(isTaggedTemplate) {
10750             var start = pos;
10751             pos++;
10752             if (pos >= end) {
10753                 error(ts.Diagnostics.Unexpected_end_of_text);
10754                 return "";
10755             }
10756             var ch = text.charCodeAt(pos);
10757             pos++;
10758             switch (ch) {
10759                 case 48 /* _0 */:
10760                     // '\01'
10761                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
10762                         pos++;
10763                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
10764                         return text.substring(start, pos);
10765                     }
10766                     return "\0";
10767                 case 98 /* b */:
10768                     return "\b";
10769                 case 116 /* t */:
10770                     return "\t";
10771                 case 110 /* n */:
10772                     return "\n";
10773                 case 118 /* v */:
10774                     return "\v";
10775                 case 102 /* f */:
10776                     return "\f";
10777                 case 114 /* r */:
10778                     return "\r";
10779                 case 39 /* singleQuote */:
10780                     return "\'";
10781                 case 34 /* doubleQuote */:
10782                     return "\"";
10783                 case 117 /* u */:
10784                     if (isTaggedTemplate) {
10785                         // '\u' or '\u0' or '\u00' or '\u000'
10786                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
10787                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
10788                                 pos = escapePos;
10789                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10790                                 return text.substring(start, pos);
10791                             }
10792                         }
10793                     }
10794                     // '\u{DDDDDDDD}'
10795                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
10796                         pos++;
10797                         // '\u{'
10798                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
10799                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10800                             return text.substring(start, pos);
10801                         }
10802                         if (isTaggedTemplate) {
10803                             var savePos = pos;
10804                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10805                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10806                             // '\u{Not Code Point' or '\u{CodePoint'
10807                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
10808                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10809                                 return text.substring(start, pos);
10810                             }
10811                             else {
10812                                 pos = savePos;
10813                             }
10814                         }
10815                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10816                         return scanExtendedUnicodeEscape();
10817                     }
10818                     tokenFlags |= 1024 /* UnicodeEscape */;
10819                     // '\uDDDD'
10820                     return scanHexadecimalEscape(/*numDigits*/ 4);
10821                 case 120 /* x */:
10822                     if (isTaggedTemplate) {
10823                         if (!isHexDigit(text.charCodeAt(pos))) {
10824                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10825                             return text.substring(start, pos);
10826                         }
10827                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
10828                             pos++;
10829                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10830                             return text.substring(start, pos);
10831                         }
10832                     }
10833                     // '\xDD'
10834                     return scanHexadecimalEscape(/*numDigits*/ 2);
10835                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
10836                 // the line terminator is interpreted to be "the empty code unit sequence".
10837                 case 13 /* carriageReturn */:
10838                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10839                         pos++;
10840                     }
10841                 // falls through
10842                 case 10 /* lineFeed */:
10843                 case 8232 /* lineSeparator */:
10844                 case 8233 /* paragraphSeparator */:
10845                     return "";
10846                 default:
10847                     return String.fromCharCode(ch);
10848             }
10849         }
10850         function scanHexadecimalEscape(numDigits) {
10851             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
10852             if (escapedValue >= 0) {
10853                 return String.fromCharCode(escapedValue);
10854             }
10855             else {
10856                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10857                 return "";
10858             }
10859         }
10860         function scanExtendedUnicodeEscape() {
10861             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10862             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10863             var isInvalidExtendedEscape = false;
10864             // Validate the value of the digit
10865             if (escapedValue < 0) {
10866                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10867                 isInvalidExtendedEscape = true;
10868             }
10869             else if (escapedValue > 0x10FFFF) {
10870                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
10871                 isInvalidExtendedEscape = true;
10872             }
10873             if (pos >= end) {
10874                 error(ts.Diagnostics.Unexpected_end_of_text);
10875                 isInvalidExtendedEscape = true;
10876             }
10877             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
10878                 // Only swallow the following character up if it's a '}'.
10879                 pos++;
10880             }
10881             else {
10882                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
10883                 isInvalidExtendedEscape = true;
10884             }
10885             if (isInvalidExtendedEscape) {
10886                 return "";
10887             }
10888             return utf16EncodeAsString(escapedValue);
10889         }
10890         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
10891         // and return code point value if valid Unicode escape is found. Otherwise return -1.
10892         function peekUnicodeEscape() {
10893             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
10894                 var start_1 = pos;
10895                 pos += 2;
10896                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
10897                 pos = start_1;
10898                 return value;
10899             }
10900             return -1;
10901         }
10902         function peekExtendedUnicodeEscape() {
10903             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
10904                 var start_2 = pos;
10905                 pos += 3;
10906                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10907                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10908                 pos = start_2;
10909                 return escapedValue;
10910             }
10911             return -1;
10912         }
10913         function scanIdentifierParts() {
10914             var result = "";
10915             var start = pos;
10916             while (pos < end) {
10917                 var ch = codePointAt(text, pos);
10918                 if (isIdentifierPart(ch, languageVersion)) {
10919                     pos += charSize(ch);
10920                 }
10921                 else if (ch === 92 /* backslash */) {
10922                     ch = peekExtendedUnicodeEscape();
10923                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
10924                         pos += 3;
10925                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10926                         result += scanExtendedUnicodeEscape();
10927                         start = pos;
10928                         continue;
10929                     }
10930                     ch = peekUnicodeEscape();
10931                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
10932                         break;
10933                     }
10934                     tokenFlags |= 1024 /* UnicodeEscape */;
10935                     result += text.substring(start, pos);
10936                     result += utf16EncodeAsString(ch);
10937                     // Valid Unicode escape is always six characters
10938                     pos += 6;
10939                     start = pos;
10940                 }
10941                 else {
10942                     break;
10943                 }
10944             }
10945             result += text.substring(start, pos);
10946             return result;
10947         }
10948         function getIdentifierToken() {
10949             // Reserved words are between 2 and 12 characters long and start with a lowercase letter
10950             var len = tokenValue.length;
10951             if (len >= 2 && len <= 12) {
10952                 var ch = tokenValue.charCodeAt(0);
10953                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
10954                     var keyword = textToKeyword.get(tokenValue);
10955                     if (keyword !== undefined) {
10956                         return token = keyword;
10957                     }
10958                 }
10959             }
10960             return token = 79 /* Identifier */;
10961         }
10962         function scanBinaryOrOctalDigits(base) {
10963             var value = "";
10964             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
10965             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
10966             var separatorAllowed = false;
10967             var isPreviousTokenSeparator = false;
10968             while (true) {
10969                 var ch = text.charCodeAt(pos);
10970                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
10971                 if (ch === 95 /* _ */) {
10972                     tokenFlags |= 512 /* ContainsSeparator */;
10973                     if (separatorAllowed) {
10974                         separatorAllowed = false;
10975                         isPreviousTokenSeparator = true;
10976                     }
10977                     else if (isPreviousTokenSeparator) {
10978                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10979                     }
10980                     else {
10981                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10982                     }
10983                     pos++;
10984                     continue;
10985                 }
10986                 separatorAllowed = true;
10987                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
10988                     break;
10989                 }
10990                 value += text[pos];
10991                 pos++;
10992                 isPreviousTokenSeparator = false;
10993             }
10994             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10995                 // Literal ends with underscore - not allowed
10996                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10997             }
10998             return value;
10999         }
11000         function checkBigIntSuffix() {
11001             if (text.charCodeAt(pos) === 110 /* n */) {
11002                 tokenValue += "n";
11003                 // Use base 10 instead of base 2 or base 8 for shorter literals
11004                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
11005                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
11006                 }
11007                 pos++;
11008                 return 9 /* BigIntLiteral */;
11009             }
11010             else { // not a bigint, so can convert to number in simplified form
11011                 // Number() may not support 0b or 0o, so use parseInt() instead
11012                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
11013                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
11014                     : tokenFlags & 256 /* OctalSpecifier */
11015                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
11016                         : +tokenValue;
11017                 tokenValue = "" + numericValue;
11018                 return 8 /* NumericLiteral */;
11019             }
11020         }
11021         function scan() {
11022             var _a;
11023             startPos = pos;
11024             tokenFlags = 0 /* None */;
11025             var asteriskSeen = false;
11026             while (true) {
11027                 tokenPos = pos;
11028                 if (pos >= end) {
11029                     return token = 1 /* EndOfFileToken */;
11030                 }
11031                 var ch = codePointAt(text, pos);
11032                 // Special handling for shebang
11033                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
11034                     pos = scanShebangTrivia(text, pos);
11035                     if (skipTrivia) {
11036                         continue;
11037                     }
11038                     else {
11039                         return token = 6 /* ShebangTrivia */;
11040                     }
11041                 }
11042                 switch (ch) {
11043                     case 10 /* lineFeed */:
11044                     case 13 /* carriageReturn */:
11045                         tokenFlags |= 1 /* PrecedingLineBreak */;
11046                         if (skipTrivia) {
11047                             pos++;
11048                             continue;
11049                         }
11050                         else {
11051                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
11052                                 // consume both CR and LF
11053                                 pos += 2;
11054                             }
11055                             else {
11056                                 pos++;
11057                             }
11058                             return token = 4 /* NewLineTrivia */;
11059                         }
11060                     case 9 /* tab */:
11061                     case 11 /* verticalTab */:
11062                     case 12 /* formFeed */:
11063                     case 32 /* space */:
11064                     case 160 /* nonBreakingSpace */:
11065                     case 5760 /* ogham */:
11066                     case 8192 /* enQuad */:
11067                     case 8193 /* emQuad */:
11068                     case 8194 /* enSpace */:
11069                     case 8195 /* emSpace */:
11070                     case 8196 /* threePerEmSpace */:
11071                     case 8197 /* fourPerEmSpace */:
11072                     case 8198 /* sixPerEmSpace */:
11073                     case 8199 /* figureSpace */:
11074                     case 8200 /* punctuationSpace */:
11075                     case 8201 /* thinSpace */:
11076                     case 8202 /* hairSpace */:
11077                     case 8203 /* zeroWidthSpace */:
11078                     case 8239 /* narrowNoBreakSpace */:
11079                     case 8287 /* mathematicalSpace */:
11080                     case 12288 /* ideographicSpace */:
11081                     case 65279 /* byteOrderMark */:
11082                         if (skipTrivia) {
11083                             pos++;
11084                             continue;
11085                         }
11086                         else {
11087                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
11088                                 pos++;
11089                             }
11090                             return token = 5 /* WhitespaceTrivia */;
11091                         }
11092                     case 33 /* exclamation */:
11093                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11094                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11095                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
11096                             }
11097                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
11098                         }
11099                         pos++;
11100                         return token = 53 /* ExclamationToken */;
11101                     case 34 /* doubleQuote */:
11102                     case 39 /* singleQuote */:
11103                         tokenValue = scanString();
11104                         return token = 10 /* StringLiteral */;
11105                     case 96 /* backtick */:
11106                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
11107                     case 37 /* percent */:
11108                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11109                             return pos += 2, token = 69 /* PercentEqualsToken */;
11110                         }
11111                         pos++;
11112                         return token = 44 /* PercentToken */;
11113                     case 38 /* ampersand */:
11114                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
11115                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11116                                 return pos += 3, token = 76 /* AmpersandAmpersandEqualsToken */;
11117                             }
11118                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
11119                         }
11120                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11121                             return pos += 2, token = 73 /* AmpersandEqualsToken */;
11122                         }
11123                         pos++;
11124                         return token = 50 /* AmpersandToken */;
11125                     case 40 /* openParen */:
11126                         pos++;
11127                         return token = 20 /* OpenParenToken */;
11128                     case 41 /* closeParen */:
11129                         pos++;
11130                         return token = 21 /* CloseParenToken */;
11131                     case 42 /* asterisk */:
11132                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11133                             return pos += 2, token = 66 /* AsteriskEqualsToken */;
11134                         }
11135                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
11136                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11137                                 return pos += 3, token = 67 /* AsteriskAsteriskEqualsToken */;
11138                             }
11139                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
11140                         }
11141                         pos++;
11142                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
11143                             // decoration at the start of a JSDoc comment line
11144                             asteriskSeen = true;
11145                             continue;
11146                         }
11147                         return token = 41 /* AsteriskToken */;
11148                     case 43 /* plus */:
11149                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
11150                             return pos += 2, token = 45 /* PlusPlusToken */;
11151                         }
11152                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11153                             return pos += 2, token = 64 /* PlusEqualsToken */;
11154                         }
11155                         pos++;
11156                         return token = 39 /* PlusToken */;
11157                     case 44 /* comma */:
11158                         pos++;
11159                         return token = 27 /* CommaToken */;
11160                     case 45 /* minus */:
11161                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
11162                             return pos += 2, token = 46 /* MinusMinusToken */;
11163                         }
11164                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11165                             return pos += 2, token = 65 /* MinusEqualsToken */;
11166                         }
11167                         pos++;
11168                         return token = 40 /* MinusToken */;
11169                     case 46 /* dot */:
11170                         if (isDigit(text.charCodeAt(pos + 1))) {
11171                             tokenValue = scanNumber().value;
11172                             return token = 8 /* NumericLiteral */;
11173                         }
11174                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
11175                             return pos += 3, token = 25 /* DotDotDotToken */;
11176                         }
11177                         pos++;
11178                         return token = 24 /* DotToken */;
11179                     case 47 /* slash */:
11180                         // Single-line comment
11181                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
11182                             pos += 2;
11183                             while (pos < end) {
11184                                 if (isLineBreak(text.charCodeAt(pos))) {
11185                                     break;
11186                                 }
11187                                 pos++;
11188                             }
11189                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
11190                             if (skipTrivia) {
11191                                 continue;
11192                             }
11193                             else {
11194                                 return token = 2 /* SingleLineCommentTrivia */;
11195                             }
11196                         }
11197                         // Multi-line comment
11198                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
11199                             pos += 2;
11200                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
11201                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
11202                             }
11203                             var commentClosed = false;
11204                             var lastLineStart = tokenPos;
11205                             while (pos < end) {
11206                                 var ch_1 = text.charCodeAt(pos);
11207                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
11208                                     pos += 2;
11209                                     commentClosed = true;
11210                                     break;
11211                                 }
11212                                 pos++;
11213                                 if (isLineBreak(ch_1)) {
11214                                     lastLineStart = pos;
11215                                     tokenFlags |= 1 /* PrecedingLineBreak */;
11216                                 }
11217                             }
11218                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
11219                             if (!commentClosed) {
11220                                 error(ts.Diagnostics.Asterisk_Slash_expected);
11221                             }
11222                             if (skipTrivia) {
11223                                 continue;
11224                             }
11225                             else {
11226                                 if (!commentClosed) {
11227                                     tokenFlags |= 4 /* Unterminated */;
11228                                 }
11229                                 return token = 3 /* MultiLineCommentTrivia */;
11230                             }
11231                         }
11232                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11233                             return pos += 2, token = 68 /* SlashEqualsToken */;
11234                         }
11235                         pos++;
11236                         return token = 43 /* SlashToken */;
11237                     case 48 /* _0 */:
11238                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
11239                             pos += 2;
11240                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
11241                             if (!tokenValue) {
11242                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
11243                                 tokenValue = "0";
11244                             }
11245                             tokenValue = "0x" + tokenValue;
11246                             tokenFlags |= 64 /* HexSpecifier */;
11247                             return token = checkBigIntSuffix();
11248                         }
11249                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
11250                             pos += 2;
11251                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
11252                             if (!tokenValue) {
11253                                 error(ts.Diagnostics.Binary_digit_expected);
11254                                 tokenValue = "0";
11255                             }
11256                             tokenValue = "0b" + tokenValue;
11257                             tokenFlags |= 128 /* BinarySpecifier */;
11258                             return token = checkBigIntSuffix();
11259                         }
11260                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
11261                             pos += 2;
11262                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
11263                             if (!tokenValue) {
11264                                 error(ts.Diagnostics.Octal_digit_expected);
11265                                 tokenValue = "0";
11266                             }
11267                             tokenValue = "0o" + tokenValue;
11268                             tokenFlags |= 256 /* OctalSpecifier */;
11269                             return token = checkBigIntSuffix();
11270                         }
11271                         // Try to parse as an octal
11272                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
11273                             tokenValue = "" + scanOctalDigits();
11274                             tokenFlags |= 32 /* Octal */;
11275                             return token = 8 /* NumericLiteral */;
11276                         }
11277                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
11278                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
11279                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
11280                     // falls through
11281                     case 49 /* _1 */:
11282                     case 50 /* _2 */:
11283                     case 51 /* _3 */:
11284                     case 52 /* _4 */:
11285                     case 53 /* _5 */:
11286                     case 54 /* _6 */:
11287                     case 55 /* _7 */:
11288                     case 56 /* _8 */:
11289                     case 57 /* _9 */:
11290                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
11291                         return token;
11292                     case 58 /* colon */:
11293                         pos++;
11294                         return token = 58 /* ColonToken */;
11295                     case 59 /* semicolon */:
11296                         pos++;
11297                         return token = 26 /* SemicolonToken */;
11298                     case 60 /* lessThan */:
11299                         if (isConflictMarkerTrivia(text, pos)) {
11300                             pos = scanConflictMarkerTrivia(text, pos, error);
11301                             if (skipTrivia) {
11302                                 continue;
11303                             }
11304                             else {
11305                                 return token = 7 /* ConflictMarkerTrivia */;
11306                             }
11307                         }
11308                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
11309                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11310                                 return pos += 3, token = 70 /* LessThanLessThanEqualsToken */;
11311                             }
11312                             return pos += 2, token = 47 /* LessThanLessThanToken */;
11313                         }
11314                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11315                             return pos += 2, token = 32 /* LessThanEqualsToken */;
11316                         }
11317                         if (languageVariant === 1 /* JSX */ &&
11318                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
11319                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
11320                             return pos += 2, token = 30 /* LessThanSlashToken */;
11321                         }
11322                         pos++;
11323                         return token = 29 /* LessThanToken */;
11324                     case 61 /* equals */:
11325                         if (isConflictMarkerTrivia(text, pos)) {
11326                             pos = scanConflictMarkerTrivia(text, pos, error);
11327                             if (skipTrivia) {
11328                                 continue;
11329                             }
11330                             else {
11331                                 return token = 7 /* ConflictMarkerTrivia */;
11332                             }
11333                         }
11334                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11335                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11336                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
11337                             }
11338                             return pos += 2, token = 34 /* EqualsEqualsToken */;
11339                         }
11340                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
11341                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
11342                         }
11343                         pos++;
11344                         return token = 63 /* EqualsToken */;
11345                     case 62 /* greaterThan */:
11346                         if (isConflictMarkerTrivia(text, pos)) {
11347                             pos = scanConflictMarkerTrivia(text, pos, error);
11348                             if (skipTrivia) {
11349                                 continue;
11350                             }
11351                             else {
11352                                 return token = 7 /* ConflictMarkerTrivia */;
11353                             }
11354                         }
11355                         pos++;
11356                         return token = 31 /* GreaterThanToken */;
11357                     case 63 /* question */:
11358                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
11359                             return pos += 2, token = 28 /* QuestionDotToken */;
11360                         }
11361                         if (text.charCodeAt(pos + 1) === 63 /* question */) {
11362                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11363                                 return pos += 3, token = 77 /* QuestionQuestionEqualsToken */;
11364                             }
11365                             return pos += 2, token = 60 /* QuestionQuestionToken */;
11366                         }
11367                         pos++;
11368                         return token = 57 /* QuestionToken */;
11369                     case 91 /* openBracket */:
11370                         pos++;
11371                         return token = 22 /* OpenBracketToken */;
11372                     case 93 /* closeBracket */:
11373                         pos++;
11374                         return token = 23 /* CloseBracketToken */;
11375                     case 94 /* caret */:
11376                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11377                             return pos += 2, token = 78 /* CaretEqualsToken */;
11378                         }
11379                         pos++;
11380                         return token = 52 /* CaretToken */;
11381                     case 123 /* openBrace */:
11382                         pos++;
11383                         return token = 18 /* OpenBraceToken */;
11384                     case 124 /* bar */:
11385                         if (isConflictMarkerTrivia(text, pos)) {
11386                             pos = scanConflictMarkerTrivia(text, pos, error);
11387                             if (skipTrivia) {
11388                                 continue;
11389                             }
11390                             else {
11391                                 return token = 7 /* ConflictMarkerTrivia */;
11392                             }
11393                         }
11394                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
11395                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11396                                 return pos += 3, token = 75 /* BarBarEqualsToken */;
11397                             }
11398                             return pos += 2, token = 56 /* BarBarToken */;
11399                         }
11400                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11401                             return pos += 2, token = 74 /* BarEqualsToken */;
11402                         }
11403                         pos++;
11404                         return token = 51 /* BarToken */;
11405                     case 125 /* closeBrace */:
11406                         pos++;
11407                         return token = 19 /* CloseBraceToken */;
11408                     case 126 /* tilde */:
11409                         pos++;
11410                         return token = 54 /* TildeToken */;
11411                     case 64 /* at */:
11412                         pos++;
11413                         return token = 59 /* AtToken */;
11414                     case 92 /* backslash */:
11415                         var extendedCookedChar = peekExtendedUnicodeEscape();
11416                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
11417                             pos += 3;
11418                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
11419                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
11420                             return token = getIdentifierToken();
11421                         }
11422                         var cookedChar = peekUnicodeEscape();
11423                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
11424                             pos += 6;
11425                             tokenFlags |= 1024 /* UnicodeEscape */;
11426                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
11427                             return token = getIdentifierToken();
11428                         }
11429                         error(ts.Diagnostics.Invalid_character);
11430                         pos++;
11431                         return token = 0 /* Unknown */;
11432                     case 35 /* hash */:
11433                         if (pos !== 0 && text[pos + 1] === "!") {
11434                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
11435                             pos++;
11436                             return token = 0 /* Unknown */;
11437                         }
11438                         if (isIdentifierStart(codePointAt(text, pos + 1), languageVersion)) {
11439                             pos++;
11440                             scanIdentifier(codePointAt(text, pos), languageVersion);
11441                         }
11442                         else {
11443                             tokenValue = String.fromCharCode(codePointAt(text, pos));
11444                             error(ts.Diagnostics.Invalid_character, pos++, charSize(ch));
11445                         }
11446                         return token = 80 /* PrivateIdentifier */;
11447                     default:
11448                         var identifierKind = scanIdentifier(ch, languageVersion);
11449                         if (identifierKind) {
11450                             return token = identifierKind;
11451                         }
11452                         else if (isWhiteSpaceSingleLine(ch)) {
11453                             pos += charSize(ch);
11454                             continue;
11455                         }
11456                         else if (isLineBreak(ch)) {
11457                             tokenFlags |= 1 /* PrecedingLineBreak */;
11458                             pos += charSize(ch);
11459                             continue;
11460                         }
11461                         var size = charSize(ch);
11462                         error(ts.Diagnostics.Invalid_character, pos, size);
11463                         pos += size;
11464                         return token = 0 /* Unknown */;
11465                 }
11466             }
11467         }
11468         function reScanInvalidIdentifier() {
11469             ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'.");
11470             pos = tokenPos = startPos;
11471             tokenFlags = 0;
11472             var ch = codePointAt(text, pos);
11473             var identifierKind = scanIdentifier(ch, 99 /* ESNext */);
11474             if (identifierKind) {
11475                 return token = identifierKind;
11476             }
11477             pos += charSize(ch);
11478             return token; // Still `SyntaKind.Unknown`
11479         }
11480         function scanIdentifier(startCharacter, languageVersion) {
11481             var ch = startCharacter;
11482             if (isIdentifierStart(ch, languageVersion)) {
11483                 pos += charSize(ch);
11484                 while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
11485                     pos += charSize(ch);
11486                 tokenValue = text.substring(tokenPos, pos);
11487                 if (ch === 92 /* backslash */) {
11488                     tokenValue += scanIdentifierParts();
11489                 }
11490                 return getIdentifierToken();
11491             }
11492         }
11493         function reScanGreaterToken() {
11494             if (token === 31 /* GreaterThanToken */) {
11495                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
11496                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
11497                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
11498                             return pos += 3, token = 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
11499                         }
11500                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
11501                     }
11502                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
11503                         return pos += 2, token = 71 /* GreaterThanGreaterThanEqualsToken */;
11504                     }
11505                     pos++;
11506                     return token = 48 /* GreaterThanGreaterThanToken */;
11507                 }
11508                 if (text.charCodeAt(pos) === 61 /* equals */) {
11509                     pos++;
11510                     return token = 33 /* GreaterThanEqualsToken */;
11511                 }
11512             }
11513             return token;
11514         }
11515         function reScanAsteriskEqualsToken() {
11516             ts.Debug.assert(token === 66 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
11517             pos = tokenPos + 1;
11518             return token = 63 /* EqualsToken */;
11519         }
11520         function reScanSlashToken() {
11521             if (token === 43 /* SlashToken */ || token === 68 /* SlashEqualsToken */) {
11522                 var p = tokenPos + 1;
11523                 var inEscape = false;
11524                 var inCharacterClass = false;
11525                 while (true) {
11526                     // If we reach the end of a file, or hit a newline, then this is an unterminated
11527                     // regex.  Report error and return what we have so far.
11528                     if (p >= end) {
11529                         tokenFlags |= 4 /* Unterminated */;
11530                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
11531                         break;
11532                     }
11533                     var ch = text.charCodeAt(p);
11534                     if (isLineBreak(ch)) {
11535                         tokenFlags |= 4 /* Unterminated */;
11536                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
11537                         break;
11538                     }
11539                     if (inEscape) {
11540                         // Parsing an escape character;
11541                         // reset the flag and just advance to the next char.
11542                         inEscape = false;
11543                     }
11544                     else if (ch === 47 /* slash */ && !inCharacterClass) {
11545                         // A slash within a character class is permissible,
11546                         // but in general it signals the end of the regexp literal.
11547                         p++;
11548                         break;
11549                     }
11550                     else if (ch === 91 /* openBracket */) {
11551                         inCharacterClass = true;
11552                     }
11553                     else if (ch === 92 /* backslash */) {
11554                         inEscape = true;
11555                     }
11556                     else if (ch === 93 /* closeBracket */) {
11557                         inCharacterClass = false;
11558                     }
11559                     p++;
11560                 }
11561                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
11562                     p++;
11563                 }
11564                 pos = p;
11565                 tokenValue = text.substring(tokenPos, pos);
11566                 token = 13 /* RegularExpressionLiteral */;
11567             }
11568             return token;
11569         }
11570         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
11571             var type = getDirectiveFromComment(ts.trimStringStart(text), commentDirectiveRegEx);
11572             if (type === undefined) {
11573                 return commentDirectives;
11574             }
11575             return ts.append(commentDirectives, {
11576                 range: { pos: lineStart, end: pos },
11577                 type: type,
11578             });
11579         }
11580         function getDirectiveFromComment(text, commentDirectiveRegEx) {
11581             var match = commentDirectiveRegEx.exec(text);
11582             if (!match) {
11583                 return undefined;
11584             }
11585             switch (match[1]) {
11586                 case "ts-expect-error":
11587                     return 0 /* ExpectError */;
11588                 case "ts-ignore":
11589                     return 1 /* Ignore */;
11590             }
11591             return undefined;
11592         }
11593         /**
11594          * Unconditionally back up and scan a template expression portion.
11595          */
11596         function reScanTemplateToken(isTaggedTemplate) {
11597             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
11598             pos = tokenPos;
11599             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
11600         }
11601         function reScanTemplateHeadOrNoSubstitutionTemplate() {
11602             pos = tokenPos;
11603             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
11604         }
11605         function reScanJsxToken(allowMultilineJsxText) {
11606             if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; }
11607             pos = tokenPos = startPos;
11608             return token = scanJsxToken(allowMultilineJsxText);
11609         }
11610         function reScanLessThanToken() {
11611             if (token === 47 /* LessThanLessThanToken */) {
11612                 pos = tokenPos + 1;
11613                 return token = 29 /* LessThanToken */;
11614             }
11615             return token;
11616         }
11617         function reScanHashToken() {
11618             if (token === 80 /* PrivateIdentifier */) {
11619                 pos = tokenPos + 1;
11620                 return token = 62 /* HashToken */;
11621             }
11622             return token;
11623         }
11624         function reScanQuestionToken() {
11625             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
11626             pos = tokenPos + 1;
11627             return token = 57 /* QuestionToken */;
11628         }
11629         function scanJsxToken(allowMultilineJsxText) {
11630             if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; }
11631             startPos = tokenPos = pos;
11632             if (pos >= end) {
11633                 return token = 1 /* EndOfFileToken */;
11634             }
11635             var char = text.charCodeAt(pos);
11636             if (char === 60 /* lessThan */) {
11637                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
11638                     pos += 2;
11639                     return token = 30 /* LessThanSlashToken */;
11640                 }
11641                 pos++;
11642                 return token = 29 /* LessThanToken */;
11643             }
11644             if (char === 123 /* openBrace */) {
11645                 pos++;
11646                 return token = 18 /* OpenBraceToken */;
11647             }
11648             // First non-whitespace character on this line.
11649             var firstNonWhitespace = 0;
11650             // These initial values are special because the first line is:
11651             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
11652             while (pos < end) {
11653                 char = text.charCodeAt(pos);
11654                 if (char === 123 /* openBrace */) {
11655                     break;
11656                 }
11657                 if (char === 60 /* lessThan */) {
11658                     if (isConflictMarkerTrivia(text, pos)) {
11659                         pos = scanConflictMarkerTrivia(text, pos, error);
11660                         return token = 7 /* ConflictMarkerTrivia */;
11661                     }
11662                     break;
11663                 }
11664                 if (char === 62 /* greaterThan */) {
11665                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
11666                 }
11667                 if (char === 125 /* closeBrace */) {
11668                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
11669                 }
11670                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
11671                 // i.e (- : whitespace)
11672                 //      <div>----
11673                 //      </div> becomes <div></div>
11674                 //
11675                 //      <div>----</div> becomes <div>----</div>
11676                 if (isLineBreak(char) && firstNonWhitespace === 0) {
11677                     firstNonWhitespace = -1;
11678                 }
11679                 else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) {
11680                     // Stop JsxText on each line during formatting. This allows the formatter to
11681                     // indent each line correctly.
11682                     break;
11683                 }
11684                 else if (!isWhiteSpaceLike(char)) {
11685                     firstNonWhitespace = pos;
11686                 }
11687                 pos++;
11688             }
11689             tokenValue = text.substring(startPos, pos);
11690             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
11691         }
11692         // Scans a JSX identifier; these differ from normal identifiers in that
11693         // they allow dashes
11694         function scanJsxIdentifier() {
11695             if (tokenIsIdentifierOrKeyword(token)) {
11696                 // An identifier or keyword has already been parsed - check for a `-` or a single instance of `:` and then append it and
11697                 // everything after it to the token
11698                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
11699                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
11700                 var namespaceSeparator = false;
11701                 while (pos < end) {
11702                     var ch = text.charCodeAt(pos);
11703                     if (ch === 45 /* minus */) {
11704                         tokenValue += "-";
11705                         pos++;
11706                         continue;
11707                     }
11708                     else if (ch === 58 /* colon */ && !namespaceSeparator) {
11709                         tokenValue += ":";
11710                         pos++;
11711                         namespaceSeparator = true;
11712                         token = 79 /* Identifier */; // swap from keyword kind to identifier kind
11713                         continue;
11714                     }
11715                     var oldPos = pos;
11716                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
11717                     if (pos === oldPos) {
11718                         break;
11719                     }
11720                 }
11721                 // Do not include a trailing namespace separator in the token, since this is against the spec.
11722                 if (tokenValue.slice(-1) === ":") {
11723                     tokenValue = tokenValue.slice(0, -1);
11724                     pos--;
11725                 }
11726             }
11727             return token;
11728         }
11729         function scanJsxAttributeValue() {
11730             startPos = pos;
11731             switch (text.charCodeAt(pos)) {
11732                 case 34 /* doubleQuote */:
11733                 case 39 /* singleQuote */:
11734                     tokenValue = scanString(/*jsxAttributeString*/ true);
11735                     return token = 10 /* StringLiteral */;
11736                 default:
11737                     // If this scans anything other than `{`, it's a parse error.
11738                     return scan();
11739             }
11740         }
11741         function reScanJsxAttributeValue() {
11742             pos = tokenPos = startPos;
11743             return scanJsxAttributeValue();
11744         }
11745         function scanJsDocToken() {
11746             startPos = tokenPos = pos;
11747             tokenFlags = 0 /* None */;
11748             if (pos >= end) {
11749                 return token = 1 /* EndOfFileToken */;
11750             }
11751             var ch = codePointAt(text, pos);
11752             pos += charSize(ch);
11753             switch (ch) {
11754                 case 9 /* tab */:
11755                 case 11 /* verticalTab */:
11756                 case 12 /* formFeed */:
11757                 case 32 /* space */:
11758                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
11759                         pos++;
11760                     }
11761                     return token = 5 /* WhitespaceTrivia */;
11762                 case 64 /* at */:
11763                     return token = 59 /* AtToken */;
11764                 case 13 /* carriageReturn */:
11765                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
11766                         pos++;
11767                     }
11768                 // falls through
11769                 case 10 /* lineFeed */:
11770                     tokenFlags |= 1 /* PrecedingLineBreak */;
11771                     return token = 4 /* NewLineTrivia */;
11772                 case 42 /* asterisk */:
11773                     return token = 41 /* AsteriskToken */;
11774                 case 123 /* openBrace */:
11775                     return token = 18 /* OpenBraceToken */;
11776                 case 125 /* closeBrace */:
11777                     return token = 19 /* CloseBraceToken */;
11778                 case 91 /* openBracket */:
11779                     return token = 22 /* OpenBracketToken */;
11780                 case 93 /* closeBracket */:
11781                     return token = 23 /* CloseBracketToken */;
11782                 case 60 /* lessThan */:
11783                     return token = 29 /* LessThanToken */;
11784                 case 62 /* greaterThan */:
11785                     return token = 31 /* GreaterThanToken */;
11786                 case 61 /* equals */:
11787                     return token = 63 /* EqualsToken */;
11788                 case 44 /* comma */:
11789                     return token = 27 /* CommaToken */;
11790                 case 46 /* dot */:
11791                     return token = 24 /* DotToken */;
11792                 case 96 /* backtick */:
11793                     return token = 61 /* BacktickToken */;
11794                 case 35 /* hash */:
11795                     return token = 62 /* HashToken */;
11796                 case 92 /* backslash */:
11797                     pos--;
11798                     var extendedCookedChar = peekExtendedUnicodeEscape();
11799                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
11800                         pos += 3;
11801                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
11802                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
11803                         return token = getIdentifierToken();
11804                     }
11805                     var cookedChar = peekUnicodeEscape();
11806                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
11807                         pos += 6;
11808                         tokenFlags |= 1024 /* UnicodeEscape */;
11809                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
11810                         return token = getIdentifierToken();
11811                     }
11812                     pos++;
11813                     return token = 0 /* Unknown */;
11814             }
11815             if (isIdentifierStart(ch, languageVersion)) {
11816                 var char = ch;
11817                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
11818                     pos += charSize(char);
11819                 tokenValue = text.substring(tokenPos, pos);
11820                 if (char === 92 /* backslash */) {
11821                     tokenValue += scanIdentifierParts();
11822                 }
11823                 return token = getIdentifierToken();
11824             }
11825             else {
11826                 return token = 0 /* Unknown */;
11827             }
11828         }
11829         function speculationHelper(callback, isLookahead) {
11830             var savePos = pos;
11831             var saveStartPos = startPos;
11832             var saveTokenPos = tokenPos;
11833             var saveToken = token;
11834             var saveTokenValue = tokenValue;
11835             var saveTokenFlags = tokenFlags;
11836             var result = callback();
11837             // If our callback returned something 'falsy' or we're just looking ahead,
11838             // then unconditionally restore us to where we were.
11839             if (!result || isLookahead) {
11840                 pos = savePos;
11841                 startPos = saveStartPos;
11842                 tokenPos = saveTokenPos;
11843                 token = saveToken;
11844                 tokenValue = saveTokenValue;
11845                 tokenFlags = saveTokenFlags;
11846             }
11847             return result;
11848         }
11849         function scanRange(start, length, callback) {
11850             var saveEnd = end;
11851             var savePos = pos;
11852             var saveStartPos = startPos;
11853             var saveTokenPos = tokenPos;
11854             var saveToken = token;
11855             var saveTokenValue = tokenValue;
11856             var saveTokenFlags = tokenFlags;
11857             var saveErrorExpectations = commentDirectives;
11858             setText(text, start, length);
11859             var result = callback();
11860             end = saveEnd;
11861             pos = savePos;
11862             startPos = saveStartPos;
11863             tokenPos = saveTokenPos;
11864             token = saveToken;
11865             tokenValue = saveTokenValue;
11866             tokenFlags = saveTokenFlags;
11867             commentDirectives = saveErrorExpectations;
11868             return result;
11869         }
11870         function lookAhead(callback) {
11871             return speculationHelper(callback, /*isLookahead*/ true);
11872         }
11873         function tryScan(callback) {
11874             return speculationHelper(callback, /*isLookahead*/ false);
11875         }
11876         function getText() {
11877             return text;
11878         }
11879         function clearCommentDirectives() {
11880             commentDirectives = undefined;
11881         }
11882         function setText(newText, start, length) {
11883             text = newText || "";
11884             end = length === undefined ? text.length : start + length;
11885             setTextPos(start || 0);
11886         }
11887         function setOnError(errorCallback) {
11888             onError = errorCallback;
11889         }
11890         function setScriptTarget(scriptTarget) {
11891             languageVersion = scriptTarget;
11892         }
11893         function setLanguageVariant(variant) {
11894             languageVariant = variant;
11895         }
11896         function setTextPos(textPos) {
11897             ts.Debug.assert(textPos >= 0);
11898             pos = textPos;
11899             startPos = textPos;
11900             tokenPos = textPos;
11901             token = 0 /* Unknown */;
11902             tokenValue = undefined;
11903             tokenFlags = 0 /* None */;
11904         }
11905         function setInJSDocType(inType) {
11906             inJSDocType += inType ? 1 : -1;
11907         }
11908     }
11909     ts.createScanner = createScanner;
11910     /* @internal */
11911     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
11912         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
11913         var size = str.length;
11914         // Account for out-of-bounds indices:
11915         if (i < 0 || i >= size) {
11916             return undefined; // String.codePointAt returns `undefined` for OOB indexes
11917         }
11918         // Get the first code unit
11919         var first = str.charCodeAt(i);
11920         // check if it’s the start of a surrogate pair
11921         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
11922             var second = str.charCodeAt(i + 1);
11923             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
11924                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
11925                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
11926             }
11927         }
11928         return first;
11929     };
11930     /* @internal */
11931     function charSize(ch) {
11932         if (ch >= 0x10000) {
11933             return 2;
11934         }
11935         return 1;
11936     }
11937     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
11938     function utf16EncodeAsStringFallback(codePoint) {
11939         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
11940         if (codePoint <= 65535) {
11941             return String.fromCharCode(codePoint);
11942         }
11943         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
11944         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
11945         return String.fromCharCode(codeUnit1, codeUnit2);
11946     }
11947     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
11948     /* @internal */
11949     function utf16EncodeAsString(codePoint) {
11950         return utf16EncodeAsStringWorker(codePoint);
11951     }
11952     ts.utf16EncodeAsString = utf16EncodeAsString;
11953 })(ts || (ts = {}));
11954 var ts;
11955 (function (ts) {
11956     function isExternalModuleNameRelative(moduleName) {
11957         // TypeScript 1.0 spec (April 2014): 11.2.1
11958         // An external module name is "relative" if the first term is "." or "..".
11959         // 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.
11960         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
11961     }
11962     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
11963     function sortAndDeduplicateDiagnostics(diagnostics) {
11964         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
11965     }
11966     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
11967     function getDefaultLibFileName(options) {
11968         switch (ts.getEmitScriptTarget(options)) {
11969             case 99 /* ESNext */:
11970                 return "lib.esnext.full.d.ts";
11971             case 8 /* ES2021 */:
11972                 return "lib.es2021.full.d.ts";
11973             case 7 /* ES2020 */:
11974                 return "lib.es2020.full.d.ts";
11975             case 6 /* ES2019 */:
11976                 return "lib.es2019.full.d.ts";
11977             case 5 /* ES2018 */:
11978                 return "lib.es2018.full.d.ts";
11979             case 4 /* ES2017 */:
11980                 return "lib.es2017.full.d.ts";
11981             case 3 /* ES2016 */:
11982                 return "lib.es2016.full.d.ts";
11983             case 2 /* ES2015 */:
11984                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
11985             default:
11986                 return "lib.d.ts";
11987         }
11988     }
11989     ts.getDefaultLibFileName = getDefaultLibFileName;
11990     function textSpanEnd(span) {
11991         return span.start + span.length;
11992     }
11993     ts.textSpanEnd = textSpanEnd;
11994     function textSpanIsEmpty(span) {
11995         return span.length === 0;
11996     }
11997     ts.textSpanIsEmpty = textSpanIsEmpty;
11998     function textSpanContainsPosition(span, position) {
11999         return position >= span.start && position < textSpanEnd(span);
12000     }
12001     ts.textSpanContainsPosition = textSpanContainsPosition;
12002     /* @internal */
12003     function textRangeContainsPositionInclusive(span, position) {
12004         return position >= span.pos && position <= span.end;
12005     }
12006     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
12007     // Returns true if 'span' contains 'other'.
12008     function textSpanContainsTextSpan(span, other) {
12009         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
12010     }
12011     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
12012     function textSpanOverlapsWith(span, other) {
12013         return textSpanOverlap(span, other) !== undefined;
12014     }
12015     ts.textSpanOverlapsWith = textSpanOverlapsWith;
12016     function textSpanOverlap(span1, span2) {
12017         var overlap = textSpanIntersection(span1, span2);
12018         return overlap && overlap.length === 0 ? undefined : overlap;
12019     }
12020     ts.textSpanOverlap = textSpanOverlap;
12021     function textSpanIntersectsWithTextSpan(span, other) {
12022         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
12023     }
12024     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
12025     function textSpanIntersectsWith(span, start, length) {
12026         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
12027     }
12028     ts.textSpanIntersectsWith = textSpanIntersectsWith;
12029     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
12030         var end1 = start1 + length1;
12031         var end2 = start2 + length2;
12032         return start2 <= end1 && end2 >= start1;
12033     }
12034     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
12035     function textSpanIntersectsWithPosition(span, position) {
12036         return position <= textSpanEnd(span) && position >= span.start;
12037     }
12038     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
12039     function textSpanIntersection(span1, span2) {
12040         var start = Math.max(span1.start, span2.start);
12041         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
12042         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
12043     }
12044     ts.textSpanIntersection = textSpanIntersection;
12045     function createTextSpan(start, length) {
12046         if (start < 0) {
12047             throw new Error("start < 0");
12048         }
12049         if (length < 0) {
12050             throw new Error("length < 0");
12051         }
12052         return { start: start, length: length };
12053     }
12054     ts.createTextSpan = createTextSpan;
12055     function createTextSpanFromBounds(start, end) {
12056         return createTextSpan(start, end - start);
12057     }
12058     ts.createTextSpanFromBounds = createTextSpanFromBounds;
12059     function textChangeRangeNewSpan(range) {
12060         return createTextSpan(range.span.start, range.newLength);
12061     }
12062     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
12063     function textChangeRangeIsUnchanged(range) {
12064         return textSpanIsEmpty(range.span) && range.newLength === 0;
12065     }
12066     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
12067     function createTextChangeRange(span, newLength) {
12068         if (newLength < 0) {
12069             throw new Error("newLength < 0");
12070         }
12071         return { span: span, newLength: newLength };
12072     }
12073     ts.createTextChangeRange = createTextChangeRange;
12074     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
12075     /**
12076      * Called to merge all the changes that occurred across several versions of a script snapshot
12077      * into a single change.  i.e. if a user keeps making successive edits to a script we will
12078      * have a text change from V1 to V2, V2 to V3, ..., Vn.
12079      *
12080      * This function will then merge those changes into a single change range valid between V1 and
12081      * Vn.
12082      */
12083     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
12084         if (changes.length === 0) {
12085             return ts.unchangedTextChangeRange;
12086         }
12087         if (changes.length === 1) {
12088             return changes[0];
12089         }
12090         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
12091         // as it makes things much easier to reason about.
12092         var change0 = changes[0];
12093         var oldStartN = change0.span.start;
12094         var oldEndN = textSpanEnd(change0.span);
12095         var newEndN = oldStartN + change0.newLength;
12096         for (var i = 1; i < changes.length; i++) {
12097             var nextChange = changes[i];
12098             // Consider the following case:
12099             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
12100             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
12101             // i.e. the span starting at 30 with length 30 is increased to length 40.
12102             //
12103             //      0         10        20        30        40        50        60        70        80        90        100
12104             //      -------------------------------------------------------------------------------------------------------
12105             //                |                                                 /
12106             //                |                                            /----
12107             //  T1            |                                       /----
12108             //                |                                  /----
12109             //                |                             /----
12110             //      -------------------------------------------------------------------------------------------------------
12111             //                                     |                            \
12112             //                                     |                               \
12113             //   T2                                |                                 \
12114             //                                     |                                   \
12115             //                                     |                                      \
12116             //      -------------------------------------------------------------------------------------------------------
12117             //
12118             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
12119             // it's just the min of the old and new starts.  i.e.:
12120             //
12121             //      0         10        20        30        40        50        60        70        80        90        100
12122             //      ------------------------------------------------------------*------------------------------------------
12123             //                |                                                 /
12124             //                |                                            /----
12125             //  T1            |                                       /----
12126             //                |                                  /----
12127             //                |                             /----
12128             //      ----------------------------------------$-------------------$------------------------------------------
12129             //                .                    |                            \
12130             //                .                    |                               \
12131             //   T2           .                    |                                 \
12132             //                .                    |                                   \
12133             //                .                    |                                      \
12134             //      ----------------------------------------------------------------------*--------------------------------
12135             //
12136             // (Note the dots represent the newly inferred start.
12137             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
12138             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
12139             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
12140             // means:
12141             //
12142             //      0         10        20        30        40        50        60        70        80        90        100
12143             //      --------------------------------------------------------------------------------*----------------------
12144             //                |                                                                     /
12145             //                |                                                                /----
12146             //  T1            |                                                           /----
12147             //                |                                                      /----
12148             //                |                                                 /----
12149             //      ------------------------------------------------------------$------------------------------------------
12150             //                .                    |                            \
12151             //                .                    |                               \
12152             //   T2           .                    |                                 \
12153             //                .                    |                                   \
12154             //                .                    |                                      \
12155             //      ----------------------------------------------------------------------*--------------------------------
12156             //
12157             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
12158             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
12159             // that's the same as if we started at char 80 instead of 60.
12160             //
12161             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
12162             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
12163             // first.
12164             //
12165             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
12166             // semantics: { { start: 10, length: 70 }, newLength: 60 }
12167             //
12168             // The math then works out as follows.
12169             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
12170             // final result like so:
12171             //
12172             // {
12173             //      oldStart3: Min(oldStart1, oldStart2),
12174             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
12175             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
12176             // }
12177             var oldStart1 = oldStartN;
12178             var oldEnd1 = oldEndN;
12179             var newEnd1 = newEndN;
12180             var oldStart2 = nextChange.span.start;
12181             var oldEnd2 = textSpanEnd(nextChange.span);
12182             var newEnd2 = oldStart2 + nextChange.newLength;
12183             oldStartN = Math.min(oldStart1, oldStart2);
12184             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
12185             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
12186         }
12187         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
12188     }
12189     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
12190     function getTypeParameterOwner(d) {
12191         if (d && d.kind === 162 /* TypeParameter */) {
12192             for (var current = d; current; current = current.parent) {
12193                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 257 /* InterfaceDeclaration */) {
12194                     return current;
12195                 }
12196             }
12197         }
12198     }
12199     ts.getTypeParameterOwner = getTypeParameterOwner;
12200     function isParameterPropertyDeclaration(node, parent) {
12201         return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 170 /* Constructor */;
12202     }
12203     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
12204     function isEmptyBindingPattern(node) {
12205         if (isBindingPattern(node)) {
12206             return ts.every(node.elements, isEmptyBindingElement);
12207         }
12208         return false;
12209     }
12210     ts.isEmptyBindingPattern = isEmptyBindingPattern;
12211     function isEmptyBindingElement(node) {
12212         if (ts.isOmittedExpression(node)) {
12213             return true;
12214         }
12215         return isEmptyBindingPattern(node.name);
12216     }
12217     ts.isEmptyBindingElement = isEmptyBindingElement;
12218     function walkUpBindingElementsAndPatterns(binding) {
12219         var node = binding.parent;
12220         while (ts.isBindingElement(node.parent)) {
12221             node = node.parent.parent;
12222         }
12223         return node.parent;
12224     }
12225     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
12226     function getCombinedFlags(node, getFlags) {
12227         if (ts.isBindingElement(node)) {
12228             node = walkUpBindingElementsAndPatterns(node);
12229         }
12230         var flags = getFlags(node);
12231         if (node.kind === 253 /* VariableDeclaration */) {
12232             node = node.parent;
12233         }
12234         if (node && node.kind === 254 /* VariableDeclarationList */) {
12235             flags |= getFlags(node);
12236             node = node.parent;
12237         }
12238         if (node && node.kind === 236 /* VariableStatement */) {
12239             flags |= getFlags(node);
12240         }
12241         return flags;
12242     }
12243     function getCombinedModifierFlags(node) {
12244         return getCombinedFlags(node, ts.getEffectiveModifierFlags);
12245     }
12246     ts.getCombinedModifierFlags = getCombinedModifierFlags;
12247     /* @internal */
12248     function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
12249         return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
12250     }
12251     ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
12252     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
12253     // nodes like variable declarations and binding elements can returned a view of their flags
12254     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
12255     // stored on the variable declaration directly, but on the containing variable statement
12256     // (if it has one).  Similarly, flags for let/const are stored on the variable declaration
12257     // list.  By calling this function, all those flags are combined so that the client can treat
12258     // the node as if it actually had those flags.
12259     function getCombinedNodeFlags(node) {
12260         return getCombinedFlags(node, function (n) { return n.flags; });
12261     }
12262     ts.getCombinedNodeFlags = getCombinedNodeFlags;
12263     /* @internal */
12264     ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"];
12265     /**
12266      * Checks to see if the locale is in the appropriate format,
12267      * and if it is, attempts to set the appropriate language.
12268      */
12269     function validateLocaleAndSetLanguage(locale, sys, errors) {
12270         var lowerCaseLocale = locale.toLowerCase();
12271         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale);
12272         if (!matchResult) {
12273             if (errors) {
12274                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
12275             }
12276             return;
12277         }
12278         var language = matchResult[1];
12279         var territory = matchResult[3];
12280         // First try the entire locale, then fall back to just language if that's all we have.
12281         // Either ways do not fail, and fallback to the English diagnostic strings.
12282         if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) {
12283             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
12284         }
12285         // Set the UI locale for string collation
12286         ts.setUILocale(locale);
12287         function trySetLanguageAndTerritory(language, territory, errors) {
12288             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
12289             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
12290             var filePath = ts.combinePaths(containingDirectoryPath, language);
12291             if (territory) {
12292                 filePath = filePath + "-" + territory;
12293             }
12294             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
12295             if (!sys.fileExists(filePath)) {
12296                 return false;
12297             }
12298             // TODO: Add codePage support for readFile?
12299             var fileContents = "";
12300             try {
12301                 fileContents = sys.readFile(filePath);
12302             }
12303             catch (e) {
12304                 if (errors) {
12305                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
12306                 }
12307                 return false;
12308             }
12309             try {
12310                 // this is a global mutation (or live binding update)!
12311                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
12312             }
12313             catch (_a) {
12314                 if (errors) {
12315                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
12316                 }
12317                 return false;
12318             }
12319             return true;
12320         }
12321     }
12322     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
12323     function getOriginalNode(node, nodeTest) {
12324         if (node) {
12325             while (node.original !== undefined) {
12326                 node = node.original;
12327             }
12328         }
12329         return !nodeTest || nodeTest(node) ? node : undefined;
12330     }
12331     ts.getOriginalNode = getOriginalNode;
12332     function findAncestor(node, callback) {
12333         while (node) {
12334             var result = callback(node);
12335             if (result === "quit") {
12336                 return undefined;
12337             }
12338             else if (result) {
12339                 return node;
12340             }
12341             node = node.parent;
12342         }
12343         return undefined;
12344     }
12345     ts.findAncestor = findAncestor;
12346     /**
12347      * Gets a value indicating whether a node originated in the parse tree.
12348      *
12349      * @param node The node to test.
12350      */
12351     function isParseTreeNode(node) {
12352         return (node.flags & 8 /* Synthesized */) === 0;
12353     }
12354     ts.isParseTreeNode = isParseTreeNode;
12355     function getParseTreeNode(node, nodeTest) {
12356         if (node === undefined || isParseTreeNode(node)) {
12357             return node;
12358         }
12359         node = node.original;
12360         while (node) {
12361             if (isParseTreeNode(node)) {
12362                 return !nodeTest || nodeTest(node) ? node : undefined;
12363             }
12364             node = node.original;
12365         }
12366     }
12367     ts.getParseTreeNode = getParseTreeNode;
12368     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
12369     function escapeLeadingUnderscores(identifier) {
12370         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
12371     }
12372     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
12373     /**
12374      * Remove extra underscore from escaped identifier text content.
12375      *
12376      * @param identifier The escaped identifier text.
12377      * @returns The unescaped identifier text.
12378      */
12379     function unescapeLeadingUnderscores(identifier) {
12380         var id = identifier;
12381         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
12382     }
12383     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
12384     function idText(identifierOrPrivateName) {
12385         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
12386     }
12387     ts.idText = idText;
12388     function symbolName(symbol) {
12389         if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) {
12390             return idText(symbol.valueDeclaration.name);
12391         }
12392         return unescapeLeadingUnderscores(symbol.escapedName);
12393     }
12394     ts.symbolName = symbolName;
12395     /**
12396      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
12397      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
12398      * will be merged with)
12399      */
12400     function nameForNamelessJSDocTypedef(declaration) {
12401         var hostNode = declaration.parent.parent;
12402         if (!hostNode) {
12403             return undefined;
12404         }
12405         // Covers classes, functions - any named declaration host node
12406         if (isDeclaration(hostNode)) {
12407             return getDeclarationIdentifier(hostNode);
12408         }
12409         // Covers remaining cases (returning undefined if none match).
12410         switch (hostNode.kind) {
12411             case 236 /* VariableStatement */:
12412                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
12413                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
12414                 }
12415                 break;
12416             case 237 /* ExpressionStatement */:
12417                 var expr = hostNode.expression;
12418                 if (expr.kind === 220 /* BinaryExpression */ && expr.operatorToken.kind === 63 /* EqualsToken */) {
12419                     expr = expr.left;
12420                 }
12421                 switch (expr.kind) {
12422                     case 205 /* PropertyAccessExpression */:
12423                         return expr.name;
12424                     case 206 /* ElementAccessExpression */:
12425                         var arg = expr.argumentExpression;
12426                         if (ts.isIdentifier(arg)) {
12427                             return arg;
12428                         }
12429                 }
12430                 break;
12431             case 211 /* ParenthesizedExpression */: {
12432                 return getDeclarationIdentifier(hostNode.expression);
12433             }
12434             case 249 /* LabeledStatement */: {
12435                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
12436                     return getDeclarationIdentifier(hostNode.statement);
12437                 }
12438                 break;
12439             }
12440         }
12441     }
12442     function getDeclarationIdentifier(node) {
12443         var name = getNameOfDeclaration(node);
12444         return name && ts.isIdentifier(name) ? name : undefined;
12445     }
12446     /** @internal */
12447     function nodeHasName(statement, name) {
12448         if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
12449             return true;
12450         }
12451         if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
12452             return true;
12453         }
12454         return false;
12455     }
12456     ts.nodeHasName = nodeHasName;
12457     function getNameOfJSDocTypedef(declaration) {
12458         return declaration.name || nameForNamelessJSDocTypedef(declaration);
12459     }
12460     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
12461     /** @internal */
12462     function isNamedDeclaration(node) {
12463         return !!node.name; // A 'name' property should always be a DeclarationName.
12464     }
12465     ts.isNamedDeclaration = isNamedDeclaration;
12466     /** @internal */
12467     function getNonAssignedNameOfDeclaration(declaration) {
12468         switch (declaration.kind) {
12469             case 79 /* Identifier */:
12470                 return declaration;
12471             case 345 /* JSDocPropertyTag */:
12472             case 338 /* JSDocParameterTag */: {
12473                 var name = declaration.name;
12474                 if (name.kind === 160 /* QualifiedName */) {
12475                     return name.right;
12476                 }
12477                 break;
12478             }
12479             case 207 /* CallExpression */:
12480             case 220 /* BinaryExpression */: {
12481                 var expr_1 = declaration;
12482                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
12483                     case 1 /* ExportsProperty */:
12484                     case 4 /* ThisProperty */:
12485                     case 5 /* Property */:
12486                     case 3 /* PrototypeProperty */:
12487                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
12488                     case 7 /* ObjectDefinePropertyValue */:
12489                     case 8 /* ObjectDefinePropertyExports */:
12490                     case 9 /* ObjectDefinePrototypeProperty */:
12491                         return expr_1.arguments[1];
12492                     default:
12493                         return undefined;
12494                 }
12495             }
12496             case 343 /* JSDocTypedefTag */:
12497                 return getNameOfJSDocTypedef(declaration);
12498             case 337 /* JSDocEnumTag */:
12499                 return nameForNamelessJSDocTypedef(declaration);
12500             case 270 /* ExportAssignment */: {
12501                 var expression = declaration.expression;
12502                 return ts.isIdentifier(expression) ? expression : undefined;
12503             }
12504             case 206 /* ElementAccessExpression */:
12505                 var expr = declaration;
12506                 if (ts.isBindableStaticElementAccessExpression(expr)) {
12507                     return expr.argumentExpression;
12508                 }
12509         }
12510         return declaration.name;
12511     }
12512     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
12513     function getNameOfDeclaration(declaration) {
12514         if (declaration === undefined)
12515             return undefined;
12516         return getNonAssignedNameOfDeclaration(declaration) ||
12517             (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
12518     }
12519     ts.getNameOfDeclaration = getNameOfDeclaration;
12520     /*@internal*/
12521     function getAssignedName(node) {
12522         if (!node.parent) {
12523             return undefined;
12524         }
12525         else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
12526             return node.parent.name;
12527         }
12528         else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
12529             if (ts.isIdentifier(node.parent.left)) {
12530                 return node.parent.left;
12531             }
12532             else if (ts.isAccessExpression(node.parent.left)) {
12533                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
12534             }
12535         }
12536         else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
12537             return node.parent.name;
12538         }
12539     }
12540     ts.getAssignedName = getAssignedName;
12541     function getJSDocParameterTagsWorker(param, noCache) {
12542         if (param.name) {
12543             if (ts.isIdentifier(param.name)) {
12544                 var name_1 = param.name.escapedText;
12545                 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
12546             }
12547             else {
12548                 var i = param.parent.parameters.indexOf(param);
12549                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
12550                 var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
12551                 if (i < paramTags.length) {
12552                     return [paramTags[i]];
12553                 }
12554             }
12555         }
12556         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
12557         return ts.emptyArray;
12558     }
12559     /**
12560      * Gets the JSDoc parameter tags for the node if present.
12561      *
12562      * @remarks Returns any JSDoc param tag whose name matches the provided
12563      * parameter, whether a param tag on a containing function
12564      * expression, or a param tag on a variable declaration whose
12565      * initializer is the containing function. The tags closest to the
12566      * node are returned first, so in the previous example, the param
12567      * tag on the containing function expression would be first.
12568      *
12569      * For binding patterns, parameter tags are matched by position.
12570      */
12571     function getJSDocParameterTags(param) {
12572         return getJSDocParameterTagsWorker(param, /*noCache*/ false);
12573     }
12574     ts.getJSDocParameterTags = getJSDocParameterTags;
12575     /* @internal */
12576     function getJSDocParameterTagsNoCache(param) {
12577         return getJSDocParameterTagsWorker(param, /*noCache*/ true);
12578     }
12579     ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
12580     function getJSDocTypeParameterTagsWorker(param, noCache) {
12581         var name = param.name.escapedText;
12582         return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
12583             return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
12584         });
12585     }
12586     /**
12587      * Gets the JSDoc type parameter tags for the node if present.
12588      *
12589      * @remarks Returns any JSDoc template tag whose names match the provided
12590      * parameter, whether a template tag on a containing function
12591      * expression, or a template tag on a variable declaration whose
12592      * initializer is the containing function. The tags closest to the
12593      * node are returned first, so in the previous example, the template
12594      * tag on the containing function expression would be first.
12595      */
12596     function getJSDocTypeParameterTags(param) {
12597         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
12598     }
12599     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
12600     /* @internal */
12601     function getJSDocTypeParameterTagsNoCache(param) {
12602         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
12603     }
12604     ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
12605     /**
12606      * Return true if the node has JSDoc parameter tags.
12607      *
12608      * @remarks Includes parameter tags that are not directly on the node,
12609      * for example on a variable declaration whose initializer is a function expression.
12610      */
12611     function hasJSDocParameterTags(node) {
12612         return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
12613     }
12614     ts.hasJSDocParameterTags = hasJSDocParameterTags;
12615     /** Gets the JSDoc augments tag for the node if present */
12616     function getJSDocAugmentsTag(node) {
12617         return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
12618     }
12619     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
12620     /** Gets the JSDoc implements tags for the node if present */
12621     function getJSDocImplementsTags(node) {
12622         return getAllJSDocTags(node, ts.isJSDocImplementsTag);
12623     }
12624     ts.getJSDocImplementsTags = getJSDocImplementsTags;
12625     /** Gets the JSDoc class tag for the node if present */
12626     function getJSDocClassTag(node) {
12627         return getFirstJSDocTag(node, ts.isJSDocClassTag);
12628     }
12629     ts.getJSDocClassTag = getJSDocClassTag;
12630     /** Gets the JSDoc public tag for the node if present */
12631     function getJSDocPublicTag(node) {
12632         return getFirstJSDocTag(node, ts.isJSDocPublicTag);
12633     }
12634     ts.getJSDocPublicTag = getJSDocPublicTag;
12635     /*@internal*/
12636     function getJSDocPublicTagNoCache(node) {
12637         return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
12638     }
12639     ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
12640     /** Gets the JSDoc private tag for the node if present */
12641     function getJSDocPrivateTag(node) {
12642         return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
12643     }
12644     ts.getJSDocPrivateTag = getJSDocPrivateTag;
12645     /*@internal*/
12646     function getJSDocPrivateTagNoCache(node) {
12647         return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
12648     }
12649     ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
12650     /** Gets the JSDoc protected tag for the node if present */
12651     function getJSDocProtectedTag(node) {
12652         return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
12653     }
12654     ts.getJSDocProtectedTag = getJSDocProtectedTag;
12655     /*@internal*/
12656     function getJSDocProtectedTagNoCache(node) {
12657         return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
12658     }
12659     ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
12660     /** Gets the JSDoc protected tag for the node if present */
12661     function getJSDocReadonlyTag(node) {
12662         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
12663     }
12664     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
12665     /*@internal*/
12666     function getJSDocReadonlyTagNoCache(node) {
12667         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
12668     }
12669     ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
12670     function getJSDocOverrideTagNoCache(node) {
12671         return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true);
12672     }
12673     ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache;
12674     /** Gets the JSDoc deprecated tag for the node if present */
12675     function getJSDocDeprecatedTag(node) {
12676         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
12677     }
12678     ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
12679     /*@internal */
12680     function getJSDocDeprecatedTagNoCache(node) {
12681         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
12682     }
12683     ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
12684     /** Gets the JSDoc enum tag for the node if present */
12685     function getJSDocEnumTag(node) {
12686         return getFirstJSDocTag(node, ts.isJSDocEnumTag);
12687     }
12688     ts.getJSDocEnumTag = getJSDocEnumTag;
12689     /** Gets the JSDoc this tag for the node if present */
12690     function getJSDocThisTag(node) {
12691         return getFirstJSDocTag(node, ts.isJSDocThisTag);
12692     }
12693     ts.getJSDocThisTag = getJSDocThisTag;
12694     /** Gets the JSDoc return tag for the node if present */
12695     function getJSDocReturnTag(node) {
12696         return getFirstJSDocTag(node, ts.isJSDocReturnTag);
12697     }
12698     ts.getJSDocReturnTag = getJSDocReturnTag;
12699     /** Gets the JSDoc template tag for the node if present */
12700     function getJSDocTemplateTag(node) {
12701         return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
12702     }
12703     ts.getJSDocTemplateTag = getJSDocTemplateTag;
12704     /** Gets the JSDoc type tag for the node if present and valid */
12705     function getJSDocTypeTag(node) {
12706         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
12707         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12708         if (tag && tag.typeExpression && tag.typeExpression.type) {
12709             return tag;
12710         }
12711         return undefined;
12712     }
12713     ts.getJSDocTypeTag = getJSDocTypeTag;
12714     /**
12715      * Gets the type node for the node if provided via JSDoc.
12716      *
12717      * @remarks The search includes any JSDoc param tag that relates
12718      * to the provided parameter, for example a type tag on the
12719      * parameter itself, or a param tag on a containing function
12720      * expression, or a param tag on a variable declaration whose
12721      * initializer is the containing function. The tags closest to the
12722      * node are examined first, so in the previous example, the type
12723      * tag directly on the node would be returned.
12724      */
12725     function getJSDocType(node) {
12726         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12727         if (!tag && ts.isParameter(node)) {
12728             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
12729         }
12730         return tag && tag.typeExpression && tag.typeExpression.type;
12731     }
12732     ts.getJSDocType = getJSDocType;
12733     /**
12734      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
12735      *
12736      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
12737      * gets the type from inside the braces, after the fat arrow, etc.
12738      */
12739     function getJSDocReturnType(node) {
12740         var returnTag = getJSDocReturnTag(node);
12741         if (returnTag && returnTag.typeExpression) {
12742             return returnTag.typeExpression.type;
12743         }
12744         var typeTag = getJSDocTypeTag(node);
12745         if (typeTag && typeTag.typeExpression) {
12746             var type = typeTag.typeExpression.type;
12747             if (ts.isTypeLiteralNode(type)) {
12748                 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
12749                 return sig && sig.type;
12750             }
12751             if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
12752                 return type.type;
12753             }
12754         }
12755     }
12756     ts.getJSDocReturnType = getJSDocReturnType;
12757     function getJSDocTagsWorker(node, noCache) {
12758         var tags = node.jsDocCache;
12759         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
12760         if (tags === undefined || noCache) {
12761             var comments = ts.getJSDocCommentsAndTags(node, noCache);
12762             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
12763             tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
12764             if (!noCache) {
12765                 node.jsDocCache = tags;
12766             }
12767         }
12768         return tags;
12769     }
12770     /** Get all JSDoc tags related to a node, including those on parent nodes. */
12771     function getJSDocTags(node) {
12772         return getJSDocTagsWorker(node, /*noCache*/ false);
12773     }
12774     ts.getJSDocTags = getJSDocTags;
12775     /* @internal */
12776     function getJSDocTagsNoCache(node) {
12777         return getJSDocTagsWorker(node, /*noCache*/ true);
12778     }
12779     ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
12780     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
12781     function getFirstJSDocTag(node, predicate, noCache) {
12782         return ts.find(getJSDocTagsWorker(node, noCache), predicate);
12783     }
12784     /** Gets all JSDoc tags that match a specified predicate */
12785     function getAllJSDocTags(node, predicate) {
12786         return getJSDocTags(node).filter(predicate);
12787     }
12788     ts.getAllJSDocTags = getAllJSDocTags;
12789     /** Gets all JSDoc tags of a specified kind */
12790     function getAllJSDocTagsOfKind(node, kind) {
12791         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
12792     }
12793     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
12794     /** Gets the text of a jsdoc comment, flattening links to their text. */
12795     function getTextOfJSDocComment(comment) {
12796         return typeof comment === "string" ? comment
12797             : comment === null || comment === void 0 ? void 0 : comment.map(function (c) {
12798                 // TODO: Other kinds here
12799                 return c.kind === 319 /* JSDocText */ ? c.text : "{@link ".concat(c.name ? ts.entityNameToString(c.name) + " " : "").concat(c.text, "}");
12800             }).join("");
12801     }
12802     ts.getTextOfJSDocComment = getTextOfJSDocComment;
12803     /**
12804      * Gets the effective type parameters. If the node was parsed in a
12805      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
12806      */
12807     function getEffectiveTypeParameterDeclarations(node) {
12808         if (ts.isJSDocSignature(node)) {
12809             return ts.emptyArray;
12810         }
12811         if (ts.isJSDocTypeAlias(node)) {
12812             ts.Debug.assert(node.parent.kind === 318 /* JSDocComment */);
12813             return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
12814         }
12815         if (node.typeParameters) {
12816             return node.typeParameters;
12817         }
12818         if (ts.isInJSFile(node)) {
12819             var decls = ts.getJSDocTypeParameterDeclarations(node);
12820             if (decls.length) {
12821                 return decls;
12822             }
12823             var typeTag = getJSDocType(node);
12824             if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
12825                 return typeTag.typeParameters;
12826             }
12827         }
12828         return ts.emptyArray;
12829     }
12830     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
12831     function getEffectiveConstraintOfTypeParameter(node) {
12832         return node.constraint ? node.constraint :
12833             ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
12834                 undefined;
12835     }
12836     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
12837     // #region
12838     function isMemberName(node) {
12839         return node.kind === 79 /* Identifier */ || node.kind === 80 /* PrivateIdentifier */;
12840     }
12841     ts.isMemberName = isMemberName;
12842     /* @internal */
12843     function isGetOrSetAccessorDeclaration(node) {
12844         return node.kind === 172 /* SetAccessor */ || node.kind === 171 /* GetAccessor */;
12845     }
12846     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
12847     function isPropertyAccessChain(node) {
12848         return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12849     }
12850     ts.isPropertyAccessChain = isPropertyAccessChain;
12851     function isElementAccessChain(node) {
12852         return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12853     }
12854     ts.isElementAccessChain = isElementAccessChain;
12855     function isCallChain(node) {
12856         return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12857     }
12858     ts.isCallChain = isCallChain;
12859     function isOptionalChain(node) {
12860         var kind = node.kind;
12861         return !!(node.flags & 32 /* OptionalChain */) &&
12862             (kind === 205 /* PropertyAccessExpression */
12863                 || kind === 206 /* ElementAccessExpression */
12864                 || kind === 207 /* CallExpression */
12865                 || kind === 229 /* NonNullExpression */);
12866     }
12867     ts.isOptionalChain = isOptionalChain;
12868     /* @internal */
12869     function isOptionalChainRoot(node) {
12870         return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
12871     }
12872     ts.isOptionalChainRoot = isOptionalChainRoot;
12873     /**
12874      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
12875      */
12876     /* @internal */
12877     function isExpressionOfOptionalChainRoot(node) {
12878         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
12879     }
12880     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
12881     /**
12882      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
12883      *
12884      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
12885      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
12886      * 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)
12887      * 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
12888      *   the end of the chain starting at `c?.`)
12889      * 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
12890      *   the end of the chain starting at `a?.`)
12891      */
12892     /* @internal */
12893     function isOutermostOptionalChain(node) {
12894         return !isOptionalChain(node.parent) // cases 1, 2, and 3
12895             || isOptionalChainRoot(node.parent) // case 4
12896             || node !== node.parent.expression; // case 5
12897     }
12898     ts.isOutermostOptionalChain = isOutermostOptionalChain;
12899     function isNullishCoalesce(node) {
12900         return node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
12901     }
12902     ts.isNullishCoalesce = isNullishCoalesce;
12903     function isConstTypeReference(node) {
12904         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
12905             node.typeName.escapedText === "const" && !node.typeArguments;
12906     }
12907     ts.isConstTypeReference = isConstTypeReference;
12908     function skipPartiallyEmittedExpressions(node) {
12909         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
12910     }
12911     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
12912     function isNonNullChain(node) {
12913         return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12914     }
12915     ts.isNonNullChain = isNonNullChain;
12916     function isBreakOrContinueStatement(node) {
12917         return node.kind === 245 /* BreakStatement */ || node.kind === 244 /* ContinueStatement */;
12918     }
12919     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
12920     function isNamedExportBindings(node) {
12921         return node.kind === 273 /* NamespaceExport */ || node.kind === 272 /* NamedExports */;
12922     }
12923     ts.isNamedExportBindings = isNamedExportBindings;
12924     function isUnparsedTextLike(node) {
12925         switch (node.kind) {
12926             case 300 /* UnparsedText */:
12927             case 301 /* UnparsedInternalText */:
12928                 return true;
12929             default:
12930                 return false;
12931         }
12932     }
12933     ts.isUnparsedTextLike = isUnparsedTextLike;
12934     function isUnparsedNode(node) {
12935         return isUnparsedTextLike(node) ||
12936             node.kind === 298 /* UnparsedPrologue */ ||
12937             node.kind === 302 /* UnparsedSyntheticReference */;
12938     }
12939     ts.isUnparsedNode = isUnparsedNode;
12940     function isJSDocPropertyLikeTag(node) {
12941         return node.kind === 345 /* JSDocPropertyTag */ || node.kind === 338 /* JSDocParameterTag */;
12942     }
12943     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
12944     // #endregion
12945     // #region
12946     // Node tests
12947     //
12948     // All node tests in the following list should *not* reference parent pointers so that
12949     // they may be used with transformations.
12950     /* @internal */
12951     function isNode(node) {
12952         return isNodeKind(node.kind);
12953     }
12954     ts.isNode = isNode;
12955     /* @internal */
12956     function isNodeKind(kind) {
12957         return kind >= 160 /* FirstNode */;
12958     }
12959     ts.isNodeKind = isNodeKind;
12960     /**
12961      * True if kind is of some token syntax kind.
12962      * For example, this is true for an IfKeyword but not for an IfStatement.
12963      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12964      */
12965     function isTokenKind(kind) {
12966         return kind >= 0 /* FirstToken */ && kind <= 159 /* LastToken */;
12967     }
12968     ts.isTokenKind = isTokenKind;
12969     /**
12970      * True if node is of some token syntax kind.
12971      * For example, this is true for an IfKeyword but not for an IfStatement.
12972      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12973      */
12974     function isToken(n) {
12975         return isTokenKind(n.kind);
12976     }
12977     ts.isToken = isToken;
12978     // Node Arrays
12979     /* @internal */
12980     function isNodeArray(array) {
12981         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
12982     }
12983     ts.isNodeArray = isNodeArray;
12984     // Literals
12985     /* @internal */
12986     function isLiteralKind(kind) {
12987         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
12988     }
12989     ts.isLiteralKind = isLiteralKind;
12990     function isLiteralExpression(node) {
12991         return isLiteralKind(node.kind);
12992     }
12993     ts.isLiteralExpression = isLiteralExpression;
12994     // Pseudo-literals
12995     /* @internal */
12996     function isTemplateLiteralKind(kind) {
12997         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
12998     }
12999     ts.isTemplateLiteralKind = isTemplateLiteralKind;
13000     function isTemplateLiteralToken(node) {
13001         return isTemplateLiteralKind(node.kind);
13002     }
13003     ts.isTemplateLiteralToken = isTemplateLiteralToken;
13004     function isTemplateMiddleOrTemplateTail(node) {
13005         var kind = node.kind;
13006         return kind === 16 /* TemplateMiddle */
13007             || kind === 17 /* TemplateTail */;
13008     }
13009     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
13010     function isImportOrExportSpecifier(node) {
13011         return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
13012     }
13013     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
13014     function isTypeOnlyImportOrExportDeclaration(node) {
13015         switch (node.kind) {
13016             case 269 /* ImportSpecifier */:
13017             case 274 /* ExportSpecifier */:
13018                 return node.isTypeOnly || node.parent.parent.isTypeOnly;
13019             case 267 /* NamespaceImport */:
13020                 return node.parent.isTypeOnly;
13021             case 266 /* ImportClause */:
13022             case 264 /* ImportEqualsDeclaration */:
13023                 return node.isTypeOnly;
13024             default:
13025                 return false;
13026         }
13027     }
13028     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
13029     function isAssertionKey(node) {
13030         return ts.isStringLiteral(node) || ts.isIdentifier(node);
13031     }
13032     ts.isAssertionKey = isAssertionKey;
13033     function isStringTextContainingNode(node) {
13034         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
13035     }
13036     ts.isStringTextContainingNode = isStringTextContainingNode;
13037     // Identifiers
13038     /* @internal */
13039     function isGeneratedIdentifier(node) {
13040         return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
13041     }
13042     ts.isGeneratedIdentifier = isGeneratedIdentifier;
13043     // Private Identifiers
13044     /*@internal*/
13045     function isPrivateIdentifierClassElementDeclaration(node) {
13046         return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name);
13047     }
13048     ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration;
13049     /*@internal*/
13050     function isPrivateIdentifierPropertyAccessExpression(node) {
13051         return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
13052     }
13053     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
13054     // Keywords
13055     /* @internal */
13056     function isModifierKind(token) {
13057         switch (token) {
13058             case 126 /* AbstractKeyword */:
13059             case 131 /* AsyncKeyword */:
13060             case 85 /* ConstKeyword */:
13061             case 135 /* DeclareKeyword */:
13062             case 88 /* DefaultKeyword */:
13063             case 93 /* ExportKeyword */:
13064             case 123 /* PublicKeyword */:
13065             case 121 /* PrivateKeyword */:
13066             case 122 /* ProtectedKeyword */:
13067             case 144 /* ReadonlyKeyword */:
13068             case 124 /* StaticKeyword */:
13069             case 158 /* OverrideKeyword */:
13070                 return true;
13071         }
13072         return false;
13073     }
13074     ts.isModifierKind = isModifierKind;
13075     /* @internal */
13076     function isParameterPropertyModifier(kind) {
13077         return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */);
13078     }
13079     ts.isParameterPropertyModifier = isParameterPropertyModifier;
13080     /* @internal */
13081     function isClassMemberModifier(idToken) {
13082         return isParameterPropertyModifier(idToken) || idToken === 124 /* StaticKeyword */ || idToken === 158 /* OverrideKeyword */;
13083     }
13084     ts.isClassMemberModifier = isClassMemberModifier;
13085     function isModifier(node) {
13086         return isModifierKind(node.kind);
13087     }
13088     ts.isModifier = isModifier;
13089     function isEntityName(node) {
13090         var kind = node.kind;
13091         return kind === 160 /* QualifiedName */
13092             || kind === 79 /* Identifier */;
13093     }
13094     ts.isEntityName = isEntityName;
13095     function isPropertyName(node) {
13096         var kind = node.kind;
13097         return kind === 79 /* Identifier */
13098             || kind === 80 /* PrivateIdentifier */
13099             || kind === 10 /* StringLiteral */
13100             || kind === 8 /* NumericLiteral */
13101             || kind === 161 /* ComputedPropertyName */;
13102     }
13103     ts.isPropertyName = isPropertyName;
13104     function isBindingName(node) {
13105         var kind = node.kind;
13106         return kind === 79 /* Identifier */
13107             || kind === 200 /* ObjectBindingPattern */
13108             || kind === 201 /* ArrayBindingPattern */;
13109     }
13110     ts.isBindingName = isBindingName;
13111     // Functions
13112     function isFunctionLike(node) {
13113         return !!node && isFunctionLikeKind(node.kind);
13114     }
13115     ts.isFunctionLike = isFunctionLike;
13116     /* @internal */
13117     function isFunctionLikeOrClassStaticBlockDeclaration(node) {
13118         return !!node && (isFunctionLikeKind(node.kind) || ts.isClassStaticBlockDeclaration(node));
13119     }
13120     ts.isFunctionLikeOrClassStaticBlockDeclaration = isFunctionLikeOrClassStaticBlockDeclaration;
13121     /* @internal */
13122     function isFunctionLikeDeclaration(node) {
13123         return node && isFunctionLikeDeclarationKind(node.kind);
13124     }
13125     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
13126     /* @internal */
13127     function isBooleanLiteral(node) {
13128         return node.kind === 110 /* TrueKeyword */ || node.kind === 95 /* FalseKeyword */;
13129     }
13130     ts.isBooleanLiteral = isBooleanLiteral;
13131     function isFunctionLikeDeclarationKind(kind) {
13132         switch (kind) {
13133             case 255 /* FunctionDeclaration */:
13134             case 168 /* MethodDeclaration */:
13135             case 170 /* Constructor */:
13136             case 171 /* GetAccessor */:
13137             case 172 /* SetAccessor */:
13138             case 212 /* FunctionExpression */:
13139             case 213 /* ArrowFunction */:
13140                 return true;
13141             default:
13142                 return false;
13143         }
13144     }
13145     /* @internal */
13146     function isFunctionLikeKind(kind) {
13147         switch (kind) {
13148             case 167 /* MethodSignature */:
13149             case 173 /* CallSignature */:
13150             case 321 /* JSDocSignature */:
13151             case 174 /* ConstructSignature */:
13152             case 175 /* IndexSignature */:
13153             case 178 /* FunctionType */:
13154             case 315 /* JSDocFunctionType */:
13155             case 179 /* ConstructorType */:
13156                 return true;
13157             default:
13158                 return isFunctionLikeDeclarationKind(kind);
13159         }
13160     }
13161     ts.isFunctionLikeKind = isFunctionLikeKind;
13162     /* @internal */
13163     function isFunctionOrModuleBlock(node) {
13164         return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
13165     }
13166     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
13167     // Classes
13168     function isClassElement(node) {
13169         var kind = node.kind;
13170         return kind === 170 /* Constructor */
13171             || kind === 166 /* PropertyDeclaration */
13172             || kind === 168 /* MethodDeclaration */
13173             || kind === 171 /* GetAccessor */
13174             || kind === 172 /* SetAccessor */
13175             || kind === 175 /* IndexSignature */
13176             || kind === 169 /* ClassStaticBlockDeclaration */
13177             || kind === 233 /* SemicolonClassElement */;
13178     }
13179     ts.isClassElement = isClassElement;
13180     function isClassLike(node) {
13181         return node && (node.kind === 256 /* ClassDeclaration */ || node.kind === 225 /* ClassExpression */);
13182     }
13183     ts.isClassLike = isClassLike;
13184     function isAccessor(node) {
13185         return node && (node.kind === 171 /* GetAccessor */ || node.kind === 172 /* SetAccessor */);
13186     }
13187     ts.isAccessor = isAccessor;
13188     /* @internal */
13189     function isMethodOrAccessor(node) {
13190         switch (node.kind) {
13191             case 168 /* MethodDeclaration */:
13192             case 171 /* GetAccessor */:
13193             case 172 /* SetAccessor */:
13194                 return true;
13195             default:
13196                 return false;
13197         }
13198     }
13199     ts.isMethodOrAccessor = isMethodOrAccessor;
13200     // Type members
13201     function isTypeElement(node) {
13202         var kind = node.kind;
13203         return kind === 174 /* ConstructSignature */
13204             || kind === 173 /* CallSignature */
13205             || kind === 165 /* PropertySignature */
13206             || kind === 167 /* MethodSignature */
13207             || kind === 175 /* IndexSignature */;
13208     }
13209     ts.isTypeElement = isTypeElement;
13210     function isClassOrTypeElement(node) {
13211         return isTypeElement(node) || isClassElement(node);
13212     }
13213     ts.isClassOrTypeElement = isClassOrTypeElement;
13214     function isObjectLiteralElementLike(node) {
13215         var kind = node.kind;
13216         return kind === 294 /* PropertyAssignment */
13217             || kind === 295 /* ShorthandPropertyAssignment */
13218             || kind === 296 /* SpreadAssignment */
13219             || kind === 168 /* MethodDeclaration */
13220             || kind === 171 /* GetAccessor */
13221             || kind === 172 /* SetAccessor */;
13222     }
13223     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
13224     // Type
13225     /**
13226      * Node test that determines whether a node is a valid type node.
13227      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
13228      * of a TypeNode.
13229      */
13230     function isTypeNode(node) {
13231         return ts.isTypeNodeKind(node.kind);
13232     }
13233     ts.isTypeNode = isTypeNode;
13234     function isFunctionOrConstructorTypeNode(node) {
13235         switch (node.kind) {
13236             case 178 /* FunctionType */:
13237             case 179 /* ConstructorType */:
13238                 return true;
13239         }
13240         return false;
13241     }
13242     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
13243     // Binding patterns
13244     /* @internal */
13245     function isBindingPattern(node) {
13246         if (node) {
13247             var kind = node.kind;
13248             return kind === 201 /* ArrayBindingPattern */
13249                 || kind === 200 /* ObjectBindingPattern */;
13250         }
13251         return false;
13252     }
13253     ts.isBindingPattern = isBindingPattern;
13254     /* @internal */
13255     function isAssignmentPattern(node) {
13256         var kind = node.kind;
13257         return kind === 203 /* ArrayLiteralExpression */
13258             || kind === 204 /* ObjectLiteralExpression */;
13259     }
13260     ts.isAssignmentPattern = isAssignmentPattern;
13261     /* @internal */
13262     function isArrayBindingElement(node) {
13263         var kind = node.kind;
13264         return kind === 202 /* BindingElement */
13265             || kind === 226 /* OmittedExpression */;
13266     }
13267     ts.isArrayBindingElement = isArrayBindingElement;
13268     /**
13269      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
13270      */
13271     /* @internal */
13272     function isDeclarationBindingElement(bindingElement) {
13273         switch (bindingElement.kind) {
13274             case 253 /* VariableDeclaration */:
13275             case 163 /* Parameter */:
13276             case 202 /* BindingElement */:
13277                 return true;
13278         }
13279         return false;
13280     }
13281     ts.isDeclarationBindingElement = isDeclarationBindingElement;
13282     /**
13283      * Determines whether a node is a BindingOrAssignmentPattern
13284      */
13285     /* @internal */
13286     function isBindingOrAssignmentPattern(node) {
13287         return isObjectBindingOrAssignmentPattern(node)
13288             || isArrayBindingOrAssignmentPattern(node);
13289     }
13290     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
13291     /**
13292      * Determines whether a node is an ObjectBindingOrAssignmentPattern
13293      */
13294     /* @internal */
13295     function isObjectBindingOrAssignmentPattern(node) {
13296         switch (node.kind) {
13297             case 200 /* ObjectBindingPattern */:
13298             case 204 /* ObjectLiteralExpression */:
13299                 return true;
13300         }
13301         return false;
13302     }
13303     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
13304     /* @internal */
13305     function isObjectBindingOrAssignmentElement(node) {
13306         switch (node.kind) {
13307             case 202 /* BindingElement */:
13308             case 294 /* PropertyAssignment */: // AssignmentProperty
13309             case 295 /* ShorthandPropertyAssignment */: // AssignmentProperty
13310             case 296 /* SpreadAssignment */: // AssignmentRestProperty
13311                 return true;
13312         }
13313         return false;
13314     }
13315     ts.isObjectBindingOrAssignmentElement = isObjectBindingOrAssignmentElement;
13316     /**
13317      * Determines whether a node is an ArrayBindingOrAssignmentPattern
13318      */
13319     /* @internal */
13320     function isArrayBindingOrAssignmentPattern(node) {
13321         switch (node.kind) {
13322             case 201 /* ArrayBindingPattern */:
13323             case 203 /* ArrayLiteralExpression */:
13324                 return true;
13325         }
13326         return false;
13327     }
13328     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
13329     /* @internal */
13330     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
13331         var kind = node.kind;
13332         return kind === 205 /* PropertyAccessExpression */
13333             || kind === 160 /* QualifiedName */
13334             || kind === 199 /* ImportType */;
13335     }
13336     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
13337     // Expression
13338     function isPropertyAccessOrQualifiedName(node) {
13339         var kind = node.kind;
13340         return kind === 205 /* PropertyAccessExpression */
13341             || kind === 160 /* QualifiedName */;
13342     }
13343     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
13344     function isCallLikeExpression(node) {
13345         switch (node.kind) {
13346             case 279 /* JsxOpeningElement */:
13347             case 278 /* JsxSelfClosingElement */:
13348             case 207 /* CallExpression */:
13349             case 208 /* NewExpression */:
13350             case 209 /* TaggedTemplateExpression */:
13351             case 164 /* Decorator */:
13352                 return true;
13353             default:
13354                 return false;
13355         }
13356     }
13357     ts.isCallLikeExpression = isCallLikeExpression;
13358     function isCallOrNewExpression(node) {
13359         return node.kind === 207 /* CallExpression */ || node.kind === 208 /* NewExpression */;
13360     }
13361     ts.isCallOrNewExpression = isCallOrNewExpression;
13362     function isTemplateLiteral(node) {
13363         var kind = node.kind;
13364         return kind === 222 /* TemplateExpression */
13365             || kind === 14 /* NoSubstitutionTemplateLiteral */;
13366     }
13367     ts.isTemplateLiteral = isTemplateLiteral;
13368     /* @internal */
13369     function isLeftHandSideExpression(node) {
13370         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
13371     }
13372     ts.isLeftHandSideExpression = isLeftHandSideExpression;
13373     function isLeftHandSideExpressionKind(kind) {
13374         switch (kind) {
13375             case 205 /* PropertyAccessExpression */:
13376             case 206 /* ElementAccessExpression */:
13377             case 208 /* NewExpression */:
13378             case 207 /* CallExpression */:
13379             case 277 /* JsxElement */:
13380             case 278 /* JsxSelfClosingElement */:
13381             case 281 /* JsxFragment */:
13382             case 209 /* TaggedTemplateExpression */:
13383             case 203 /* ArrayLiteralExpression */:
13384             case 211 /* ParenthesizedExpression */:
13385             case 204 /* ObjectLiteralExpression */:
13386             case 225 /* ClassExpression */:
13387             case 212 /* FunctionExpression */:
13388             case 79 /* Identifier */:
13389             case 80 /* PrivateIdentifier */: // technically this is only an Expression if it's in a `#field in expr` BinaryExpression
13390             case 13 /* RegularExpressionLiteral */:
13391             case 8 /* NumericLiteral */:
13392             case 9 /* BigIntLiteral */:
13393             case 10 /* StringLiteral */:
13394             case 14 /* NoSubstitutionTemplateLiteral */:
13395             case 222 /* TemplateExpression */:
13396             case 95 /* FalseKeyword */:
13397             case 104 /* NullKeyword */:
13398             case 108 /* ThisKeyword */:
13399             case 110 /* TrueKeyword */:
13400             case 106 /* SuperKeyword */:
13401             case 229 /* NonNullExpression */:
13402             case 230 /* MetaProperty */:
13403             case 100 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
13404                 return true;
13405             default:
13406                 return false;
13407         }
13408     }
13409     /* @internal */
13410     function isUnaryExpression(node) {
13411         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
13412     }
13413     ts.isUnaryExpression = isUnaryExpression;
13414     function isUnaryExpressionKind(kind) {
13415         switch (kind) {
13416             case 218 /* PrefixUnaryExpression */:
13417             case 219 /* PostfixUnaryExpression */:
13418             case 214 /* DeleteExpression */:
13419             case 215 /* TypeOfExpression */:
13420             case 216 /* VoidExpression */:
13421             case 217 /* AwaitExpression */:
13422             case 210 /* TypeAssertionExpression */:
13423                 return true;
13424             default:
13425                 return isLeftHandSideExpressionKind(kind);
13426         }
13427     }
13428     /* @internal */
13429     function isUnaryExpressionWithWrite(expr) {
13430         switch (expr.kind) {
13431             case 219 /* PostfixUnaryExpression */:
13432                 return true;
13433             case 218 /* PrefixUnaryExpression */:
13434                 return expr.operator === 45 /* PlusPlusToken */ ||
13435                     expr.operator === 46 /* MinusMinusToken */;
13436             default:
13437                 return false;
13438         }
13439     }
13440     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
13441     /* @internal */
13442     /**
13443      * Determines whether a node is an expression based only on its kind.
13444      * Use `isExpressionNode` if not in transforms.
13445      */
13446     function isExpression(node) {
13447         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
13448     }
13449     ts.isExpression = isExpression;
13450     function isExpressionKind(kind) {
13451         switch (kind) {
13452             case 221 /* ConditionalExpression */:
13453             case 223 /* YieldExpression */:
13454             case 213 /* ArrowFunction */:
13455             case 220 /* BinaryExpression */:
13456             case 224 /* SpreadElement */:
13457             case 228 /* AsExpression */:
13458             case 226 /* OmittedExpression */:
13459             case 349 /* CommaListExpression */:
13460             case 348 /* PartiallyEmittedExpression */:
13461                 return true;
13462             default:
13463                 return isUnaryExpressionKind(kind);
13464         }
13465     }
13466     function isAssertionExpression(node) {
13467         var kind = node.kind;
13468         return kind === 210 /* TypeAssertionExpression */
13469             || kind === 228 /* AsExpression */;
13470     }
13471     ts.isAssertionExpression = isAssertionExpression;
13472     /* @internal */
13473     function isNotEmittedOrPartiallyEmittedNode(node) {
13474         return ts.isNotEmittedStatement(node)
13475             || ts.isPartiallyEmittedExpression(node);
13476     }
13477     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
13478     function isIterationStatement(node, lookInLabeledStatements) {
13479         switch (node.kind) {
13480             case 241 /* ForStatement */:
13481             case 242 /* ForInStatement */:
13482             case 243 /* ForOfStatement */:
13483             case 239 /* DoStatement */:
13484             case 240 /* WhileStatement */:
13485                 return true;
13486             case 249 /* LabeledStatement */:
13487                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
13488         }
13489         return false;
13490     }
13491     ts.isIterationStatement = isIterationStatement;
13492     /* @internal */
13493     function isScopeMarker(node) {
13494         return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
13495     }
13496     ts.isScopeMarker = isScopeMarker;
13497     /* @internal */
13498     function hasScopeMarker(statements) {
13499         return ts.some(statements, isScopeMarker);
13500     }
13501     ts.hasScopeMarker = hasScopeMarker;
13502     /* @internal */
13503     function needsScopeMarker(result) {
13504         return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
13505     }
13506     ts.needsScopeMarker = needsScopeMarker;
13507     /* @internal */
13508     function isExternalModuleIndicator(result) {
13509         // Exported top-level member indicates moduleness
13510         return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
13511     }
13512     ts.isExternalModuleIndicator = isExternalModuleIndicator;
13513     /* @internal */
13514     function isForInOrOfStatement(node) {
13515         return node.kind === 242 /* ForInStatement */ || node.kind === 243 /* ForOfStatement */;
13516     }
13517     ts.isForInOrOfStatement = isForInOrOfStatement;
13518     // Element
13519     /* @internal */
13520     function isConciseBody(node) {
13521         return ts.isBlock(node)
13522             || isExpression(node);
13523     }
13524     ts.isConciseBody = isConciseBody;
13525     /* @internal */
13526     function isFunctionBody(node) {
13527         return ts.isBlock(node);
13528     }
13529     ts.isFunctionBody = isFunctionBody;
13530     /* @internal */
13531     function isForInitializer(node) {
13532         return ts.isVariableDeclarationList(node)
13533             || isExpression(node);
13534     }
13535     ts.isForInitializer = isForInitializer;
13536     /* @internal */
13537     function isModuleBody(node) {
13538         var kind = node.kind;
13539         return kind === 261 /* ModuleBlock */
13540             || kind === 260 /* ModuleDeclaration */
13541             || kind === 79 /* Identifier */;
13542     }
13543     ts.isModuleBody = isModuleBody;
13544     /* @internal */
13545     function isNamespaceBody(node) {
13546         var kind = node.kind;
13547         return kind === 261 /* ModuleBlock */
13548             || kind === 260 /* ModuleDeclaration */;
13549     }
13550     ts.isNamespaceBody = isNamespaceBody;
13551     /* @internal */
13552     function isJSDocNamespaceBody(node) {
13553         var kind = node.kind;
13554         return kind === 79 /* Identifier */
13555             || kind === 260 /* ModuleDeclaration */;
13556     }
13557     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
13558     /* @internal */
13559     function isNamedImportBindings(node) {
13560         var kind = node.kind;
13561         return kind === 268 /* NamedImports */
13562             || kind === 267 /* NamespaceImport */;
13563     }
13564     ts.isNamedImportBindings = isNamedImportBindings;
13565     /* @internal */
13566     function isModuleOrEnumDeclaration(node) {
13567         return node.kind === 260 /* ModuleDeclaration */ || node.kind === 259 /* EnumDeclaration */;
13568     }
13569     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
13570     function isDeclarationKind(kind) {
13571         return kind === 213 /* ArrowFunction */
13572             || kind === 202 /* BindingElement */
13573             || kind === 256 /* ClassDeclaration */
13574             || kind === 225 /* ClassExpression */
13575             || kind === 169 /* ClassStaticBlockDeclaration */
13576             || kind === 170 /* Constructor */
13577             || kind === 259 /* EnumDeclaration */
13578             || kind === 297 /* EnumMember */
13579             || kind === 274 /* ExportSpecifier */
13580             || kind === 255 /* FunctionDeclaration */
13581             || kind === 212 /* FunctionExpression */
13582             || kind === 171 /* GetAccessor */
13583             || kind === 266 /* ImportClause */
13584             || kind === 264 /* ImportEqualsDeclaration */
13585             || kind === 269 /* ImportSpecifier */
13586             || kind === 257 /* InterfaceDeclaration */
13587             || kind === 284 /* JsxAttribute */
13588             || kind === 168 /* MethodDeclaration */
13589             || kind === 167 /* MethodSignature */
13590             || kind === 260 /* ModuleDeclaration */
13591             || kind === 263 /* NamespaceExportDeclaration */
13592             || kind === 267 /* NamespaceImport */
13593             || kind === 273 /* NamespaceExport */
13594             || kind === 163 /* Parameter */
13595             || kind === 294 /* PropertyAssignment */
13596             || kind === 166 /* PropertyDeclaration */
13597             || kind === 165 /* PropertySignature */
13598             || kind === 172 /* SetAccessor */
13599             || kind === 295 /* ShorthandPropertyAssignment */
13600             || kind === 258 /* TypeAliasDeclaration */
13601             || kind === 162 /* TypeParameter */
13602             || kind === 253 /* VariableDeclaration */
13603             || kind === 343 /* JSDocTypedefTag */
13604             || kind === 336 /* JSDocCallbackTag */
13605             || kind === 345 /* JSDocPropertyTag */;
13606     }
13607     function isDeclarationStatementKind(kind) {
13608         return kind === 255 /* FunctionDeclaration */
13609             || kind === 275 /* MissingDeclaration */
13610             || kind === 256 /* ClassDeclaration */
13611             || kind === 257 /* InterfaceDeclaration */
13612             || kind === 258 /* TypeAliasDeclaration */
13613             || kind === 259 /* EnumDeclaration */
13614             || kind === 260 /* ModuleDeclaration */
13615             || kind === 265 /* ImportDeclaration */
13616             || kind === 264 /* ImportEqualsDeclaration */
13617             || kind === 271 /* ExportDeclaration */
13618             || kind === 270 /* ExportAssignment */
13619             || kind === 263 /* NamespaceExportDeclaration */;
13620     }
13621     function isStatementKindButNotDeclarationKind(kind) {
13622         return kind === 245 /* BreakStatement */
13623             || kind === 244 /* ContinueStatement */
13624             || kind === 252 /* DebuggerStatement */
13625             || kind === 239 /* DoStatement */
13626             || kind === 237 /* ExpressionStatement */
13627             || kind === 235 /* EmptyStatement */
13628             || kind === 242 /* ForInStatement */
13629             || kind === 243 /* ForOfStatement */
13630             || kind === 241 /* ForStatement */
13631             || kind === 238 /* IfStatement */
13632             || kind === 249 /* LabeledStatement */
13633             || kind === 246 /* ReturnStatement */
13634             || kind === 248 /* SwitchStatement */
13635             || kind === 250 /* ThrowStatement */
13636             || kind === 251 /* TryStatement */
13637             || kind === 236 /* VariableStatement */
13638             || kind === 240 /* WhileStatement */
13639             || kind === 247 /* WithStatement */
13640             || kind === 347 /* NotEmittedStatement */
13641             || kind === 351 /* EndOfDeclarationMarker */
13642             || kind === 350 /* MergeDeclarationMarker */;
13643     }
13644     /* @internal */
13645     function isDeclaration(node) {
13646         if (node.kind === 162 /* TypeParameter */) {
13647             return (node.parent && node.parent.kind !== 342 /* JSDocTemplateTag */) || ts.isInJSFile(node);
13648         }
13649         return isDeclarationKind(node.kind);
13650     }
13651     ts.isDeclaration = isDeclaration;
13652     /* @internal */
13653     function isDeclarationStatement(node) {
13654         return isDeclarationStatementKind(node.kind);
13655     }
13656     ts.isDeclarationStatement = isDeclarationStatement;
13657     /**
13658      * Determines whether the node is a statement that is not also a declaration
13659      */
13660     /* @internal */
13661     function isStatementButNotDeclaration(node) {
13662         return isStatementKindButNotDeclarationKind(node.kind);
13663     }
13664     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
13665     /* @internal */
13666     function isStatement(node) {
13667         var kind = node.kind;
13668         return isStatementKindButNotDeclarationKind(kind)
13669             || isDeclarationStatementKind(kind)
13670             || isBlockStatement(node);
13671     }
13672     ts.isStatement = isStatement;
13673     function isBlockStatement(node) {
13674         if (node.kind !== 234 /* Block */)
13675             return false;
13676         if (node.parent !== undefined) {
13677             if (node.parent.kind === 251 /* TryStatement */ || node.parent.kind === 291 /* CatchClause */) {
13678                 return false;
13679             }
13680         }
13681         return !ts.isFunctionBlock(node);
13682     }
13683     /**
13684      * NOTE: This is similar to `isStatement` but does not access parent pointers.
13685      */
13686     /* @internal */
13687     function isStatementOrBlock(node) {
13688         var kind = node.kind;
13689         return isStatementKindButNotDeclarationKind(kind)
13690             || isDeclarationStatementKind(kind)
13691             || kind === 234 /* Block */;
13692     }
13693     ts.isStatementOrBlock = isStatementOrBlock;
13694     // Module references
13695     /* @internal */
13696     function isModuleReference(node) {
13697         var kind = node.kind;
13698         return kind === 276 /* ExternalModuleReference */
13699             || kind === 160 /* QualifiedName */
13700             || kind === 79 /* Identifier */;
13701     }
13702     ts.isModuleReference = isModuleReference;
13703     // JSX
13704     /* @internal */
13705     function isJsxTagNameExpression(node) {
13706         var kind = node.kind;
13707         return kind === 108 /* ThisKeyword */
13708             || kind === 79 /* Identifier */
13709             || kind === 205 /* PropertyAccessExpression */;
13710     }
13711     ts.isJsxTagNameExpression = isJsxTagNameExpression;
13712     /* @internal */
13713     function isJsxChild(node) {
13714         var kind = node.kind;
13715         return kind === 277 /* JsxElement */
13716             || kind === 287 /* JsxExpression */
13717             || kind === 278 /* JsxSelfClosingElement */
13718             || kind === 11 /* JsxText */
13719             || kind === 281 /* JsxFragment */;
13720     }
13721     ts.isJsxChild = isJsxChild;
13722     /* @internal */
13723     function isJsxAttributeLike(node) {
13724         var kind = node.kind;
13725         return kind === 284 /* JsxAttribute */
13726             || kind === 286 /* JsxSpreadAttribute */;
13727     }
13728     ts.isJsxAttributeLike = isJsxAttributeLike;
13729     /* @internal */
13730     function isStringLiteralOrJsxExpression(node) {
13731         var kind = node.kind;
13732         return kind === 10 /* StringLiteral */
13733             || kind === 287 /* JsxExpression */;
13734     }
13735     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
13736     function isJsxOpeningLikeElement(node) {
13737         var kind = node.kind;
13738         return kind === 279 /* JsxOpeningElement */
13739             || kind === 278 /* JsxSelfClosingElement */;
13740     }
13741     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
13742     // Clauses
13743     function isCaseOrDefaultClause(node) {
13744         var kind = node.kind;
13745         return kind === 288 /* CaseClause */
13746             || kind === 289 /* DefaultClause */;
13747     }
13748     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
13749     // JSDoc
13750     /** True if node is of some JSDoc syntax kind. */
13751     /* @internal */
13752     function isJSDocNode(node) {
13753         return node.kind >= 307 /* FirstJSDocNode */ && node.kind <= 345 /* LastJSDocNode */;
13754     }
13755     ts.isJSDocNode = isJSDocNode;
13756     /** True if node is of a kind that may contain comment text. */
13757     function isJSDocCommentContainingNode(node) {
13758         return node.kind === 318 /* JSDocComment */
13759             || node.kind === 317 /* JSDocNamepathType */
13760             || node.kind === 319 /* JSDocText */
13761             || isJSDocLinkLike(node)
13762             || isJSDocTag(node)
13763             || ts.isJSDocTypeLiteral(node)
13764             || ts.isJSDocSignature(node);
13765     }
13766     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
13767     // TODO: determine what this does before making it public.
13768     /* @internal */
13769     function isJSDocTag(node) {
13770         return node.kind >= 325 /* FirstJSDocTagNode */ && node.kind <= 345 /* LastJSDocTagNode */;
13771     }
13772     ts.isJSDocTag = isJSDocTag;
13773     function isSetAccessor(node) {
13774         return node.kind === 172 /* SetAccessor */;
13775     }
13776     ts.isSetAccessor = isSetAccessor;
13777     function isGetAccessor(node) {
13778         return node.kind === 171 /* GetAccessor */;
13779     }
13780     ts.isGetAccessor = isGetAccessor;
13781     /** True if has jsdoc nodes attached to it. */
13782     /* @internal */
13783     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
13784     function hasJSDocNodes(node) {
13785         var jsDoc = node.jsDoc;
13786         return !!jsDoc && jsDoc.length > 0;
13787     }
13788     ts.hasJSDocNodes = hasJSDocNodes;
13789     /** True if has type node attached to it. */
13790     /* @internal */
13791     function hasType(node) {
13792         return !!node.type;
13793     }
13794     ts.hasType = hasType;
13795     /** True if has initializer node attached to it. */
13796     /* @internal */
13797     function hasInitializer(node) {
13798         return !!node.initializer;
13799     }
13800     ts.hasInitializer = hasInitializer;
13801     /** True if has initializer node attached to it. */
13802     function hasOnlyExpressionInitializer(node) {
13803         switch (node.kind) {
13804             case 253 /* VariableDeclaration */:
13805             case 163 /* Parameter */:
13806             case 202 /* BindingElement */:
13807             case 165 /* PropertySignature */:
13808             case 166 /* PropertyDeclaration */:
13809             case 294 /* PropertyAssignment */:
13810             case 297 /* EnumMember */:
13811                 return true;
13812             default:
13813                 return false;
13814         }
13815     }
13816     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
13817     function isObjectLiteralElement(node) {
13818         return node.kind === 284 /* JsxAttribute */ || node.kind === 286 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
13819     }
13820     ts.isObjectLiteralElement = isObjectLiteralElement;
13821     /* @internal */
13822     function isTypeReferenceType(node) {
13823         return node.kind === 177 /* TypeReference */ || node.kind === 227 /* ExpressionWithTypeArguments */;
13824     }
13825     ts.isTypeReferenceType = isTypeReferenceType;
13826     var MAX_SMI_X86 = 1073741823;
13827     /* @internal */
13828     function guessIndentation(lines) {
13829         var indentation = MAX_SMI_X86;
13830         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
13831             var line = lines_1[_i];
13832             if (!line.length) {
13833                 continue;
13834             }
13835             var i = 0;
13836             for (; i < line.length && i < indentation; i++) {
13837                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
13838                     break;
13839                 }
13840             }
13841             if (i < indentation) {
13842                 indentation = i;
13843             }
13844             if (indentation === 0) {
13845                 return 0;
13846             }
13847         }
13848         return indentation === MAX_SMI_X86 ? undefined : indentation;
13849     }
13850     ts.guessIndentation = guessIndentation;
13851     function isStringLiteralLike(node) {
13852         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
13853     }
13854     ts.isStringLiteralLike = isStringLiteralLike;
13855     function isJSDocLinkLike(node) {
13856         return node.kind === 322 /* JSDocLink */ || node.kind === 323 /* JSDocLinkCode */ || node.kind === 324 /* JSDocLinkPlain */;
13857     }
13858     ts.isJSDocLinkLike = isJSDocLinkLike;
13859     // #endregion
13860 })(ts || (ts = {}));
13861 /* @internal */
13862 var ts;
13863 (function (ts) {
13864     ts.resolvingEmptyArray = [];
13865     ts.externalHelpersModuleNameText = "tslib";
13866     ts.defaultMaximumTruncationLength = 160;
13867     ts.noTruncationMaximumTruncationLength = 1000000;
13868     function getDeclarationOfKind(symbol, kind) {
13869         var declarations = symbol.declarations;
13870         if (declarations) {
13871             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13872                 var declaration = declarations_1[_i];
13873                 if (declaration.kind === kind) {
13874                     return declaration;
13875                 }
13876             }
13877         }
13878         return undefined;
13879     }
13880     ts.getDeclarationOfKind = getDeclarationOfKind;
13881     /**
13882      * Create a new escaped identifier map.
13883      * @deprecated Use `new Map<__String, T>()` instead.
13884      */
13885     function createUnderscoreEscapedMap() {
13886         return new ts.Map();
13887     }
13888     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
13889     /**
13890      * @deprecated Use `!!map?.size` instead
13891      */
13892     function hasEntries(map) {
13893         return !!map && !!map.size;
13894     }
13895     ts.hasEntries = hasEntries;
13896     function createSymbolTable(symbols) {
13897         var result = new ts.Map();
13898         if (symbols) {
13899             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
13900                 var symbol = symbols_1[_i];
13901                 result.set(symbol.escapedName, symbol);
13902             }
13903         }
13904         return result;
13905     }
13906     ts.createSymbolTable = createSymbolTable;
13907     function isTransientSymbol(symbol) {
13908         return (symbol.flags & 33554432 /* Transient */) !== 0;
13909     }
13910     ts.isTransientSymbol = isTransientSymbol;
13911     var stringWriter = createSingleLineStringWriter();
13912     function createSingleLineStringWriter() {
13913         var str = "";
13914         var writeText = function (text) { return str += text; };
13915         return {
13916             getText: function () { return str; },
13917             write: writeText,
13918             rawWrite: writeText,
13919             writeKeyword: writeText,
13920             writeOperator: writeText,
13921             writePunctuation: writeText,
13922             writeSpace: writeText,
13923             writeStringLiteral: writeText,
13924             writeLiteral: writeText,
13925             writeParameter: writeText,
13926             writeProperty: writeText,
13927             writeSymbol: function (s, _) { return writeText(s); },
13928             writeTrailingSemicolon: writeText,
13929             writeComment: writeText,
13930             getTextPos: function () { return str.length; },
13931             getLine: function () { return 0; },
13932             getColumn: function () { return 0; },
13933             getIndent: function () { return 0; },
13934             isAtStartOfLine: function () { return false; },
13935             hasTrailingComment: function () { return false; },
13936             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
13937             // Completely ignore indentation for string writers.  And map newlines to
13938             // a single space.
13939             writeLine: function () { return str += " "; },
13940             increaseIndent: ts.noop,
13941             decreaseIndent: ts.noop,
13942             clear: function () { return str = ""; },
13943             trackSymbol: function () { return false; },
13944             reportInaccessibleThisError: ts.noop,
13945             reportInaccessibleUniqueSymbolError: ts.noop,
13946             reportPrivateInBaseOfClassExpression: ts.noop,
13947         };
13948     }
13949     function changesAffectModuleResolution(oldOptions, newOptions) {
13950         return oldOptions.configFilePath !== newOptions.configFilePath ||
13951             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
13952     }
13953     ts.changesAffectModuleResolution = changesAffectModuleResolution;
13954     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
13955         return optionsHaveChanges(oldOptions, newOptions, ts.moduleResolutionOptionDeclarations);
13956     }
13957     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
13958     function changesAffectingProgramStructure(oldOptions, newOptions) {
13959         return optionsHaveChanges(oldOptions, newOptions, ts.optionsAffectingProgramStructure);
13960     }
13961     ts.changesAffectingProgramStructure = changesAffectingProgramStructure;
13962     function optionsHaveChanges(oldOptions, newOptions, optionDeclarations) {
13963         return oldOptions !== newOptions && optionDeclarations.some(function (o) {
13964             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
13965         });
13966     }
13967     ts.optionsHaveChanges = optionsHaveChanges;
13968     function forEachAncestor(node, callback) {
13969         while (true) {
13970             var res = callback(node);
13971             if (res === "quit")
13972                 return undefined;
13973             if (res !== undefined)
13974                 return res;
13975             if (ts.isSourceFile(node))
13976                 return undefined;
13977             node = node.parent;
13978         }
13979     }
13980     ts.forEachAncestor = forEachAncestor;
13981     /**
13982      * Calls `callback` for each entry in the map, returning the first truthy result.
13983      * Use `map.forEach` instead for normal iteration.
13984      */
13985     function forEachEntry(map, callback) {
13986         var iterator = map.entries();
13987         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13988             var _a = iterResult.value, key = _a[0], value = _a[1];
13989             var result = callback(value, key);
13990             if (result) {
13991                 return result;
13992             }
13993         }
13994         return undefined;
13995     }
13996     ts.forEachEntry = forEachEntry;
13997     /** `forEachEntry` for just keys. */
13998     function forEachKey(map, callback) {
13999         var iterator = map.keys();
14000         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
14001             var result = callback(iterResult.value);
14002             if (result) {
14003                 return result;
14004             }
14005         }
14006         return undefined;
14007     }
14008     ts.forEachKey = forEachKey;
14009     /** Copy entries from `source` to `target`. */
14010     function copyEntries(source, target) {
14011         source.forEach(function (value, key) {
14012             target.set(key, value);
14013         });
14014     }
14015     ts.copyEntries = copyEntries;
14016     function usingSingleLineStringWriter(action) {
14017         var oldString = stringWriter.getText();
14018         try {
14019             action(stringWriter);
14020             return stringWriter.getText();
14021         }
14022         finally {
14023             stringWriter.clear();
14024             stringWriter.writeKeyword(oldString);
14025         }
14026     }
14027     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
14028     function getFullWidth(node) {
14029         return node.end - node.pos;
14030     }
14031     ts.getFullWidth = getFullWidth;
14032     function getResolvedModule(sourceFile, moduleNameText, mode) {
14033         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText, mode);
14034     }
14035     ts.getResolvedModule = getResolvedModule;
14036     function setResolvedModule(sourceFile, moduleNameText, resolvedModule, mode) {
14037         if (!sourceFile.resolvedModules) {
14038             sourceFile.resolvedModules = ts.createModeAwareCache();
14039         }
14040         sourceFile.resolvedModules.set(moduleNameText, mode, resolvedModule);
14041     }
14042     ts.setResolvedModule = setResolvedModule;
14043     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
14044         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
14045             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createModeAwareCache();
14046         }
14047         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, /*mode*/ undefined, resolvedTypeReferenceDirective);
14048     }
14049     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
14050     function projectReferenceIsEqualTo(oldRef, newRef) {
14051         return oldRef.path === newRef.path &&
14052             !oldRef.prepend === !newRef.prepend &&
14053             !oldRef.circular === !newRef.circular;
14054     }
14055     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
14056     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
14057         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
14058             oldResolution.extension === newResolution.extension &&
14059             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
14060             oldResolution.originalPath === newResolution.originalPath &&
14061             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
14062     }
14063     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
14064     function packageIdIsEqual(a, b) {
14065         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
14066     }
14067     function packageIdToString(_a) {
14068         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
14069         var fullName = subModuleName ? "".concat(name, "/").concat(subModuleName) : name;
14070         return "".concat(fullName, "@").concat(version);
14071     }
14072     ts.packageIdToString = packageIdToString;
14073     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
14074         return oldResolution.resolvedFileName === newResolution.resolvedFileName
14075             && oldResolution.primary === newResolution.primary
14076             && oldResolution.originalPath === newResolution.originalPath;
14077     }
14078     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
14079     function hasChangesInResolutions(names, newResolutions, oldResolutions, oldSourceFile, comparer) {
14080         ts.Debug.assert(names.length === newResolutions.length);
14081         for (var i = 0; i < names.length; i++) {
14082             var newResolution = newResolutions[i];
14083             var oldResolution = oldResolutions && oldResolutions.get(names[i], oldSourceFile && ts.getModeForResolutionAtIndex(oldSourceFile, i));
14084             var changed = oldResolution
14085                 ? !newResolution || !comparer(oldResolution, newResolution)
14086                 : newResolution;
14087             if (changed) {
14088                 return true;
14089             }
14090         }
14091         return false;
14092     }
14093     ts.hasChangesInResolutions = hasChangesInResolutions;
14094     // Returns true if this node contains a parse error anywhere underneath it.
14095     function containsParseError(node) {
14096         aggregateChildData(node);
14097         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
14098     }
14099     ts.containsParseError = containsParseError;
14100     function aggregateChildData(node) {
14101         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
14102             // A node is considered to contain a parse error if:
14103             //  a) the parser explicitly marked that it had an error
14104             //  b) any of it's children reported that it had an error.
14105             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
14106                 ts.forEachChild(node, containsParseError);
14107             // If so, mark ourselves accordingly.
14108             if (thisNodeOrAnySubNodesHasError) {
14109                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
14110             }
14111             // Also mark that we've propagated the child information to this node.  This way we can
14112             // always consult the bit directly on this node without needing to check its children
14113             // again.
14114             node.flags |= 524288 /* HasAggregatedChildData */;
14115         }
14116     }
14117     function getSourceFileOfNode(node) {
14118         while (node && node.kind !== 303 /* SourceFile */) {
14119             node = node.parent;
14120         }
14121         return node;
14122     }
14123     ts.getSourceFileOfNode = getSourceFileOfNode;
14124     function getSourceFileOfModule(module) {
14125         return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module));
14126     }
14127     ts.getSourceFileOfModule = getSourceFileOfModule;
14128     function isStatementWithLocals(node) {
14129         switch (node.kind) {
14130             case 234 /* Block */:
14131             case 262 /* CaseBlock */:
14132             case 241 /* ForStatement */:
14133             case 242 /* ForInStatement */:
14134             case 243 /* ForOfStatement */:
14135                 return true;
14136         }
14137         return false;
14138     }
14139     ts.isStatementWithLocals = isStatementWithLocals;
14140     function getStartPositionOfLine(line, sourceFile) {
14141         ts.Debug.assert(line >= 0);
14142         return ts.getLineStarts(sourceFile)[line];
14143     }
14144     ts.getStartPositionOfLine = getStartPositionOfLine;
14145     // This is a useful function for debugging purposes.
14146     function nodePosToString(node) {
14147         var file = getSourceFileOfNode(node);
14148         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
14149         return "".concat(file.fileName, "(").concat(loc.line + 1, ",").concat(loc.character + 1, ")");
14150     }
14151     ts.nodePosToString = nodePosToString;
14152     function getEndLinePosition(line, sourceFile) {
14153         ts.Debug.assert(line >= 0);
14154         var lineStarts = ts.getLineStarts(sourceFile);
14155         var lineIndex = line;
14156         var sourceText = sourceFile.text;
14157         if (lineIndex + 1 === lineStarts.length) {
14158             // last line - return EOF
14159             return sourceText.length - 1;
14160         }
14161         else {
14162             // current line start
14163             var start = lineStarts[lineIndex];
14164             // take the start position of the next line - 1 = it should be some line break
14165             var pos = lineStarts[lineIndex + 1] - 1;
14166             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
14167             // walk backwards skipping line breaks, stop the the beginning of current line.
14168             // i.e:
14169             // <some text>
14170             // $ <- end of line for this position should match the start position
14171             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
14172                 pos--;
14173             }
14174             return pos;
14175         }
14176     }
14177     ts.getEndLinePosition = getEndLinePosition;
14178     /**
14179      * Returns a value indicating whether a name is unique globally or within the current file.
14180      * 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`.
14181      */
14182     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
14183         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
14184     }
14185     ts.isFileLevelUniqueName = isFileLevelUniqueName;
14186     // Returns true if this node is missing from the actual source code. A 'missing' node is different
14187     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
14188     // in the tree), it is definitely missing. However, a node may be defined, but still be
14189     // missing.  This happens whenever the parser knows it needs to parse something, but can't
14190     // get anything in the source code that it expects at that location. For example:
14191     //
14192     //          let a: ;
14193     //
14194     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
14195     // code). So the parser will attempt to parse out a type, and will create an actual node.
14196     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
14197     // contained within it.
14198     function nodeIsMissing(node) {
14199         if (node === undefined) {
14200             return true;
14201         }
14202         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
14203     }
14204     ts.nodeIsMissing = nodeIsMissing;
14205     function nodeIsPresent(node) {
14206         return !nodeIsMissing(node);
14207     }
14208     ts.nodeIsPresent = nodeIsPresent;
14209     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
14210         if (from === undefined || from.length === 0)
14211             return to;
14212         var statementIndex = 0;
14213         // skip all prologue directives to insert at the correct position
14214         for (; statementIndex < to.length; ++statementIndex) {
14215             if (!isPrologueDirective(to[statementIndex])) {
14216                 break;
14217             }
14218         }
14219         to.splice.apply(to, __spreadArray([statementIndex, 0], from, false));
14220         return to;
14221     }
14222     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
14223         if (statement === undefined)
14224             return to;
14225         var statementIndex = 0;
14226         // skip all prologue directives to insert at the correct position
14227         for (; statementIndex < to.length; ++statementIndex) {
14228             if (!isPrologueDirective(to[statementIndex])) {
14229                 break;
14230             }
14231         }
14232         to.splice(statementIndex, 0, statement);
14233         return to;
14234     }
14235     function isAnyPrologueDirective(node) {
14236         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
14237     }
14238     /**
14239      * Prepends statements to an array while taking care of prologue directives.
14240      */
14241     function insertStatementsAfterStandardPrologue(to, from) {
14242         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
14243     }
14244     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
14245     function insertStatementsAfterCustomPrologue(to, from) {
14246         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
14247     }
14248     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
14249     /**
14250      * Prepends statements to an array while taking care of prologue directives.
14251      */
14252     function insertStatementAfterStandardPrologue(to, statement) {
14253         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
14254     }
14255     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
14256     function insertStatementAfterCustomPrologue(to, statement) {
14257         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
14258     }
14259     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
14260     /**
14261      * Determine if the given comment is a triple-slash
14262      *
14263      * @return true if the comment is a triple-slash comment else false
14264      */
14265     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
14266         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
14267         // so that we don't end up computing comment string and doing match for all // comments
14268         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
14269             commentPos + 2 < commentEnd &&
14270             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
14271             var textSubStr = text.substring(commentPos, commentEnd);
14272             return ts.fullTripleSlashReferencePathRegEx.test(textSubStr) ||
14273                 ts.fullTripleSlashAMDReferencePathRegEx.test(textSubStr) ||
14274                 fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) ||
14275                 defaultLibReferenceRegEx.test(textSubStr) ?
14276                 true : false;
14277         }
14278         return false;
14279     }
14280     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
14281     function isPinnedComment(text, start) {
14282         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
14283             text.charCodeAt(start + 2) === 33 /* exclamation */;
14284     }
14285     ts.isPinnedComment = isPinnedComment;
14286     function createCommentDirectivesMap(sourceFile, commentDirectives) {
14287         var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
14288             "".concat(ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line),
14289             commentDirective,
14290         ]); }));
14291         var usedLines = new ts.Map();
14292         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
14293         function getUnusedExpectations() {
14294             return ts.arrayFrom(directivesByLine.entries())
14295                 .filter(function (_a) {
14296                 var line = _a[0], directive = _a[1];
14297                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
14298             })
14299                 .map(function (_a) {
14300                 var _ = _a[0], directive = _a[1];
14301                 return directive;
14302             });
14303         }
14304         function markUsed(line) {
14305             if (!directivesByLine.has("".concat(line))) {
14306                 return false;
14307             }
14308             usedLines.set("".concat(line), true);
14309             return true;
14310         }
14311     }
14312     ts.createCommentDirectivesMap = createCommentDirectivesMap;
14313     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
14314         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
14315         // want to skip trivia because this will launch us forward to the next token.
14316         if (nodeIsMissing(node)) {
14317             return node.pos;
14318         }
14319         if (ts.isJSDocNode(node) || node.kind === 11 /* JsxText */) {
14320             // JsxText cannot actually contain comments, even though the scanner will think it sees comments
14321             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
14322         }
14323         if (includeJsDoc && ts.hasJSDocNodes(node)) {
14324             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
14325         }
14326         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
14327         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
14328         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
14329         // first child to determine the actual position of its first token.
14330         if (node.kind === 346 /* SyntaxList */ && node._children.length > 0) {
14331             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
14332         }
14333         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, 
14334         /*stopAfterLineBreak*/ false, 
14335         /*stopAtComments*/ false, isInJSDoc(node));
14336     }
14337     ts.getTokenPosOfNode = getTokenPosOfNode;
14338     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
14339         if (nodeIsMissing(node) || !node.decorators) {
14340             return getTokenPosOfNode(node, sourceFile);
14341         }
14342         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
14343     }
14344     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
14345     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
14346         if (includeTrivia === void 0) { includeTrivia = false; }
14347         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
14348     }
14349     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
14350     function isJSDocTypeExpressionOrChild(node) {
14351         return !!ts.findAncestor(node, ts.isJSDocTypeExpression);
14352     }
14353     function isExportNamespaceAsDefaultDeclaration(node) {
14354         return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default");
14355     }
14356     ts.isExportNamespaceAsDefaultDeclaration = isExportNamespaceAsDefaultDeclaration;
14357     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
14358         if (includeTrivia === void 0) { includeTrivia = false; }
14359         if (nodeIsMissing(node)) {
14360             return "";
14361         }
14362         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
14363         if (isJSDocTypeExpressionOrChild(node)) {
14364             // strip space + asterisk at line start
14365             text = text.split(/\r\n|\n|\r/).map(function (line) { return ts.trimStringStart(line.replace(/^\s*\*/, "")); }).join("\n");
14366         }
14367         return text;
14368     }
14369     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
14370     function getTextOfNode(node, includeTrivia) {
14371         if (includeTrivia === void 0) { includeTrivia = false; }
14372         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
14373     }
14374     ts.getTextOfNode = getTextOfNode;
14375     function getPos(range) {
14376         return range.pos;
14377     }
14378     /**
14379      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
14380      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
14381      */
14382     function indexOfNode(nodeArray, node) {
14383         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
14384     }
14385     ts.indexOfNode = indexOfNode;
14386     /**
14387      * Gets flags that control emit behavior of a node.
14388      */
14389     function getEmitFlags(node) {
14390         var emitNode = node.emitNode;
14391         return emitNode && emitNode.flags || 0;
14392     }
14393     ts.getEmitFlags = getEmitFlags;
14394     ;
14395     function getScriptTargetFeatures() {
14396         return {
14397             es2015: {
14398                 Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
14399                 RegExp: ["flags", "sticky", "unicode"],
14400                 Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get", " getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
14401                 ArrayConstructor: ["from", "of"],
14402                 ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
14403                 NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
14404                 Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
14405                 Map: ["entries", "keys", "values"],
14406                 Set: ["entries", "keys", "values"],
14407                 Promise: ts.emptyArray,
14408                 PromiseConstructor: ["all", "race", "reject", "resolve"],
14409                 Symbol: ["for", "keyFor"],
14410                 WeakMap: ["entries", "keys", "values"],
14411                 WeakSet: ["entries", "keys", "values"],
14412                 Iterator: ts.emptyArray,
14413                 AsyncIterator: ts.emptyArray,
14414                 String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
14415                 StringConstructor: ["fromCodePoint", "raw"]
14416             },
14417             es2016: {
14418                 Array: ["includes"]
14419             },
14420             es2017: {
14421                 Atomics: ts.emptyArray,
14422                 SharedArrayBuffer: ts.emptyArray,
14423                 String: ["padStart", "padEnd"],
14424                 ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
14425                 DateTimeFormat: ["formatToParts"]
14426             },
14427             es2018: {
14428                 Promise: ["finally"],
14429                 RegExpMatchArray: ["groups"],
14430                 RegExpExecArray: ["groups"],
14431                 RegExp: ["dotAll"],
14432                 Intl: ["PluralRules"],
14433                 AsyncIterable: ts.emptyArray,
14434                 AsyncIterableIterator: ts.emptyArray,
14435                 AsyncGenerator: ts.emptyArray,
14436                 AsyncGeneratorFunction: ts.emptyArray,
14437             },
14438             es2019: {
14439                 Array: ["flat", "flatMap"],
14440                 ObjectConstructor: ["fromEntries"],
14441                 String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
14442                 Symbol: ["description"]
14443             },
14444             es2020: {
14445                 BigInt: ts.emptyArray,
14446                 BigInt64Array: ts.emptyArray,
14447                 BigUint64Array: ts.emptyArray,
14448                 PromiseConstructor: ["allSettled"],
14449                 SymbolConstructor: ["matchAll"],
14450                 String: ["matchAll"],
14451                 DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
14452                 RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
14453             },
14454             es2021: {
14455                 PromiseConstructor: ["any"],
14456                 String: ["replaceAll"]
14457             },
14458             esnext: {
14459                 NumberFormat: ["formatToParts"]
14460             }
14461         };
14462     }
14463     ts.getScriptTargetFeatures = getScriptTargetFeatures;
14464     var GetLiteralTextFlags;
14465     (function (GetLiteralTextFlags) {
14466         GetLiteralTextFlags[GetLiteralTextFlags["None"] = 0] = "None";
14467         GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
14468         GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
14469         GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
14470         GetLiteralTextFlags[GetLiteralTextFlags["AllowNumericSeparator"] = 8] = "AllowNumericSeparator";
14471     })(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
14472     function getLiteralText(node, sourceFile, flags) {
14473         var _a;
14474         // If we don't need to downlevel and we can reach the original source text using
14475         // the node's parent reference, then simply get the text as it was originally written.
14476         if (canUseOriginalText(node, flags)) {
14477             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
14478         }
14479         // If we can't reach the original source text, use the canonical form if it's a number,
14480         // or a (possibly escaped) quoted form of the original text if it's string-like.
14481         switch (node.kind) {
14482             case 10 /* StringLiteral */: {
14483                 var escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString :
14484                     flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
14485                         escapeNonAsciiString;
14486                 if (node.singleQuote) {
14487                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
14488                 }
14489                 else {
14490                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
14491                 }
14492             }
14493             case 14 /* NoSubstitutionTemplateLiteral */:
14494             case 15 /* TemplateHead */:
14495             case 16 /* TemplateMiddle */:
14496             case 17 /* TemplateTail */: {
14497                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
14498                 // had to include a backslash: `not \${a} substitution`.
14499                 var escapeText = flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
14500                     escapeNonAsciiString;
14501                 var rawText = (_a = node.rawText) !== null && _a !== void 0 ? _a : escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
14502                 switch (node.kind) {
14503                     case 14 /* NoSubstitutionTemplateLiteral */:
14504                         return "`" + rawText + "`";
14505                     case 15 /* TemplateHead */:
14506                         return "`" + rawText + "${";
14507                     case 16 /* TemplateMiddle */:
14508                         return "}" + rawText + "${";
14509                     case 17 /* TemplateTail */:
14510                         return "}" + rawText + "`";
14511                 }
14512                 break;
14513             }
14514             case 8 /* NumericLiteral */:
14515             case 9 /* BigIntLiteral */:
14516                 return node.text;
14517             case 13 /* RegularExpressionLiteral */:
14518                 if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) {
14519                     return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/");
14520                 }
14521                 return node.text;
14522         }
14523         return ts.Debug.fail("Literal kind '".concat(node.kind, "' not accounted for."));
14524     }
14525     ts.getLiteralText = getLiteralText;
14526     function canUseOriginalText(node, flags) {
14527         if (nodeIsSynthesized(node) || !node.parent || (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated)) {
14528             return false;
14529         }
14530         if (ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) {
14531             return !!(flags & 8 /* AllowNumericSeparator */);
14532         }
14533         return !ts.isBigIntLiteral(node);
14534     }
14535     function getTextOfConstantValue(value) {
14536         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
14537     }
14538     ts.getTextOfConstantValue = getTextOfConstantValue;
14539     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
14540     // all non-alphanumeric characters with underscores
14541     function makeIdentifierFromModuleName(moduleName) {
14542         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
14543     }
14544     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
14545     function isBlockOrCatchScoped(declaration) {
14546         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
14547             isCatchClauseVariableDeclarationOrBindingElement(declaration);
14548     }
14549     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
14550     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
14551         var node = getRootDeclaration(declaration);
14552         return node.kind === 253 /* VariableDeclaration */ && node.parent.kind === 291 /* CatchClause */;
14553     }
14554     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
14555     function isAmbientModule(node) {
14556         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
14557     }
14558     ts.isAmbientModule = isAmbientModule;
14559     function isModuleWithStringLiteralName(node) {
14560         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
14561     }
14562     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
14563     function isNonGlobalAmbientModule(node) {
14564         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
14565     }
14566     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
14567     /**
14568      * An effective module (namespace) declaration is either
14569      * 1. An actual declaration: namespace X { ... }
14570      * 2. A Javascript declaration, which is:
14571      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
14572      */
14573     function isEffectiveModuleDeclaration(node) {
14574         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
14575     }
14576     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
14577     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
14578     function isShorthandAmbientModuleSymbol(moduleSymbol) {
14579         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
14580     }
14581     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
14582     function isShorthandAmbientModule(node) {
14583         // The only kind of module that can be missing a body is a shorthand ambient module.
14584         return !!node && node.kind === 260 /* ModuleDeclaration */ && (!node.body);
14585     }
14586     function isBlockScopedContainerTopLevel(node) {
14587         return node.kind === 303 /* SourceFile */ ||
14588             node.kind === 260 /* ModuleDeclaration */ ||
14589             ts.isFunctionLikeOrClassStaticBlockDeclaration(node);
14590     }
14591     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
14592     function isGlobalScopeAugmentation(module) {
14593         return !!(module.flags & 1024 /* GlobalAugmentation */);
14594     }
14595     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
14596     function isExternalModuleAugmentation(node) {
14597         return isAmbientModule(node) && isModuleAugmentationExternal(node);
14598     }
14599     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
14600     function isModuleAugmentationExternal(node) {
14601         // external module augmentation is a ambient module declaration that is either:
14602         // - defined in the top level scope and source file is an external module
14603         // - defined inside ambient module declaration located in the top level scope and source file not an external module
14604         switch (node.parent.kind) {
14605             case 303 /* SourceFile */:
14606                 return ts.isExternalModule(node.parent);
14607             case 261 /* ModuleBlock */:
14608                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
14609         }
14610         return false;
14611     }
14612     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
14613     function getNonAugmentationDeclaration(symbol) {
14614         var _a;
14615         return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
14616     }
14617     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
14618     function isCommonJSContainingModuleKind(kind) {
14619         return kind === ts.ModuleKind.CommonJS || kind === ts.ModuleKind.Node12 || kind === ts.ModuleKind.NodeNext;
14620     }
14621     function isEffectiveExternalModule(node, compilerOptions) {
14622         return ts.isExternalModule(node) || compilerOptions.isolatedModules || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator);
14623     }
14624     ts.isEffectiveExternalModule = isEffectiveExternalModule;
14625     /**
14626      * Returns whether the source file will be treated as if it were in strict mode at runtime.
14627      */
14628     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
14629         // We can only verify strict mode for JS/TS files
14630         switch (node.scriptKind) {
14631             case 1 /* JS */:
14632             case 3 /* TS */:
14633             case 2 /* JSX */:
14634             case 4 /* TSX */:
14635                 break;
14636             default:
14637                 return false;
14638         }
14639         // Strict mode does not matter for declaration files.
14640         if (node.isDeclarationFile) {
14641             return false;
14642         }
14643         // If `alwaysStrict` is set, then treat the file as strict.
14644         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
14645             return true;
14646         }
14647         // Starting with a "use strict" directive indicates the file is strict.
14648         if (ts.startsWithUseStrict(node.statements)) {
14649             return true;
14650         }
14651         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
14652             // ECMAScript Modules are always strict.
14653             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
14654                 return true;
14655             }
14656             // Other modules are strict unless otherwise specified.
14657             return !compilerOptions.noImplicitUseStrict;
14658         }
14659         return false;
14660     }
14661     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
14662     function isBlockScope(node, parentNode) {
14663         switch (node.kind) {
14664             case 303 /* SourceFile */:
14665             case 262 /* CaseBlock */:
14666             case 291 /* CatchClause */:
14667             case 260 /* ModuleDeclaration */:
14668             case 241 /* ForStatement */:
14669             case 242 /* ForInStatement */:
14670             case 243 /* ForOfStatement */:
14671             case 170 /* Constructor */:
14672             case 168 /* MethodDeclaration */:
14673             case 171 /* GetAccessor */:
14674             case 172 /* SetAccessor */:
14675             case 255 /* FunctionDeclaration */:
14676             case 212 /* FunctionExpression */:
14677             case 213 /* ArrowFunction */:
14678             case 166 /* PropertyDeclaration */:
14679             case 169 /* ClassStaticBlockDeclaration */:
14680                 return true;
14681             case 234 /* Block */:
14682                 // function block is not considered block-scope container
14683                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
14684                 return !ts.isFunctionLikeOrClassStaticBlockDeclaration(parentNode);
14685         }
14686         return false;
14687     }
14688     ts.isBlockScope = isBlockScope;
14689     function isDeclarationWithTypeParameters(node) {
14690         switch (node.kind) {
14691             case 336 /* JSDocCallbackTag */:
14692             case 343 /* JSDocTypedefTag */:
14693             case 321 /* JSDocSignature */:
14694                 return true;
14695             default:
14696                 ts.assertType(node);
14697                 return isDeclarationWithTypeParameterChildren(node);
14698         }
14699     }
14700     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
14701     function isDeclarationWithTypeParameterChildren(node) {
14702         switch (node.kind) {
14703             case 173 /* CallSignature */:
14704             case 174 /* ConstructSignature */:
14705             case 167 /* MethodSignature */:
14706             case 175 /* IndexSignature */:
14707             case 178 /* FunctionType */:
14708             case 179 /* ConstructorType */:
14709             case 315 /* JSDocFunctionType */:
14710             case 256 /* ClassDeclaration */:
14711             case 225 /* ClassExpression */:
14712             case 257 /* InterfaceDeclaration */:
14713             case 258 /* TypeAliasDeclaration */:
14714             case 342 /* JSDocTemplateTag */:
14715             case 255 /* FunctionDeclaration */:
14716             case 168 /* MethodDeclaration */:
14717             case 170 /* Constructor */:
14718             case 171 /* GetAccessor */:
14719             case 172 /* SetAccessor */:
14720             case 212 /* FunctionExpression */:
14721             case 213 /* ArrowFunction */:
14722                 return true;
14723             default:
14724                 ts.assertType(node);
14725                 return false;
14726         }
14727     }
14728     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
14729     function isAnyImportSyntax(node) {
14730         switch (node.kind) {
14731             case 265 /* ImportDeclaration */:
14732             case 264 /* ImportEqualsDeclaration */:
14733                 return true;
14734             default:
14735                 return false;
14736         }
14737     }
14738     ts.isAnyImportSyntax = isAnyImportSyntax;
14739     function isLateVisibilityPaintedStatement(node) {
14740         switch (node.kind) {
14741             case 265 /* ImportDeclaration */:
14742             case 264 /* ImportEqualsDeclaration */:
14743             case 236 /* VariableStatement */:
14744             case 256 /* ClassDeclaration */:
14745             case 255 /* FunctionDeclaration */:
14746             case 260 /* ModuleDeclaration */:
14747             case 258 /* TypeAliasDeclaration */:
14748             case 257 /* InterfaceDeclaration */:
14749             case 259 /* EnumDeclaration */:
14750                 return true;
14751             default:
14752                 return false;
14753         }
14754     }
14755     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
14756     function hasPossibleExternalModuleReference(node) {
14757         return isAnyImportOrReExport(node) || ts.isModuleDeclaration(node) || ts.isImportTypeNode(node) || isImportCall(node);
14758     }
14759     ts.hasPossibleExternalModuleReference = hasPossibleExternalModuleReference;
14760     function isAnyImportOrReExport(node) {
14761         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
14762     }
14763     ts.isAnyImportOrReExport = isAnyImportOrReExport;
14764     // Gets the nearest enclosing block scope container that has the provided node
14765     // as a descendant, that is not the provided node.
14766     function getEnclosingBlockScopeContainer(node) {
14767         return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
14768     }
14769     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
14770     function forEachEnclosingBlockScopeContainer(node, cb) {
14771         var container = getEnclosingBlockScopeContainer(node);
14772         while (container) {
14773             cb(container);
14774             container = getEnclosingBlockScopeContainer(container);
14775         }
14776     }
14777     ts.forEachEnclosingBlockScopeContainer = forEachEnclosingBlockScopeContainer;
14778     // Return display name of an identifier
14779     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
14780     // text of the expression in the computed property.
14781     function declarationNameToString(name) {
14782         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
14783     }
14784     ts.declarationNameToString = declarationNameToString;
14785     function getNameFromIndexInfo(info) {
14786         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
14787     }
14788     ts.getNameFromIndexInfo = getNameFromIndexInfo;
14789     function isComputedNonLiteralName(name) {
14790         return name.kind === 161 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
14791     }
14792     ts.isComputedNonLiteralName = isComputedNonLiteralName;
14793     function getTextOfPropertyName(name) {
14794         switch (name.kind) {
14795             case 79 /* Identifier */:
14796             case 80 /* PrivateIdentifier */:
14797                 return name.escapedText;
14798             case 10 /* StringLiteral */:
14799             case 8 /* NumericLiteral */:
14800             case 14 /* NoSubstitutionTemplateLiteral */:
14801                 return ts.escapeLeadingUnderscores(name.text);
14802             case 161 /* ComputedPropertyName */:
14803                 if (isStringOrNumericLiteralLike(name.expression))
14804                     return ts.escapeLeadingUnderscores(name.expression.text);
14805                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
14806             default:
14807                 return ts.Debug.assertNever(name);
14808         }
14809     }
14810     ts.getTextOfPropertyName = getTextOfPropertyName;
14811     function entityNameToString(name) {
14812         switch (name.kind) {
14813             case 108 /* ThisKeyword */:
14814                 return "this";
14815             case 80 /* PrivateIdentifier */:
14816             case 79 /* Identifier */:
14817                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
14818             case 160 /* QualifiedName */:
14819                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
14820             case 205 /* PropertyAccessExpression */:
14821                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
14822                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
14823                 }
14824                 else {
14825                     return ts.Debug.assertNever(name.name);
14826                 }
14827             case 309 /* JSDocMemberName */:
14828                 return entityNameToString(name.left) + entityNameToString(name.right);
14829             default:
14830                 return ts.Debug.assertNever(name);
14831         }
14832     }
14833     ts.entityNameToString = entityNameToString;
14834     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
14835         var sourceFile = getSourceFileOfNode(node);
14836         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
14837     }
14838     ts.createDiagnosticForNode = createDiagnosticForNode;
14839     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
14840         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
14841         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
14842     }
14843     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
14844     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
14845         var span = getErrorSpanForNode(sourceFile, node);
14846         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
14847     }
14848     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
14849     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
14850         var sourceFile = getSourceFileOfNode(node);
14851         var span = getErrorSpanForNode(sourceFile, node);
14852         return createFileDiagnosticFromMessageChain(sourceFile, span.start, span.length, messageChain, relatedInformation);
14853     }
14854     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
14855     function assertDiagnosticLocation(file, start, length) {
14856         ts.Debug.assertGreaterThanOrEqual(start, 0);
14857         ts.Debug.assertGreaterThanOrEqual(length, 0);
14858         if (file) {
14859             ts.Debug.assertLessThanOrEqual(start, file.text.length);
14860             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
14861         }
14862     }
14863     function createFileDiagnosticFromMessageChain(file, start, length, messageChain, relatedInformation) {
14864         assertDiagnosticLocation(file, start, length);
14865         return {
14866             file: file,
14867             start: start,
14868             length: length,
14869             code: messageChain.code,
14870             category: messageChain.category,
14871             messageText: messageChain.next ? messageChain : messageChain.messageText,
14872             relatedInformation: relatedInformation
14873         };
14874     }
14875     ts.createFileDiagnosticFromMessageChain = createFileDiagnosticFromMessageChain;
14876     function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
14877         return {
14878             file: sourceFile,
14879             start: 0,
14880             length: 0,
14881             code: messageChain.code,
14882             category: messageChain.category,
14883             messageText: messageChain.next ? messageChain : messageChain.messageText,
14884             relatedInformation: relatedInformation
14885         };
14886     }
14887     ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain;
14888     function createDiagnosticForRange(sourceFile, range, message) {
14889         return {
14890             file: sourceFile,
14891             start: range.pos,
14892             length: range.end - range.pos,
14893             code: message.code,
14894             category: message.category,
14895             messageText: message.message,
14896         };
14897     }
14898     ts.createDiagnosticForRange = createDiagnosticForRange;
14899     function getSpanOfTokenAtPosition(sourceFile, pos) {
14900         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
14901         scanner.scan();
14902         var start = scanner.getTokenPos();
14903         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
14904     }
14905     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
14906     function getErrorSpanForArrowFunction(sourceFile, node) {
14907         var pos = ts.skipTrivia(sourceFile.text, node.pos);
14908         if (node.body && node.body.kind === 234 /* Block */) {
14909             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
14910             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
14911             if (startLine < endLine) {
14912                 // The arrow function spans multiple lines,
14913                 // make the error span be the first line, inclusive.
14914                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
14915             }
14916         }
14917         return ts.createTextSpanFromBounds(pos, node.end);
14918     }
14919     function getErrorSpanForNode(sourceFile, node) {
14920         var errorNode = node;
14921         switch (node.kind) {
14922             case 303 /* SourceFile */:
14923                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
14924                 if (pos_1 === sourceFile.text.length) {
14925                     // file is empty - return span for the beginning of the file
14926                     return ts.createTextSpan(0, 0);
14927                 }
14928                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
14929             // This list is a work in progress. Add missing node kinds to improve their error
14930             // spans.
14931             case 253 /* VariableDeclaration */:
14932             case 202 /* BindingElement */:
14933             case 256 /* ClassDeclaration */:
14934             case 225 /* ClassExpression */:
14935             case 257 /* InterfaceDeclaration */:
14936             case 260 /* ModuleDeclaration */:
14937             case 259 /* EnumDeclaration */:
14938             case 297 /* EnumMember */:
14939             case 255 /* FunctionDeclaration */:
14940             case 212 /* FunctionExpression */:
14941             case 168 /* MethodDeclaration */:
14942             case 171 /* GetAccessor */:
14943             case 172 /* SetAccessor */:
14944             case 258 /* TypeAliasDeclaration */:
14945             case 166 /* PropertyDeclaration */:
14946             case 165 /* PropertySignature */:
14947             case 267 /* NamespaceImport */:
14948                 errorNode = node.name;
14949                 break;
14950             case 213 /* ArrowFunction */:
14951                 return getErrorSpanForArrowFunction(sourceFile, node);
14952             case 288 /* CaseClause */:
14953             case 289 /* DefaultClause */:
14954                 var start = ts.skipTrivia(sourceFile.text, node.pos);
14955                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
14956                 return ts.createTextSpanFromBounds(start, end);
14957         }
14958         if (errorNode === undefined) {
14959             // If we don't have a better node, then just set the error on the first token of
14960             // construct.
14961             return getSpanOfTokenAtPosition(sourceFile, node.pos);
14962         }
14963         ts.Debug.assert(!ts.isJSDoc(errorNode));
14964         var isMissing = nodeIsMissing(errorNode);
14965         var pos = isMissing || ts.isJsxText(node)
14966             ? errorNode.pos
14967             : ts.skipTrivia(sourceFile.text, errorNode.pos);
14968         // These asserts should all be satisfied for a properly constructed `errorNode`.
14969         if (isMissing) {
14970             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14971             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14972         }
14973         else {
14974             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14975             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14976         }
14977         return ts.createTextSpanFromBounds(pos, errorNode.end);
14978     }
14979     ts.getErrorSpanForNode = getErrorSpanForNode;
14980     function isExternalOrCommonJsModule(file) {
14981         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
14982     }
14983     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
14984     function isJsonSourceFile(file) {
14985         return file.scriptKind === 6 /* JSON */;
14986     }
14987     ts.isJsonSourceFile = isJsonSourceFile;
14988     function isEnumConst(node) {
14989         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
14990     }
14991     ts.isEnumConst = isEnumConst;
14992     function isDeclarationReadonly(declaration) {
14993         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
14994     }
14995     ts.isDeclarationReadonly = isDeclarationReadonly;
14996     function isVarConst(node) {
14997         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
14998     }
14999     ts.isVarConst = isVarConst;
15000     function isLet(node) {
15001         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
15002     }
15003     ts.isLet = isLet;
15004     function isSuperCall(n) {
15005         return n.kind === 207 /* CallExpression */ && n.expression.kind === 106 /* SuperKeyword */;
15006     }
15007     ts.isSuperCall = isSuperCall;
15008     function isImportCall(n) {
15009         return n.kind === 207 /* CallExpression */ && n.expression.kind === 100 /* ImportKeyword */;
15010     }
15011     ts.isImportCall = isImportCall;
15012     function isImportMeta(n) {
15013         return ts.isMetaProperty(n)
15014             && n.keywordToken === 100 /* ImportKeyword */
15015             && n.name.escapedText === "meta";
15016     }
15017     ts.isImportMeta = isImportMeta;
15018     function isLiteralImportTypeNode(n) {
15019         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
15020     }
15021     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
15022     function isPrologueDirective(node) {
15023         return node.kind === 237 /* ExpressionStatement */
15024             && node.expression.kind === 10 /* StringLiteral */;
15025     }
15026     ts.isPrologueDirective = isPrologueDirective;
15027     function isCustomPrologue(node) {
15028         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
15029     }
15030     ts.isCustomPrologue = isCustomPrologue;
15031     function isHoistedFunction(node) {
15032         return isCustomPrologue(node)
15033             && ts.isFunctionDeclaration(node);
15034     }
15035     ts.isHoistedFunction = isHoistedFunction;
15036     function isHoistedVariable(node) {
15037         return ts.isIdentifier(node.name)
15038             && !node.initializer;
15039     }
15040     function isHoistedVariableStatement(node) {
15041         return isCustomPrologue(node)
15042             && ts.isVariableStatement(node)
15043             && ts.every(node.declarationList.declarations, isHoistedVariable);
15044     }
15045     ts.isHoistedVariableStatement = isHoistedVariableStatement;
15046     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
15047         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
15048     }
15049     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
15050     function getJSDocCommentRanges(node, text) {
15051         var commentRanges = (node.kind === 163 /* Parameter */ ||
15052             node.kind === 162 /* TypeParameter */ ||
15053             node.kind === 212 /* FunctionExpression */ ||
15054             node.kind === 213 /* ArrowFunction */ ||
15055             node.kind === 211 /* ParenthesizedExpression */ ||
15056             node.kind === 253 /* VariableDeclaration */) ?
15057             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
15058             ts.getLeadingCommentRanges(text, node.pos);
15059         // True if the comment starts with '/**' but not if it is '/**/'
15060         return ts.filter(commentRanges, function (comment) {
15061             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
15062                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
15063                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
15064         });
15065     }
15066     ts.getJSDocCommentRanges = getJSDocCommentRanges;
15067     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)(('[^']*')|("[^"]*")).*?\/>/;
15068     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)(('[^']*')|("[^"]*")).*?\/>/;
15069     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)(('[^']*')|("[^"]*")).*?\/>/;
15070     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)(('[^']*')|("[^"]*"))\s*\/>/;
15071     function isPartOfTypeNode(node) {
15072         if (176 /* FirstTypeNode */ <= node.kind && node.kind <= 199 /* LastTypeNode */) {
15073             return true;
15074         }
15075         switch (node.kind) {
15076             case 130 /* AnyKeyword */:
15077             case 154 /* UnknownKeyword */:
15078             case 146 /* NumberKeyword */:
15079             case 157 /* BigIntKeyword */:
15080             case 149 /* StringKeyword */:
15081             case 133 /* BooleanKeyword */:
15082             case 150 /* SymbolKeyword */:
15083             case 147 /* ObjectKeyword */:
15084             case 152 /* UndefinedKeyword */:
15085             case 143 /* NeverKeyword */:
15086                 return true;
15087             case 114 /* VoidKeyword */:
15088                 return node.parent.kind !== 216 /* VoidExpression */;
15089             case 227 /* ExpressionWithTypeArguments */:
15090                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
15091             case 162 /* TypeParameter */:
15092                 return node.parent.kind === 194 /* MappedType */ || node.parent.kind === 189 /* InferType */;
15093             // Identifiers and qualified names may be type nodes, depending on their context. Climb
15094             // above them to find the lowest container
15095             case 79 /* Identifier */:
15096                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
15097                 if (node.parent.kind === 160 /* QualifiedName */ && node.parent.right === node) {
15098                     node = node.parent;
15099                 }
15100                 else if (node.parent.kind === 205 /* PropertyAccessExpression */ && node.parent.name === node) {
15101                     node = node.parent;
15102                 }
15103                 // At this point, node is either a qualified name or an identifier
15104                 ts.Debug.assert(node.kind === 79 /* Identifier */ || node.kind === 160 /* QualifiedName */ || node.kind === 205 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
15105             // falls through
15106             case 160 /* QualifiedName */:
15107             case 205 /* PropertyAccessExpression */:
15108             case 108 /* ThisKeyword */: {
15109                 var parent = node.parent;
15110                 if (parent.kind === 180 /* TypeQuery */) {
15111                     return false;
15112                 }
15113                 if (parent.kind === 199 /* ImportType */) {
15114                     return !parent.isTypeOf;
15115                 }
15116                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
15117                 //
15118                 //     let a: A.B.C;
15119                 //
15120                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
15121                 // Only C and A.B.C are type nodes.
15122                 if (176 /* FirstTypeNode */ <= parent.kind && parent.kind <= 199 /* LastTypeNode */) {
15123                     return true;
15124                 }
15125                 switch (parent.kind) {
15126                     case 227 /* ExpressionWithTypeArguments */:
15127                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
15128                     case 162 /* TypeParameter */:
15129                         return node === parent.constraint;
15130                     case 342 /* JSDocTemplateTag */:
15131                         return node === parent.constraint;
15132                     case 166 /* PropertyDeclaration */:
15133                     case 165 /* PropertySignature */:
15134                     case 163 /* Parameter */:
15135                     case 253 /* VariableDeclaration */:
15136                         return node === parent.type;
15137                     case 255 /* FunctionDeclaration */:
15138                     case 212 /* FunctionExpression */:
15139                     case 213 /* ArrowFunction */:
15140                     case 170 /* Constructor */:
15141                     case 168 /* MethodDeclaration */:
15142                     case 167 /* MethodSignature */:
15143                     case 171 /* GetAccessor */:
15144                     case 172 /* SetAccessor */:
15145                         return node === parent.type;
15146                     case 173 /* CallSignature */:
15147                     case 174 /* ConstructSignature */:
15148                     case 175 /* IndexSignature */:
15149                         return node === parent.type;
15150                     case 210 /* TypeAssertionExpression */:
15151                         return node === parent.type;
15152                     case 207 /* CallExpression */:
15153                     case 208 /* NewExpression */:
15154                         return ts.contains(parent.typeArguments, node);
15155                     case 209 /* TaggedTemplateExpression */:
15156                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
15157                         return false;
15158                 }
15159             }
15160         }
15161         return false;
15162     }
15163     ts.isPartOfTypeNode = isPartOfTypeNode;
15164     function isChildOfNodeWithKind(node, kind) {
15165         while (node) {
15166             if (node.kind === kind) {
15167                 return true;
15168             }
15169             node = node.parent;
15170         }
15171         return false;
15172     }
15173     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
15174     // Warning: This has the same semantics as the forEach family of functions,
15175     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
15176     function forEachReturnStatement(body, visitor) {
15177         return traverse(body);
15178         function traverse(node) {
15179             switch (node.kind) {
15180                 case 246 /* ReturnStatement */:
15181                     return visitor(node);
15182                 case 262 /* CaseBlock */:
15183                 case 234 /* Block */:
15184                 case 238 /* IfStatement */:
15185                 case 239 /* DoStatement */:
15186                 case 240 /* WhileStatement */:
15187                 case 241 /* ForStatement */:
15188                 case 242 /* ForInStatement */:
15189                 case 243 /* ForOfStatement */:
15190                 case 247 /* WithStatement */:
15191                 case 248 /* SwitchStatement */:
15192                 case 288 /* CaseClause */:
15193                 case 289 /* DefaultClause */:
15194                 case 249 /* LabeledStatement */:
15195                 case 251 /* TryStatement */:
15196                 case 291 /* CatchClause */:
15197                     return ts.forEachChild(node, traverse);
15198             }
15199         }
15200     }
15201     ts.forEachReturnStatement = forEachReturnStatement;
15202     function forEachYieldExpression(body, visitor) {
15203         return traverse(body);
15204         function traverse(node) {
15205             switch (node.kind) {
15206                 case 223 /* YieldExpression */:
15207                     visitor(node);
15208                     var operand = node.expression;
15209                     if (operand) {
15210                         traverse(operand);
15211                     }
15212                     return;
15213                 case 259 /* EnumDeclaration */:
15214                 case 257 /* InterfaceDeclaration */:
15215                 case 260 /* ModuleDeclaration */:
15216                 case 258 /* TypeAliasDeclaration */:
15217                     // These are not allowed inside a generator now, but eventually they may be allowed
15218                     // as local types. Regardless, skip them to avoid the work.
15219                     return;
15220                 default:
15221                     if (ts.isFunctionLike(node)) {
15222                         if (node.name && node.name.kind === 161 /* ComputedPropertyName */) {
15223                             // Note that we will not include methods/accessors of a class because they would require
15224                             // first descending into the class. This is by design.
15225                             traverse(node.name.expression);
15226                             return;
15227                         }
15228                     }
15229                     else if (!isPartOfTypeNode(node)) {
15230                         // This is the general case, which should include mostly expressions and statements.
15231                         // Also includes NodeArrays.
15232                         ts.forEachChild(node, traverse);
15233                     }
15234             }
15235         }
15236     }
15237     ts.forEachYieldExpression = forEachYieldExpression;
15238     /**
15239      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
15240      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
15241      *
15242      * @param node The type node.
15243      */
15244     function getRestParameterElementType(node) {
15245         if (node && node.kind === 182 /* ArrayType */) {
15246             return node.elementType;
15247         }
15248         else if (node && node.kind === 177 /* TypeReference */) {
15249             return ts.singleOrUndefined(node.typeArguments);
15250         }
15251         else {
15252             return undefined;
15253         }
15254     }
15255     ts.getRestParameterElementType = getRestParameterElementType;
15256     function getMembersOfDeclaration(node) {
15257         switch (node.kind) {
15258             case 257 /* InterfaceDeclaration */:
15259             case 256 /* ClassDeclaration */:
15260             case 225 /* ClassExpression */:
15261             case 181 /* TypeLiteral */:
15262                 return node.members;
15263             case 204 /* ObjectLiteralExpression */:
15264                 return node.properties;
15265         }
15266     }
15267     ts.getMembersOfDeclaration = getMembersOfDeclaration;
15268     function isVariableLike(node) {
15269         if (node) {
15270             switch (node.kind) {
15271                 case 202 /* BindingElement */:
15272                 case 297 /* EnumMember */:
15273                 case 163 /* Parameter */:
15274                 case 294 /* PropertyAssignment */:
15275                 case 166 /* PropertyDeclaration */:
15276                 case 165 /* PropertySignature */:
15277                 case 295 /* ShorthandPropertyAssignment */:
15278                 case 253 /* VariableDeclaration */:
15279                     return true;
15280             }
15281         }
15282         return false;
15283     }
15284     ts.isVariableLike = isVariableLike;
15285     function isVariableLikeOrAccessor(node) {
15286         return isVariableLike(node) || ts.isAccessor(node);
15287     }
15288     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
15289     function isVariableDeclarationInVariableStatement(node) {
15290         return node.parent.kind === 254 /* VariableDeclarationList */
15291             && node.parent.parent.kind === 236 /* VariableStatement */;
15292     }
15293     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
15294     function isValidESSymbolDeclaration(node) {
15295         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
15296             ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
15297                 ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
15298     }
15299     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
15300     function introducesArgumentsExoticObject(node) {
15301         switch (node.kind) {
15302             case 168 /* MethodDeclaration */:
15303             case 167 /* MethodSignature */:
15304             case 170 /* Constructor */:
15305             case 171 /* GetAccessor */:
15306             case 172 /* SetAccessor */:
15307             case 255 /* FunctionDeclaration */:
15308             case 212 /* FunctionExpression */:
15309                 return true;
15310         }
15311         return false;
15312     }
15313     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
15314     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
15315         while (true) {
15316             if (beforeUnwrapLabelCallback) {
15317                 beforeUnwrapLabelCallback(node);
15318             }
15319             if (node.statement.kind !== 249 /* LabeledStatement */) {
15320                 return node.statement;
15321             }
15322             node = node.statement;
15323         }
15324     }
15325     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
15326     function isFunctionBlock(node) {
15327         return node && node.kind === 234 /* Block */ && ts.isFunctionLike(node.parent);
15328     }
15329     ts.isFunctionBlock = isFunctionBlock;
15330     function isObjectLiteralMethod(node) {
15331         return node && node.kind === 168 /* MethodDeclaration */ && node.parent.kind === 204 /* ObjectLiteralExpression */;
15332     }
15333     ts.isObjectLiteralMethod = isObjectLiteralMethod;
15334     function isObjectLiteralOrClassExpressionMethodOrAccessor(node) {
15335         return (node.kind === 168 /* MethodDeclaration */ || node.kind === 171 /* GetAccessor */ || node.kind === 172 /* SetAccessor */) &&
15336             (node.parent.kind === 204 /* ObjectLiteralExpression */ ||
15337                 node.parent.kind === 225 /* ClassExpression */);
15338     }
15339     ts.isObjectLiteralOrClassExpressionMethodOrAccessor = isObjectLiteralOrClassExpressionMethodOrAccessor;
15340     function isIdentifierTypePredicate(predicate) {
15341         return predicate && predicate.kind === 1 /* Identifier */;
15342     }
15343     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
15344     function isThisTypePredicate(predicate) {
15345         return predicate && predicate.kind === 0 /* This */;
15346     }
15347     ts.isThisTypePredicate = isThisTypePredicate;
15348     function getPropertyAssignment(objectLiteral, key, key2) {
15349         return objectLiteral.properties.filter(function (property) {
15350             if (property.kind === 294 /* PropertyAssignment */) {
15351                 var propName = getTextOfPropertyName(property.name);
15352                 return key === propName || (!!key2 && key2 === propName);
15353             }
15354             return false;
15355         });
15356     }
15357     ts.getPropertyAssignment = getPropertyAssignment;
15358     function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) {
15359         return ts.firstDefined(getPropertyAssignment(objectLiteral, propKey), function (property) {
15360             return ts.isArrayLiteralExpression(property.initializer) ?
15361                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
15362                 undefined;
15363         });
15364     }
15365     ts.getPropertyArrayElementValue = getPropertyArrayElementValue;
15366     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
15367         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
15368             var expression = tsConfigSourceFile.statements[0].expression;
15369             return ts.tryCast(expression, ts.isObjectLiteralExpression);
15370         }
15371     }
15372     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
15373     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
15374         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
15375             return ts.isArrayLiteralExpression(property.initializer) ?
15376                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
15377                 undefined;
15378         });
15379     }
15380     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
15381     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
15382         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
15383         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
15384     }
15385     ts.getTsConfigPropArray = getTsConfigPropArray;
15386     function getContainingFunction(node) {
15387         return ts.findAncestor(node.parent, ts.isFunctionLike);
15388     }
15389     ts.getContainingFunction = getContainingFunction;
15390     function getContainingFunctionDeclaration(node) {
15391         return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
15392     }
15393     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
15394     function getContainingClass(node) {
15395         return ts.findAncestor(node.parent, ts.isClassLike);
15396     }
15397     ts.getContainingClass = getContainingClass;
15398     function getContainingClassStaticBlock(node) {
15399         return ts.findAncestor(node.parent, function (n) {
15400             if (ts.isClassLike(n) || ts.isFunctionLike(n)) {
15401                 return "quit";
15402             }
15403             return ts.isClassStaticBlockDeclaration(n);
15404         });
15405     }
15406     ts.getContainingClassStaticBlock = getContainingClassStaticBlock;
15407     function getContainingFunctionOrClassStaticBlock(node) {
15408         return ts.findAncestor(node.parent, ts.isFunctionLikeOrClassStaticBlockDeclaration);
15409     }
15410     ts.getContainingFunctionOrClassStaticBlock = getContainingFunctionOrClassStaticBlock;
15411     function getThisContainer(node, includeArrowFunctions) {
15412         ts.Debug.assert(node.kind !== 303 /* SourceFile */);
15413         while (true) {
15414             node = node.parent;
15415             if (!node) {
15416                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
15417             }
15418             switch (node.kind) {
15419                 case 161 /* ComputedPropertyName */:
15420                     // If the grandparent node is an object literal (as opposed to a class),
15421                     // then the computed property is not a 'this' container.
15422                     // A computed property name in a class needs to be a this container
15423                     // so that we can error on it.
15424                     if (ts.isClassLike(node.parent.parent)) {
15425                         return node;
15426                     }
15427                     // If this is a computed property, then the parent should not
15428                     // make it a this container. The parent might be a property
15429                     // in an object literal, like a method or accessor. But in order for
15430                     // such a parent to be a this container, the reference must be in
15431                     // the *body* of the container.
15432                     node = node.parent;
15433                     break;
15434                 case 164 /* Decorator */:
15435                     // Decorators are always applied outside of the body of a class or method.
15436                     if (node.parent.kind === 163 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
15437                         // If the decorator's parent is a Parameter, we resolve the this container from
15438                         // the grandparent class declaration.
15439                         node = node.parent.parent;
15440                     }
15441                     else if (ts.isClassElement(node.parent)) {
15442                         // If the decorator's parent is a class element, we resolve the 'this' container
15443                         // from the parent class declaration.
15444                         node = node.parent;
15445                     }
15446                     break;
15447                 case 213 /* ArrowFunction */:
15448                     if (!includeArrowFunctions) {
15449                         continue;
15450                     }
15451                 // falls through
15452                 case 255 /* FunctionDeclaration */:
15453                 case 212 /* FunctionExpression */:
15454                 case 260 /* ModuleDeclaration */:
15455                 case 169 /* ClassStaticBlockDeclaration */:
15456                 case 166 /* PropertyDeclaration */:
15457                 case 165 /* PropertySignature */:
15458                 case 168 /* MethodDeclaration */:
15459                 case 167 /* MethodSignature */:
15460                 case 170 /* Constructor */:
15461                 case 171 /* GetAccessor */:
15462                 case 172 /* SetAccessor */:
15463                 case 173 /* CallSignature */:
15464                 case 174 /* ConstructSignature */:
15465                 case 175 /* IndexSignature */:
15466                 case 259 /* EnumDeclaration */:
15467                 case 303 /* SourceFile */:
15468                     return node;
15469             }
15470         }
15471     }
15472     ts.getThisContainer = getThisContainer;
15473     function isInTopLevelContext(node) {
15474         // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
15475         if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
15476             node = node.parent;
15477         }
15478         var container = getThisContainer(node, /*includeArrowFunctions*/ true);
15479         return ts.isSourceFile(container);
15480     }
15481     ts.isInTopLevelContext = isInTopLevelContext;
15482     function getNewTargetContainer(node) {
15483         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
15484         if (container) {
15485             switch (container.kind) {
15486                 case 170 /* Constructor */:
15487                 case 255 /* FunctionDeclaration */:
15488                 case 212 /* FunctionExpression */:
15489                     return container;
15490             }
15491         }
15492         return undefined;
15493     }
15494     ts.getNewTargetContainer = getNewTargetContainer;
15495     /**
15496      * Given an super call/property node, returns the closest node where
15497      * - a super call/property access is legal in the node and not legal in the parent node the node.
15498      *   i.e. super call is legal in constructor but not legal in the class body.
15499      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
15500      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
15501      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
15502      */
15503     function getSuperContainer(node, stopOnFunctions) {
15504         while (true) {
15505             node = node.parent;
15506             if (!node) {
15507                 return node;
15508             }
15509             switch (node.kind) {
15510                 case 161 /* ComputedPropertyName */:
15511                     node = node.parent;
15512                     break;
15513                 case 255 /* FunctionDeclaration */:
15514                 case 212 /* FunctionExpression */:
15515                 case 213 /* ArrowFunction */:
15516                     if (!stopOnFunctions) {
15517                         continue;
15518                     }
15519                 // falls through
15520                 case 166 /* PropertyDeclaration */:
15521                 case 165 /* PropertySignature */:
15522                 case 168 /* MethodDeclaration */:
15523                 case 167 /* MethodSignature */:
15524                 case 170 /* Constructor */:
15525                 case 171 /* GetAccessor */:
15526                 case 172 /* SetAccessor */:
15527                 case 169 /* ClassStaticBlockDeclaration */:
15528                     return node;
15529                 case 164 /* Decorator */:
15530                     // Decorators are always applied outside of the body of a class or method.
15531                     if (node.parent.kind === 163 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
15532                         // If the decorator's parent is a Parameter, we resolve the this container from
15533                         // the grandparent class declaration.
15534                         node = node.parent.parent;
15535                     }
15536                     else if (ts.isClassElement(node.parent)) {
15537                         // If the decorator's parent is a class element, we resolve the 'this' container
15538                         // from the parent class declaration.
15539                         node = node.parent;
15540                     }
15541                     break;
15542             }
15543         }
15544     }
15545     ts.getSuperContainer = getSuperContainer;
15546     function getImmediatelyInvokedFunctionExpression(func) {
15547         if (func.kind === 212 /* FunctionExpression */ || func.kind === 213 /* ArrowFunction */) {
15548             var prev = func;
15549             var parent = func.parent;
15550             while (parent.kind === 211 /* ParenthesizedExpression */) {
15551                 prev = parent;
15552                 parent = parent.parent;
15553             }
15554             if (parent.kind === 207 /* CallExpression */ && parent.expression === prev) {
15555                 return parent;
15556             }
15557         }
15558     }
15559     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
15560     function isSuperOrSuperProperty(node) {
15561         return node.kind === 106 /* SuperKeyword */
15562             || isSuperProperty(node);
15563     }
15564     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
15565     /**
15566      * Determines whether a node is a property or element access expression for `super`.
15567      */
15568     function isSuperProperty(node) {
15569         var kind = node.kind;
15570         return (kind === 205 /* PropertyAccessExpression */ || kind === 206 /* ElementAccessExpression */)
15571             && node.expression.kind === 106 /* SuperKeyword */;
15572     }
15573     ts.isSuperProperty = isSuperProperty;
15574     /**
15575      * Determines whether a node is a property or element access expression for `this`.
15576      */
15577     function isThisProperty(node) {
15578         var kind = node.kind;
15579         return (kind === 205 /* PropertyAccessExpression */ || kind === 206 /* ElementAccessExpression */)
15580             && node.expression.kind === 108 /* ThisKeyword */;
15581     }
15582     ts.isThisProperty = isThisProperty;
15583     function isThisInitializedDeclaration(node) {
15584         var _a;
15585         return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 108 /* ThisKeyword */;
15586     }
15587     ts.isThisInitializedDeclaration = isThisInitializedDeclaration;
15588     function isThisInitializedObjectBindingExpression(node) {
15589         return !!node
15590             && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node))
15591             && ts.isBinaryExpression(node.parent.parent)
15592             && node.parent.parent.operatorToken.kind === 63 /* EqualsToken */
15593             && node.parent.parent.right.kind === 108 /* ThisKeyword */;
15594     }
15595     ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression;
15596     function getEntityNameFromTypeNode(node) {
15597         switch (node.kind) {
15598             case 177 /* TypeReference */:
15599                 return node.typeName;
15600             case 227 /* ExpressionWithTypeArguments */:
15601                 return isEntityNameExpression(node.expression)
15602                     ? node.expression
15603                     : undefined;
15604             // 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.
15605             case 79 /* Identifier */:
15606             case 160 /* QualifiedName */:
15607                 return node;
15608         }
15609         return undefined;
15610     }
15611     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
15612     function getInvokedExpression(node) {
15613         switch (node.kind) {
15614             case 209 /* TaggedTemplateExpression */:
15615                 return node.tag;
15616             case 279 /* JsxOpeningElement */:
15617             case 278 /* JsxSelfClosingElement */:
15618                 return node.tagName;
15619             default:
15620                 return node.expression;
15621         }
15622     }
15623     ts.getInvokedExpression = getInvokedExpression;
15624     function nodeCanBeDecorated(node, parent, grandparent) {
15625         // private names cannot be used with decorators yet
15626         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
15627             return false;
15628         }
15629         switch (node.kind) {
15630             case 256 /* ClassDeclaration */:
15631                 // classes are valid targets
15632                 return true;
15633             case 166 /* PropertyDeclaration */:
15634                 // property declarations are valid if their parent is a class declaration.
15635                 return parent.kind === 256 /* ClassDeclaration */;
15636             case 171 /* GetAccessor */:
15637             case 172 /* SetAccessor */:
15638             case 168 /* MethodDeclaration */:
15639                 // if this method has a body and its parent is a class declaration, this is a valid target.
15640                 return node.body !== undefined
15641                     && parent.kind === 256 /* ClassDeclaration */;
15642             case 163 /* Parameter */:
15643                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
15644                 return parent.body !== undefined
15645                     && (parent.kind === 170 /* Constructor */
15646                         || parent.kind === 168 /* MethodDeclaration */
15647                         || parent.kind === 172 /* SetAccessor */)
15648                     && grandparent.kind === 256 /* ClassDeclaration */;
15649         }
15650         return false;
15651     }
15652     ts.nodeCanBeDecorated = nodeCanBeDecorated;
15653     function nodeIsDecorated(node, parent, grandparent) {
15654         return node.decorators !== undefined
15655             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
15656     }
15657     ts.nodeIsDecorated = nodeIsDecorated;
15658     function nodeOrChildIsDecorated(node, parent, grandparent) {
15659         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
15660     }
15661     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
15662     function childIsDecorated(node, parent) {
15663         switch (node.kind) {
15664             case 256 /* ClassDeclaration */:
15665                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
15666             case 168 /* MethodDeclaration */:
15667             case 172 /* SetAccessor */:
15668             case 170 /* Constructor */:
15669                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
15670             default:
15671                 return false;
15672         }
15673     }
15674     ts.childIsDecorated = childIsDecorated;
15675     function classOrConstructorParameterIsDecorated(node) {
15676         if (nodeIsDecorated(node))
15677             return true;
15678         var constructor = getFirstConstructorWithBody(node);
15679         return !!constructor && childIsDecorated(constructor, node);
15680     }
15681     ts.classOrConstructorParameterIsDecorated = classOrConstructorParameterIsDecorated;
15682     function isJSXTagName(node) {
15683         var parent = node.parent;
15684         if (parent.kind === 279 /* JsxOpeningElement */ ||
15685             parent.kind === 278 /* JsxSelfClosingElement */ ||
15686             parent.kind === 280 /* JsxClosingElement */) {
15687             return parent.tagName === node;
15688         }
15689         return false;
15690     }
15691     ts.isJSXTagName = isJSXTagName;
15692     function isExpressionNode(node) {
15693         switch (node.kind) {
15694             case 106 /* SuperKeyword */:
15695             case 104 /* NullKeyword */:
15696             case 110 /* TrueKeyword */:
15697             case 95 /* FalseKeyword */:
15698             case 13 /* RegularExpressionLiteral */:
15699             case 203 /* ArrayLiteralExpression */:
15700             case 204 /* ObjectLiteralExpression */:
15701             case 205 /* PropertyAccessExpression */:
15702             case 206 /* ElementAccessExpression */:
15703             case 207 /* CallExpression */:
15704             case 208 /* NewExpression */:
15705             case 209 /* TaggedTemplateExpression */:
15706             case 228 /* AsExpression */:
15707             case 210 /* TypeAssertionExpression */:
15708             case 229 /* NonNullExpression */:
15709             case 211 /* ParenthesizedExpression */:
15710             case 212 /* FunctionExpression */:
15711             case 225 /* ClassExpression */:
15712             case 213 /* ArrowFunction */:
15713             case 216 /* VoidExpression */:
15714             case 214 /* DeleteExpression */:
15715             case 215 /* TypeOfExpression */:
15716             case 218 /* PrefixUnaryExpression */:
15717             case 219 /* PostfixUnaryExpression */:
15718             case 220 /* BinaryExpression */:
15719             case 221 /* ConditionalExpression */:
15720             case 224 /* SpreadElement */:
15721             case 222 /* TemplateExpression */:
15722             case 226 /* OmittedExpression */:
15723             case 277 /* JsxElement */:
15724             case 278 /* JsxSelfClosingElement */:
15725             case 281 /* JsxFragment */:
15726             case 223 /* YieldExpression */:
15727             case 217 /* AwaitExpression */:
15728             case 230 /* MetaProperty */:
15729                 return true;
15730             case 160 /* QualifiedName */:
15731                 while (node.parent.kind === 160 /* QualifiedName */) {
15732                     node = node.parent;
15733                 }
15734                 return node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node);
15735             case 309 /* JSDocMemberName */:
15736                 while (ts.isJSDocMemberName(node.parent)) {
15737                     node = node.parent;
15738                 }
15739                 return node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node);
15740             case 80 /* PrivateIdentifier */:
15741                 return ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 101 /* InKeyword */;
15742             case 79 /* Identifier */:
15743                 if (node.parent.kind === 180 /* TypeQuery */ || ts.isJSDocLinkLike(node.parent) || ts.isJSDocNameReference(node.parent) || ts.isJSDocMemberName(node.parent) || isJSXTagName(node)) {
15744                     return true;
15745                 }
15746             // falls through
15747             case 8 /* NumericLiteral */:
15748             case 9 /* BigIntLiteral */:
15749             case 10 /* StringLiteral */:
15750             case 14 /* NoSubstitutionTemplateLiteral */:
15751             case 108 /* ThisKeyword */:
15752                 return isInExpressionContext(node);
15753             default:
15754                 return false;
15755         }
15756     }
15757     ts.isExpressionNode = isExpressionNode;
15758     function isInExpressionContext(node) {
15759         var parent = node.parent;
15760         switch (parent.kind) {
15761             case 253 /* VariableDeclaration */:
15762             case 163 /* Parameter */:
15763             case 166 /* PropertyDeclaration */:
15764             case 165 /* PropertySignature */:
15765             case 297 /* EnumMember */:
15766             case 294 /* PropertyAssignment */:
15767             case 202 /* BindingElement */:
15768                 return parent.initializer === node;
15769             case 237 /* ExpressionStatement */:
15770             case 238 /* IfStatement */:
15771             case 239 /* DoStatement */:
15772             case 240 /* WhileStatement */:
15773             case 246 /* ReturnStatement */:
15774             case 247 /* WithStatement */:
15775             case 248 /* SwitchStatement */:
15776             case 288 /* CaseClause */:
15777             case 250 /* ThrowStatement */:
15778                 return parent.expression === node;
15779             case 241 /* ForStatement */:
15780                 var forStatement = parent;
15781                 return (forStatement.initializer === node && forStatement.initializer.kind !== 254 /* VariableDeclarationList */) ||
15782                     forStatement.condition === node ||
15783                     forStatement.incrementor === node;
15784             case 242 /* ForInStatement */:
15785             case 243 /* ForOfStatement */:
15786                 var forInStatement = parent;
15787                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 254 /* VariableDeclarationList */) ||
15788                     forInStatement.expression === node;
15789             case 210 /* TypeAssertionExpression */:
15790             case 228 /* AsExpression */:
15791                 return node === parent.expression;
15792             case 232 /* TemplateSpan */:
15793                 return node === parent.expression;
15794             case 161 /* ComputedPropertyName */:
15795                 return node === parent.expression;
15796             case 164 /* Decorator */:
15797             case 287 /* JsxExpression */:
15798             case 286 /* JsxSpreadAttribute */:
15799             case 296 /* SpreadAssignment */:
15800                 return true;
15801             case 227 /* ExpressionWithTypeArguments */:
15802                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
15803             case 295 /* ShorthandPropertyAssignment */:
15804                 return parent.objectAssignmentInitializer === node;
15805             default:
15806                 return isExpressionNode(parent);
15807         }
15808     }
15809     ts.isInExpressionContext = isInExpressionContext;
15810     function isPartOfTypeQuery(node) {
15811         while (node.kind === 160 /* QualifiedName */ || node.kind === 79 /* Identifier */) {
15812             node = node.parent;
15813         }
15814         return node.kind === 180 /* TypeQuery */;
15815     }
15816     ts.isPartOfTypeQuery = isPartOfTypeQuery;
15817     function isNamespaceReexportDeclaration(node) {
15818         return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier;
15819     }
15820     ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration;
15821     function isExternalModuleImportEqualsDeclaration(node) {
15822         return node.kind === 264 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 276 /* ExternalModuleReference */;
15823     }
15824     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
15825     function getExternalModuleImportEqualsDeclarationExpression(node) {
15826         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
15827         return node.moduleReference.expression;
15828     }
15829     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
15830     function getExternalModuleRequireArgument(node) {
15831         return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0];
15832     }
15833     ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument;
15834     function isInternalModuleImportEqualsDeclaration(node) {
15835         return node.kind === 264 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 276 /* ExternalModuleReference */;
15836     }
15837     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
15838     function isSourceFileJS(file) {
15839         return isInJSFile(file);
15840     }
15841     ts.isSourceFileJS = isSourceFileJS;
15842     function isSourceFileNotJS(file) {
15843         return !isInJSFile(file);
15844     }
15845     ts.isSourceFileNotJS = isSourceFileNotJS;
15846     function isInJSFile(node) {
15847         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
15848     }
15849     ts.isInJSFile = isInJSFile;
15850     function isInJsonFile(node) {
15851         return !!node && !!(node.flags & 33554432 /* JsonFile */);
15852     }
15853     ts.isInJsonFile = isInJsonFile;
15854     function isSourceFileNotJson(file) {
15855         return !isJsonSourceFile(file);
15856     }
15857     ts.isSourceFileNotJson = isSourceFileNotJson;
15858     function isInJSDoc(node) {
15859         return !!node && !!(node.flags & 4194304 /* JSDoc */);
15860     }
15861     ts.isInJSDoc = isInJSDoc;
15862     function isJSDocIndexSignature(node) {
15863         return ts.isTypeReferenceNode(node) &&
15864             ts.isIdentifier(node.typeName) &&
15865             node.typeName.escapedText === "Object" &&
15866             node.typeArguments && node.typeArguments.length === 2 &&
15867             (node.typeArguments[0].kind === 149 /* StringKeyword */ || node.typeArguments[0].kind === 146 /* NumberKeyword */);
15868     }
15869     ts.isJSDocIndexSignature = isJSDocIndexSignature;
15870     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
15871         if (callExpression.kind !== 207 /* CallExpression */) {
15872             return false;
15873         }
15874         var _a = callExpression, expression = _a.expression, args = _a.arguments;
15875         if (expression.kind !== 79 /* Identifier */ || expression.escapedText !== "require") {
15876             return false;
15877         }
15878         if (args.length !== 1) {
15879             return false;
15880         }
15881         var arg = args[0];
15882         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
15883     }
15884     ts.isRequireCall = isRequireCall;
15885     /**
15886      * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`).
15887      * This function does not test if the node is in a JavaScript file or not.
15888      */
15889     function isRequireVariableDeclaration(node) {
15890         if (node.kind === 202 /* BindingElement */) {
15891             node = node.parent.parent;
15892         }
15893         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true);
15894     }
15895     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
15896     function isRequireVariableStatement(node) {
15897         return ts.isVariableStatement(node)
15898             && node.declarationList.declarations.length > 0
15899             && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); });
15900     }
15901     ts.isRequireVariableStatement = isRequireVariableStatement;
15902     function isSingleOrDoubleQuote(charCode) {
15903         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
15904     }
15905     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
15906     function isStringDoubleQuoted(str, sourceFile) {
15907         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
15908     }
15909     ts.isStringDoubleQuoted = isStringDoubleQuoted;
15910     function isAssignmentDeclaration(decl) {
15911         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
15912     }
15913     ts.isAssignmentDeclaration = isAssignmentDeclaration;
15914     /** Get the initializer, taking into account defaulted Javascript initializers */
15915     function getEffectiveInitializer(node) {
15916         if (isInJSFile(node) && node.initializer &&
15917             ts.isBinaryExpression(node.initializer) &&
15918             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
15919             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
15920             return node.initializer.right;
15921         }
15922         return node.initializer;
15923     }
15924     ts.getEffectiveInitializer = getEffectiveInitializer;
15925     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
15926     function getDeclaredExpandoInitializer(node) {
15927         var init = getEffectiveInitializer(node);
15928         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
15929     }
15930     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
15931     function hasExpandoValueProperty(node, isPrototypeAssignment) {
15932         return ts.forEach(node.properties, function (p) {
15933             return ts.isPropertyAssignment(p) &&
15934                 ts.isIdentifier(p.name) &&
15935                 p.name.escapedText === "value" &&
15936                 p.initializer &&
15937                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
15938         });
15939     }
15940     /**
15941      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
15942      * We treat the right hand side of assignments with container-like initializers as declarations.
15943      */
15944     function getAssignedExpandoInitializer(node) {
15945         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */) {
15946             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
15947             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
15948                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
15949         }
15950         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
15951             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
15952             if (result) {
15953                 return result;
15954             }
15955         }
15956     }
15957     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
15958     /**
15959      * Recognized expando initializers are:
15960      * 1. (function() {})() -- IIFEs
15961      * 2. function() { } -- Function expressions
15962      * 3. class { } -- Class expressions
15963      * 4. {} -- Empty object literals
15964      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
15965      *
15966      * This function returns the provided initializer, or undefined if it is not valid.
15967      */
15968     function getExpandoInitializer(initializer, isPrototypeAssignment) {
15969         if (ts.isCallExpression(initializer)) {
15970             var e = skipParentheses(initializer.expression);
15971             return e.kind === 212 /* FunctionExpression */ || e.kind === 213 /* ArrowFunction */ ? initializer : undefined;
15972         }
15973         if (initializer.kind === 212 /* FunctionExpression */ ||
15974             initializer.kind === 225 /* ClassExpression */ ||
15975             initializer.kind === 213 /* ArrowFunction */) {
15976             return initializer;
15977         }
15978         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
15979             return initializer;
15980         }
15981     }
15982     ts.getExpandoInitializer = getExpandoInitializer;
15983     /**
15984      * A defaulted expando initializer matches the pattern
15985      * `Lhs = Lhs || ExpandoInitializer`
15986      * or `var Lhs = Lhs || ExpandoInitializer`
15987      *
15988      * The second Lhs is required to be the same as the first except that it may be prefixed with
15989      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
15990      */
15991     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
15992         var e = ts.isBinaryExpression(initializer)
15993             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
15994             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
15995         if (e && isSameEntityName(name, initializer.left)) {
15996             return e;
15997         }
15998     }
15999     function isDefaultedExpandoInitializer(node) {
16000         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
16001             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 63 /* EqualsToken */ ? node.parent.left :
16002                 undefined;
16003         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
16004     }
16005     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
16006     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
16007     function getNameOfExpando(node) {
16008         if (ts.isBinaryExpression(node.parent)) {
16009             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
16010             if (parent.operatorToken.kind === 63 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
16011                 return parent.left;
16012             }
16013         }
16014         else if (ts.isVariableDeclaration(node.parent)) {
16015             return node.parent.name;
16016         }
16017     }
16018     ts.getNameOfExpando = getNameOfExpando;
16019     /**
16020      * Is the 'declared' name the same as the one in the initializer?
16021      * @return true for identical entity names, as well as ones where the initializer is prefixed with
16022      * 'window', 'self' or 'global'. For example:
16023      *
16024      * var my = my || {}
16025      * var min = window.min || {}
16026      * my.app = self.my.app || class { }
16027      */
16028     function isSameEntityName(name, initializer) {
16029         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
16030             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
16031         }
16032         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
16033             (initializer.expression.kind === 108 /* ThisKeyword */ ||
16034                 ts.isIdentifier(initializer.expression) &&
16035                     (initializer.expression.escapedText === "window" ||
16036                         initializer.expression.escapedText === "self" ||
16037                         initializer.expression.escapedText === "global"))) {
16038             var nameOrArgument = getNameOrArgument(initializer);
16039             if (ts.isPrivateIdentifier(nameOrArgument)) {
16040                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
16041             }
16042             return isSameEntityName(name, nameOrArgument);
16043         }
16044         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
16045             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
16046                 && isSameEntityName(name.expression, initializer.expression);
16047         }
16048         return false;
16049     }
16050     ts.isSameEntityName = isSameEntityName;
16051     function getRightMostAssignedExpression(node) {
16052         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
16053             node = node.right;
16054         }
16055         return node;
16056     }
16057     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
16058     function isExportsIdentifier(node) {
16059         return ts.isIdentifier(node) && node.escapedText === "exports";
16060     }
16061     ts.isExportsIdentifier = isExportsIdentifier;
16062     function isModuleIdentifier(node) {
16063         return ts.isIdentifier(node) && node.escapedText === "module";
16064     }
16065     ts.isModuleIdentifier = isModuleIdentifier;
16066     function isModuleExportsAccessExpression(node) {
16067         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
16068             && isModuleIdentifier(node.expression)
16069             && getElementOrPropertyAccessName(node) === "exports";
16070     }
16071     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
16072     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
16073     /// assignments we treat as special in the binder
16074     function getAssignmentDeclarationKind(expr) {
16075         var special = getAssignmentDeclarationKindWorker(expr);
16076         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
16077     }
16078     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
16079     function isBindableObjectDefinePropertyCall(expr) {
16080         return ts.length(expr.arguments) === 3 &&
16081             ts.isPropertyAccessExpression(expr.expression) &&
16082             ts.isIdentifier(expr.expression.expression) &&
16083             ts.idText(expr.expression.expression) === "Object" &&
16084             ts.idText(expr.expression.name) === "defineProperty" &&
16085             isStringOrNumericLiteralLike(expr.arguments[1]) &&
16086             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
16087     }
16088     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
16089     /** x.y OR x[0] */
16090     function isLiteralLikeAccess(node) {
16091         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
16092     }
16093     ts.isLiteralLikeAccess = isLiteralLikeAccess;
16094     /** x[0] OR x['a'] OR x[Symbol.y] */
16095     function isLiteralLikeElementAccess(node) {
16096         return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression);
16097     }
16098     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
16099     /** Any series of property and element accesses. */
16100     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
16101         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
16102             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
16103     }
16104     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
16105     /** Any series of property and element accesses, ending in a literal element access */
16106     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
16107         return isLiteralLikeElementAccess(node)
16108             && ((!excludeThisKeyword && node.expression.kind === 108 /* ThisKeyword */) ||
16109                 isEntityNameExpression(node.expression) ||
16110                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
16111     }
16112     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
16113     function isBindableStaticNameExpression(node, excludeThisKeyword) {
16114         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
16115     }
16116     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
16117     function getNameOrArgument(expr) {
16118         if (ts.isPropertyAccessExpression(expr)) {
16119             return expr.name;
16120         }
16121         return expr.argumentExpression;
16122     }
16123     ts.getNameOrArgument = getNameOrArgument;
16124     function getAssignmentDeclarationKindWorker(expr) {
16125         if (ts.isCallExpression(expr)) {
16126             if (!isBindableObjectDefinePropertyCall(expr)) {
16127                 return 0 /* None */;
16128             }
16129             var entityName = expr.arguments[0];
16130             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
16131                 return 8 /* ObjectDefinePropertyExports */;
16132             }
16133             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
16134                 return 9 /* ObjectDefinePrototypeProperty */;
16135             }
16136             return 7 /* ObjectDefinePropertyValue */;
16137         }
16138         if (expr.operatorToken.kind !== 63 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
16139             return 0 /* None */;
16140         }
16141         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
16142             // F.prototype = { ... }
16143             return 6 /* Prototype */;
16144         }
16145         return getAssignmentDeclarationPropertyAccessKind(expr.left);
16146     }
16147     function isVoidZero(node) {
16148         return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
16149     }
16150     /**
16151      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
16152      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
16153      */
16154     /* @internal */
16155     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
16156         if (ts.isPropertyAccessExpression(node)) {
16157             return node.name;
16158         }
16159         var arg = skipParentheses(node.argumentExpression);
16160         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
16161             return arg;
16162         }
16163         return node;
16164     }
16165     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
16166     function getElementOrPropertyAccessName(node) {
16167         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
16168         if (name) {
16169             if (ts.isIdentifier(name)) {
16170                 return name.escapedText;
16171             }
16172             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
16173                 return ts.escapeLeadingUnderscores(name.text);
16174             }
16175         }
16176         return undefined;
16177     }
16178     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
16179     function getAssignmentDeclarationPropertyAccessKind(lhs) {
16180         if (lhs.expression.kind === 108 /* ThisKeyword */) {
16181             return 4 /* ThisProperty */;
16182         }
16183         else if (isModuleExportsAccessExpression(lhs)) {
16184             // module.exports = expr
16185             return 2 /* ModuleExports */;
16186         }
16187         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
16188             if (isPrototypeAccess(lhs.expression)) {
16189                 // F.G....prototype.x = expr
16190                 return 3 /* PrototypeProperty */;
16191             }
16192             var nextToLast = lhs;
16193             while (!ts.isIdentifier(nextToLast.expression)) {
16194                 nextToLast = nextToLast.expression;
16195             }
16196             var id = nextToLast.expression;
16197             if ((id.escapedText === "exports" ||
16198                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
16199                 // ExportsProperty does not support binding with computed names
16200                 isBindableStaticAccessExpression(lhs)) {
16201                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
16202                 return 1 /* ExportsProperty */;
16203             }
16204             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
16205                 // F.G...x = expr
16206                 return 5 /* Property */;
16207             }
16208         }
16209         return 0 /* None */;
16210     }
16211     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
16212     function getInitializerOfBinaryExpression(expr) {
16213         while (ts.isBinaryExpression(expr.right)) {
16214             expr = expr.right;
16215         }
16216         return expr.right;
16217     }
16218     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
16219     function isPrototypePropertyAssignment(node) {
16220         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
16221     }
16222     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
16223     function isSpecialPropertyDeclaration(expr) {
16224         return isInJSFile(expr) &&
16225             expr.parent && expr.parent.kind === 237 /* ExpressionStatement */ &&
16226             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
16227             !!ts.getJSDocTypeTag(expr.parent);
16228     }
16229     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
16230     function setValueDeclaration(symbol, node) {
16231         var valueDeclaration = symbol.valueDeclaration;
16232         if (!valueDeclaration ||
16233             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
16234                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
16235             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
16236             // other kinds of value declarations take precedence over modules and assignment declarations
16237             symbol.valueDeclaration = node;
16238         }
16239     }
16240     ts.setValueDeclaration = setValueDeclaration;
16241     function isFunctionSymbol(symbol) {
16242         if (!symbol || !symbol.valueDeclaration) {
16243             return false;
16244         }
16245         var decl = symbol.valueDeclaration;
16246         return decl.kind === 255 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
16247     }
16248     ts.isFunctionSymbol = isFunctionSymbol;
16249     function tryGetModuleSpecifierFromDeclaration(node) {
16250         var _a, _b, _c;
16251         switch (node.kind) {
16252             case 253 /* VariableDeclaration */:
16253                 return node.initializer.arguments[0].text;
16254             case 265 /* ImportDeclaration */:
16255                 return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text;
16256             case 264 /* ImportEqualsDeclaration */:
16257                 return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text;
16258             default:
16259                 ts.Debug.assertNever(node);
16260         }
16261     }
16262     ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration;
16263     function importFromModuleSpecifier(node) {
16264         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
16265     }
16266     ts.importFromModuleSpecifier = importFromModuleSpecifier;
16267     function tryGetImportFromModuleSpecifier(node) {
16268         switch (node.parent.kind) {
16269             case 265 /* ImportDeclaration */:
16270             case 271 /* ExportDeclaration */:
16271                 return node.parent;
16272             case 276 /* ExternalModuleReference */:
16273                 return node.parent.parent;
16274             case 207 /* CallExpression */:
16275                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
16276             case 195 /* LiteralType */:
16277                 ts.Debug.assert(ts.isStringLiteral(node));
16278                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
16279             default:
16280                 return undefined;
16281         }
16282     }
16283     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
16284     function getExternalModuleName(node) {
16285         switch (node.kind) {
16286             case 265 /* ImportDeclaration */:
16287             case 271 /* ExportDeclaration */:
16288                 return node.moduleSpecifier;
16289             case 264 /* ImportEqualsDeclaration */:
16290                 return node.moduleReference.kind === 276 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
16291             case 199 /* ImportType */:
16292                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
16293             case 207 /* CallExpression */:
16294                 return node.arguments[0];
16295             case 260 /* ModuleDeclaration */:
16296                 return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined;
16297             default:
16298                 return ts.Debug.assertNever(node);
16299         }
16300     }
16301     ts.getExternalModuleName = getExternalModuleName;
16302     function getNamespaceDeclarationNode(node) {
16303         switch (node.kind) {
16304             case 265 /* ImportDeclaration */:
16305                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
16306             case 264 /* ImportEqualsDeclaration */:
16307                 return node;
16308             case 271 /* ExportDeclaration */:
16309                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
16310             default:
16311                 return ts.Debug.assertNever(node);
16312         }
16313     }
16314     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
16315     function isDefaultImport(node) {
16316         return node.kind === 265 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
16317     }
16318     ts.isDefaultImport = isDefaultImport;
16319     function forEachImportClauseDeclaration(node, action) {
16320         if (node.name) {
16321             var result = action(node);
16322             if (result)
16323                 return result;
16324         }
16325         if (node.namedBindings) {
16326             var result = ts.isNamespaceImport(node.namedBindings)
16327                 ? action(node.namedBindings)
16328                 : ts.forEach(node.namedBindings.elements, action);
16329             if (result)
16330                 return result;
16331         }
16332     }
16333     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
16334     function hasQuestionToken(node) {
16335         if (node) {
16336             switch (node.kind) {
16337                 case 163 /* Parameter */:
16338                 case 168 /* MethodDeclaration */:
16339                 case 167 /* MethodSignature */:
16340                 case 295 /* ShorthandPropertyAssignment */:
16341                 case 294 /* PropertyAssignment */:
16342                 case 166 /* PropertyDeclaration */:
16343                 case 165 /* PropertySignature */:
16344                     return node.questionToken !== undefined;
16345             }
16346         }
16347         return false;
16348     }
16349     ts.hasQuestionToken = hasQuestionToken;
16350     function isJSDocConstructSignature(node) {
16351         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
16352         var name = ts.tryCast(param && param.name, ts.isIdentifier);
16353         return !!name && name.escapedText === "new";
16354     }
16355     ts.isJSDocConstructSignature = isJSDocConstructSignature;
16356     function isJSDocTypeAlias(node) {
16357         return node.kind === 343 /* JSDocTypedefTag */ || node.kind === 336 /* JSDocCallbackTag */ || node.kind === 337 /* JSDocEnumTag */;
16358     }
16359     ts.isJSDocTypeAlias = isJSDocTypeAlias;
16360     function isTypeAlias(node) {
16361         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
16362     }
16363     ts.isTypeAlias = isTypeAlias;
16364     function getSourceOfAssignment(node) {
16365         return ts.isExpressionStatement(node) &&
16366             ts.isBinaryExpression(node.expression) &&
16367             node.expression.operatorToken.kind === 63 /* EqualsToken */
16368             ? getRightMostAssignedExpression(node.expression)
16369             : undefined;
16370     }
16371     function getSourceOfDefaultedAssignment(node) {
16372         return ts.isExpressionStatement(node) &&
16373             ts.isBinaryExpression(node.expression) &&
16374             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
16375             ts.isBinaryExpression(node.expression.right) &&
16376             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
16377             ? node.expression.right.right
16378             : undefined;
16379     }
16380     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
16381         switch (node.kind) {
16382             case 236 /* VariableStatement */:
16383                 var v = getSingleVariableOfVariableStatement(node);
16384                 return v && v.initializer;
16385             case 166 /* PropertyDeclaration */:
16386                 return node.initializer;
16387             case 294 /* PropertyAssignment */:
16388                 return node.initializer;
16389         }
16390     }
16391     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
16392     function getSingleVariableOfVariableStatement(node) {
16393         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
16394     }
16395     ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
16396     function getNestedModuleDeclaration(node) {
16397         return ts.isModuleDeclaration(node) &&
16398             node.body &&
16399             node.body.kind === 260 /* ModuleDeclaration */
16400             ? node.body
16401             : undefined;
16402     }
16403     function getJSDocCommentsAndTags(hostNode, noCache) {
16404         var result;
16405         // Pull parameter comments from declaring function as well
16406         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
16407             result = ts.addRange(result, filterOwnedJSDocTags(hostNode, ts.last(hostNode.initializer.jsDoc)));
16408         }
16409         var node = hostNode;
16410         while (node && node.parent) {
16411             if (ts.hasJSDocNodes(node)) {
16412                 result = ts.addRange(result, filterOwnedJSDocTags(hostNode, ts.last(node.jsDoc)));
16413             }
16414             if (node.kind === 163 /* Parameter */) {
16415                 result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
16416                 break;
16417             }
16418             if (node.kind === 162 /* TypeParameter */) {
16419                 result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
16420                 break;
16421             }
16422             node = getNextJSDocCommentLocation(node);
16423         }
16424         return result || ts.emptyArray;
16425     }
16426     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
16427     function filterOwnedJSDocTags(hostNode, jsDoc) {
16428         if (ts.isJSDoc(jsDoc)) {
16429             var ownedTags = ts.filter(jsDoc.tags, function (tag) { return ownsJSDocTag(hostNode, tag); });
16430             return jsDoc.tags === ownedTags ? [jsDoc] : ownedTags;
16431         }
16432         return ownsJSDocTag(hostNode, jsDoc) ? [jsDoc] : undefined;
16433     }
16434     /**
16435      * Determines whether a host node owns a jsDoc tag. A `@type` tag attached to a
16436      * a ParenthesizedExpression belongs only to the ParenthesizedExpression.
16437      */
16438     function ownsJSDocTag(hostNode, tag) {
16439         return !ts.isJSDocTypeTag(tag)
16440             || !tag.parent
16441             || !ts.isJSDoc(tag.parent)
16442             || !ts.isParenthesizedExpression(tag.parent.parent)
16443             || tag.parent.parent === hostNode;
16444     }
16445     function getNextJSDocCommentLocation(node) {
16446         var parent = node.parent;
16447         if (parent.kind === 294 /* PropertyAssignment */ ||
16448             parent.kind === 270 /* ExportAssignment */ ||
16449             parent.kind === 166 /* PropertyDeclaration */ ||
16450             parent.kind === 237 /* ExpressionStatement */ && node.kind === 205 /* PropertyAccessExpression */ ||
16451             parent.kind === 246 /* ReturnStatement */ ||
16452             getNestedModuleDeclaration(parent) ||
16453             ts.isBinaryExpression(node) && node.operatorToken.kind === 63 /* EqualsToken */) {
16454             return parent;
16455         }
16456         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
16457         // /**
16458         //   * @param {number} name
16459         //   * @returns {number}
16460         //   */
16461         // var x = function(name) { return name.length; }
16462         else if (parent.parent &&
16463             (getSingleVariableOfVariableStatement(parent.parent) === node ||
16464                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 63 /* EqualsToken */)) {
16465             return parent.parent;
16466         }
16467         else if (parent.parent && parent.parent.parent &&
16468             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
16469                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
16470                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
16471             return parent.parent.parent;
16472         }
16473     }
16474     ts.getNextJSDocCommentLocation = getNextJSDocCommentLocation;
16475     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
16476     function getParameterSymbolFromJSDoc(node) {
16477         if (node.symbol) {
16478             return node.symbol;
16479         }
16480         if (!ts.isIdentifier(node.name)) {
16481             return undefined;
16482         }
16483         var name = node.name.escapedText;
16484         var decl = getHostSignatureFromJSDoc(node);
16485         if (!decl) {
16486             return undefined;
16487         }
16488         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 79 /* Identifier */ && p.name.escapedText === name; });
16489         return parameter && parameter.symbol;
16490     }
16491     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
16492     function getEffectiveContainerForJSDocTemplateTag(node) {
16493         if (ts.isJSDoc(node.parent) && node.parent.tags) {
16494             // A @template tag belongs to any @typedef, @callback, or @enum tags in the same comment block, if they exist.
16495             var typeAlias = ts.find(node.parent.tags, isJSDocTypeAlias);
16496             if (typeAlias) {
16497                 return typeAlias;
16498             }
16499         }
16500         // otherwise it belongs to the host it annotates
16501         return getHostSignatureFromJSDoc(node);
16502     }
16503     ts.getEffectiveContainerForJSDocTemplateTag = getEffectiveContainerForJSDocTemplateTag;
16504     function getHostSignatureFromJSDoc(node) {
16505         var host = getEffectiveJSDocHost(node);
16506         return host && ts.isFunctionLike(host) ? host : undefined;
16507     }
16508     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
16509     function getEffectiveJSDocHost(node) {
16510         var host = getJSDocHost(node);
16511         if (host) {
16512             return getSourceOfDefaultedAssignment(host)
16513                 || getSourceOfAssignment(host)
16514                 || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host)
16515                 || getSingleVariableOfVariableStatement(host)
16516                 || getNestedModuleDeclaration(host)
16517                 || host;
16518         }
16519     }
16520     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
16521     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
16522     function getJSDocHost(node) {
16523         var jsDoc = getJSDocRoot(node);
16524         if (!jsDoc) {
16525             return undefined;
16526         }
16527         var host = jsDoc.parent;
16528         if (host && host.jsDoc && jsDoc === ts.lastOrUndefined(host.jsDoc)) {
16529             return host;
16530         }
16531     }
16532     ts.getJSDocHost = getJSDocHost;
16533     function getJSDocRoot(node) {
16534         return ts.findAncestor(node.parent, ts.isJSDoc);
16535     }
16536     ts.getJSDocRoot = getJSDocRoot;
16537     function getTypeParameterFromJsDoc(node) {
16538         var name = node.name.escapedText;
16539         var typeParameters = node.parent.parent.parent.typeParameters;
16540         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
16541     }
16542     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
16543     function hasRestParameter(s) {
16544         var last = ts.lastOrUndefined(s.parameters);
16545         return !!last && isRestParameter(last);
16546     }
16547     ts.hasRestParameter = hasRestParameter;
16548     function isRestParameter(node) {
16549         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
16550         return node.dotDotDotToken !== undefined || !!type && type.kind === 316 /* JSDocVariadicType */;
16551     }
16552     ts.isRestParameter = isRestParameter;
16553     function hasTypeArguments(node) {
16554         return !!node.typeArguments;
16555     }
16556     ts.hasTypeArguments = hasTypeArguments;
16557     var AssignmentKind;
16558     (function (AssignmentKind) {
16559         AssignmentKind[AssignmentKind["None"] = 0] = "None";
16560         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
16561         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
16562     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
16563     function getAssignmentTargetKind(node) {
16564         var parent = node.parent;
16565         while (true) {
16566             switch (parent.kind) {
16567                 case 220 /* BinaryExpression */:
16568                     var binaryOperator = parent.operatorToken.kind;
16569                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
16570                         binaryOperator === 63 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
16571                         0 /* None */;
16572                 case 218 /* PrefixUnaryExpression */:
16573                 case 219 /* PostfixUnaryExpression */:
16574                     var unaryOperator = parent.operator;
16575                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
16576                 case 242 /* ForInStatement */:
16577                 case 243 /* ForOfStatement */:
16578                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
16579                 case 211 /* ParenthesizedExpression */:
16580                 case 203 /* ArrayLiteralExpression */:
16581                 case 224 /* SpreadElement */:
16582                 case 229 /* NonNullExpression */:
16583                     node = parent;
16584                     break;
16585                 case 296 /* SpreadAssignment */:
16586                     node = parent.parent;
16587                     break;
16588                 case 295 /* ShorthandPropertyAssignment */:
16589                     if (parent.name !== node) {
16590                         return 0 /* None */;
16591                     }
16592                     node = parent.parent;
16593                     break;
16594                 case 294 /* PropertyAssignment */:
16595                     if (parent.name === node) {
16596                         return 0 /* None */;
16597                     }
16598                     node = parent.parent;
16599                     break;
16600                 default:
16601                     return 0 /* None */;
16602             }
16603             parent = node.parent;
16604         }
16605     }
16606     ts.getAssignmentTargetKind = getAssignmentTargetKind;
16607     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
16608     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
16609     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
16610     // (Note that `p` is not a target in the above examples, only `a`.)
16611     function isAssignmentTarget(node) {
16612         return getAssignmentTargetKind(node) !== 0 /* None */;
16613     }
16614     ts.isAssignmentTarget = isAssignmentTarget;
16615     /**
16616      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
16617      * the same `var` declaration scope as the node's parent.
16618      */
16619     function isNodeWithPossibleHoistedDeclaration(node) {
16620         switch (node.kind) {
16621             case 234 /* Block */:
16622             case 236 /* VariableStatement */:
16623             case 247 /* WithStatement */:
16624             case 238 /* IfStatement */:
16625             case 248 /* SwitchStatement */:
16626             case 262 /* CaseBlock */:
16627             case 288 /* CaseClause */:
16628             case 289 /* DefaultClause */:
16629             case 249 /* LabeledStatement */:
16630             case 241 /* ForStatement */:
16631             case 242 /* ForInStatement */:
16632             case 243 /* ForOfStatement */:
16633             case 239 /* DoStatement */:
16634             case 240 /* WhileStatement */:
16635             case 251 /* TryStatement */:
16636             case 291 /* CatchClause */:
16637                 return true;
16638         }
16639         return false;
16640     }
16641     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
16642     function isValueSignatureDeclaration(node) {
16643         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
16644     }
16645     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
16646     function walkUp(node, kind) {
16647         while (node && node.kind === kind) {
16648             node = node.parent;
16649         }
16650         return node;
16651     }
16652     function walkUpParenthesizedTypes(node) {
16653         return walkUp(node, 190 /* ParenthesizedType */);
16654     }
16655     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
16656     function walkUpParenthesizedExpressions(node) {
16657         return walkUp(node, 211 /* ParenthesizedExpression */);
16658     }
16659     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
16660     /**
16661      * Walks up parenthesized types.
16662      * It returns both the outermost parenthesized type and its parent.
16663      * If given node is not a parenthesiezd type, undefined is return as the former.
16664      */
16665     function walkUpParenthesizedTypesAndGetParentAndChild(node) {
16666         var child;
16667         while (node && node.kind === 190 /* ParenthesizedType */) {
16668             child = node;
16669             node = node.parent;
16670         }
16671         return [child, node];
16672     }
16673     ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild;
16674     function skipParentheses(node, excludeJSDocTypeAssertions) {
16675         var flags = excludeJSDocTypeAssertions ?
16676             1 /* Parentheses */ | 16 /* ExcludeJSDocTypeAssertion */ :
16677             1 /* Parentheses */;
16678         return ts.skipOuterExpressions(node, flags);
16679     }
16680     ts.skipParentheses = skipParentheses;
16681     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
16682     function isDeleteTarget(node) {
16683         if (node.kind !== 205 /* PropertyAccessExpression */ && node.kind !== 206 /* ElementAccessExpression */) {
16684             return false;
16685         }
16686         node = walkUpParenthesizedExpressions(node.parent);
16687         return node && node.kind === 214 /* DeleteExpression */;
16688     }
16689     ts.isDeleteTarget = isDeleteTarget;
16690     function isNodeDescendantOf(node, ancestor) {
16691         while (node) {
16692             if (node === ancestor)
16693                 return true;
16694             node = node.parent;
16695         }
16696         return false;
16697     }
16698     ts.isNodeDescendantOf = isNodeDescendantOf;
16699     // True if `name` is the name of a declaration node
16700     function isDeclarationName(name) {
16701         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
16702     }
16703     ts.isDeclarationName = isDeclarationName;
16704     // See GH#16030
16705     function getDeclarationFromName(name) {
16706         var parent = name.parent;
16707         switch (name.kind) {
16708             case 10 /* StringLiteral */:
16709             case 14 /* NoSubstitutionTemplateLiteral */:
16710             case 8 /* NumericLiteral */:
16711                 if (ts.isComputedPropertyName(parent))
16712                     return parent.parent;
16713             // falls through
16714             case 79 /* Identifier */:
16715                 if (ts.isDeclaration(parent)) {
16716                     return parent.name === name ? parent : undefined;
16717                 }
16718                 else if (ts.isQualifiedName(parent)) {
16719                     var tag = parent.parent;
16720                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
16721                 }
16722                 else {
16723                     var binExp = parent.parent;
16724                     return ts.isBinaryExpression(binExp) &&
16725                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
16726                         (binExp.left.symbol || binExp.symbol) &&
16727                         ts.getNameOfDeclaration(binExp) === name
16728                         ? binExp
16729                         : undefined;
16730                 }
16731             case 80 /* PrivateIdentifier */:
16732                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
16733             default:
16734                 return undefined;
16735         }
16736     }
16737     ts.getDeclarationFromName = getDeclarationFromName;
16738     function isLiteralComputedPropertyDeclarationName(node) {
16739         return isStringOrNumericLiteralLike(node) &&
16740             node.parent.kind === 161 /* ComputedPropertyName */ &&
16741             ts.isDeclaration(node.parent.parent);
16742     }
16743     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
16744     // Return true if the given identifier is classified as an IdentifierName
16745     function isIdentifierName(node) {
16746         var parent = node.parent;
16747         switch (parent.kind) {
16748             case 166 /* PropertyDeclaration */:
16749             case 165 /* PropertySignature */:
16750             case 168 /* MethodDeclaration */:
16751             case 167 /* MethodSignature */:
16752             case 171 /* GetAccessor */:
16753             case 172 /* SetAccessor */:
16754             case 297 /* EnumMember */:
16755             case 294 /* PropertyAssignment */:
16756             case 205 /* PropertyAccessExpression */:
16757                 // Name in member declaration or property name in property access
16758                 return parent.name === node;
16759             case 160 /* QualifiedName */:
16760                 // Name on right hand side of dot in a type query or type reference
16761                 return parent.right === node;
16762             case 202 /* BindingElement */:
16763             case 269 /* ImportSpecifier */:
16764                 // Property name in binding element or import specifier
16765                 return parent.propertyName === node;
16766             case 274 /* ExportSpecifier */:
16767             case 284 /* JsxAttribute */:
16768                 // Any name in an export specifier or JSX Attribute
16769                 return true;
16770         }
16771         return false;
16772     }
16773     ts.isIdentifierName = isIdentifierName;
16774     // An alias symbol is created by one of the following declarations:
16775     // import <symbol> = ...
16776     // import <symbol> from ...
16777     // import * as <symbol> from ...
16778     // import { x as <symbol> } from ...
16779     // export { x as <symbol> } from ...
16780     // export * as ns <symbol> from ...
16781     // export = <EntityNameExpression>
16782     // export default <EntityNameExpression>
16783     // module.exports = <EntityNameExpression>
16784     // {<Identifier>}
16785     // {name: <EntityNameExpression>}
16786     function isAliasSymbolDeclaration(node) {
16787         return node.kind === 264 /* ImportEqualsDeclaration */ ||
16788             node.kind === 263 /* NamespaceExportDeclaration */ ||
16789             node.kind === 266 /* ImportClause */ && !!node.name ||
16790             node.kind === 267 /* NamespaceImport */ ||
16791             node.kind === 273 /* NamespaceExport */ ||
16792             node.kind === 269 /* ImportSpecifier */ ||
16793             node.kind === 274 /* ExportSpecifier */ ||
16794             node.kind === 270 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
16795             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
16796             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
16797             node.kind === 295 /* ShorthandPropertyAssignment */ ||
16798             node.kind === 294 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
16799     }
16800     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
16801     function getAliasDeclarationFromName(node) {
16802         switch (node.parent.kind) {
16803             case 266 /* ImportClause */:
16804             case 269 /* ImportSpecifier */:
16805             case 267 /* NamespaceImport */:
16806             case 274 /* ExportSpecifier */:
16807             case 270 /* ExportAssignment */:
16808             case 264 /* ImportEqualsDeclaration */:
16809                 return node.parent;
16810             case 160 /* QualifiedName */:
16811                 do {
16812                     node = node.parent;
16813                 } while (node.parent.kind === 160 /* QualifiedName */);
16814                 return getAliasDeclarationFromName(node);
16815         }
16816     }
16817     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
16818     function isAliasableExpression(e) {
16819         return isEntityNameExpression(e) || ts.isClassExpression(e);
16820     }
16821     ts.isAliasableExpression = isAliasableExpression;
16822     function exportAssignmentIsAlias(node) {
16823         var e = getExportAssignmentExpression(node);
16824         return isAliasableExpression(e);
16825     }
16826     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
16827     function getExportAssignmentExpression(node) {
16828         return ts.isExportAssignment(node) ? node.expression : node.right;
16829     }
16830     ts.getExportAssignmentExpression = getExportAssignmentExpression;
16831     function getPropertyAssignmentAliasLikeExpression(node) {
16832         return node.kind === 295 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 294 /* PropertyAssignment */ ? node.initializer :
16833             node.parent.right;
16834     }
16835     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
16836     function getEffectiveBaseTypeNode(node) {
16837         var baseType = getClassExtendsHeritageElement(node);
16838         if (baseType && isInJSFile(node)) {
16839             // Prefer an @augments tag because it may have type parameters.
16840             var tag = ts.getJSDocAugmentsTag(node);
16841             if (tag) {
16842                 return tag.class;
16843             }
16844         }
16845         return baseType;
16846     }
16847     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
16848     function getClassExtendsHeritageElement(node) {
16849         var heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */);
16850         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
16851     }
16852     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
16853     function getEffectiveImplementsTypeNodes(node) {
16854         if (isInJSFile(node)) {
16855             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
16856         }
16857         else {
16858             var heritageClause = getHeritageClause(node.heritageClauses, 117 /* ImplementsKeyword */);
16859             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
16860         }
16861     }
16862     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
16863     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
16864     function getAllSuperTypeNodes(node) {
16865         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
16866             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
16867                 ts.emptyArray;
16868     }
16869     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
16870     function getInterfaceBaseTypeNodes(node) {
16871         var heritageClause = getHeritageClause(node.heritageClauses, 94 /* ExtendsKeyword */);
16872         return heritageClause ? heritageClause.types : undefined;
16873     }
16874     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
16875     function getHeritageClause(clauses, kind) {
16876         if (clauses) {
16877             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
16878                 var clause = clauses_1[_i];
16879                 if (clause.token === kind) {
16880                     return clause;
16881                 }
16882             }
16883         }
16884         return undefined;
16885     }
16886     ts.getHeritageClause = getHeritageClause;
16887     function getAncestor(node, kind) {
16888         while (node) {
16889             if (node.kind === kind) {
16890                 return node;
16891             }
16892             node = node.parent;
16893         }
16894         return undefined;
16895     }
16896     ts.getAncestor = getAncestor;
16897     function isKeyword(token) {
16898         return 81 /* FirstKeyword */ <= token && token <= 159 /* LastKeyword */;
16899     }
16900     ts.isKeyword = isKeyword;
16901     function isContextualKeyword(token) {
16902         return 126 /* FirstContextualKeyword */ <= token && token <= 159 /* LastContextualKeyword */;
16903     }
16904     ts.isContextualKeyword = isContextualKeyword;
16905     function isNonContextualKeyword(token) {
16906         return isKeyword(token) && !isContextualKeyword(token);
16907     }
16908     ts.isNonContextualKeyword = isNonContextualKeyword;
16909     function isFutureReservedKeyword(token) {
16910         return 117 /* FirstFutureReservedWord */ <= token && token <= 125 /* LastFutureReservedWord */;
16911     }
16912     ts.isFutureReservedKeyword = isFutureReservedKeyword;
16913     function isStringANonContextualKeyword(name) {
16914         var token = ts.stringToToken(name);
16915         return token !== undefined && isNonContextualKeyword(token);
16916     }
16917     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
16918     function isStringAKeyword(name) {
16919         var token = ts.stringToToken(name);
16920         return token !== undefined && isKeyword(token);
16921     }
16922     ts.isStringAKeyword = isStringAKeyword;
16923     function isIdentifierANonContextualKeyword(_a) {
16924         var originalKeywordKind = _a.originalKeywordKind;
16925         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
16926     }
16927     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
16928     function isTrivia(token) {
16929         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
16930     }
16931     ts.isTrivia = isTrivia;
16932     var FunctionFlags;
16933     (function (FunctionFlags) {
16934         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
16935         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
16936         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
16937         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
16938         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
16939     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
16940     function getFunctionFlags(node) {
16941         if (!node) {
16942             return 4 /* Invalid */;
16943         }
16944         var flags = 0 /* Normal */;
16945         switch (node.kind) {
16946             case 255 /* FunctionDeclaration */:
16947             case 212 /* FunctionExpression */:
16948             case 168 /* MethodDeclaration */:
16949                 if (node.asteriskToken) {
16950                     flags |= 1 /* Generator */;
16951                 }
16952             // falls through
16953             case 213 /* ArrowFunction */:
16954                 if (hasSyntacticModifier(node, 256 /* Async */)) {
16955                     flags |= 2 /* Async */;
16956                 }
16957                 break;
16958         }
16959         if (!node.body) {
16960             flags |= 4 /* Invalid */;
16961         }
16962         return flags;
16963     }
16964     ts.getFunctionFlags = getFunctionFlags;
16965     function isAsyncFunction(node) {
16966         switch (node.kind) {
16967             case 255 /* FunctionDeclaration */:
16968             case 212 /* FunctionExpression */:
16969             case 213 /* ArrowFunction */:
16970             case 168 /* MethodDeclaration */:
16971                 return node.body !== undefined
16972                     && node.asteriskToken === undefined
16973                     && hasSyntacticModifier(node, 256 /* Async */);
16974         }
16975         return false;
16976     }
16977     ts.isAsyncFunction = isAsyncFunction;
16978     function isStringOrNumericLiteralLike(node) {
16979         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
16980     }
16981     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
16982     function isSignedNumericLiteral(node) {
16983         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
16984     }
16985     ts.isSignedNumericLiteral = isSignedNumericLiteral;
16986     /**
16987      * A declaration has a dynamic name if all of the following are true:
16988      *   1. The declaration has a computed property name.
16989      *   2. The computed name is *not* expressed as a StringLiteral.
16990      *   3. The computed name is *not* expressed as a NumericLiteral.
16991      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
16992      *      immediately followed by a NumericLiteral.
16993      */
16994     function hasDynamicName(declaration) {
16995         var name = ts.getNameOfDeclaration(declaration);
16996         return !!name && isDynamicName(name);
16997     }
16998     ts.hasDynamicName = hasDynamicName;
16999     function isDynamicName(name) {
17000         if (!(name.kind === 161 /* ComputedPropertyName */ || name.kind === 206 /* ElementAccessExpression */)) {
17001             return false;
17002         }
17003         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
17004         return !isStringOrNumericLiteralLike(expr) &&
17005             !isSignedNumericLiteral(expr);
17006     }
17007     ts.isDynamicName = isDynamicName;
17008     function getPropertyNameForPropertyNameNode(name) {
17009         switch (name.kind) {
17010             case 79 /* Identifier */:
17011             case 80 /* PrivateIdentifier */:
17012                 return name.escapedText;
17013             case 10 /* StringLiteral */:
17014             case 8 /* NumericLiteral */:
17015                 return ts.escapeLeadingUnderscores(name.text);
17016             case 161 /* ComputedPropertyName */:
17017                 var nameExpression = name.expression;
17018                 if (isStringOrNumericLiteralLike(nameExpression)) {
17019                     return ts.escapeLeadingUnderscores(nameExpression.text);
17020                 }
17021                 else if (isSignedNumericLiteral(nameExpression)) {
17022                     if (nameExpression.operator === 40 /* MinusToken */) {
17023                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
17024                     }
17025                     return nameExpression.operand.text;
17026                 }
17027                 return undefined;
17028             default:
17029                 return ts.Debug.assertNever(name);
17030         }
17031     }
17032     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
17033     function isPropertyNameLiteral(node) {
17034         switch (node.kind) {
17035             case 79 /* Identifier */:
17036             case 10 /* StringLiteral */:
17037             case 14 /* NoSubstitutionTemplateLiteral */:
17038             case 8 /* NumericLiteral */:
17039                 return true;
17040             default:
17041                 return false;
17042         }
17043     }
17044     ts.isPropertyNameLiteral = isPropertyNameLiteral;
17045     function getTextOfIdentifierOrLiteral(node) {
17046         return ts.isMemberName(node) ? ts.idText(node) : node.text;
17047     }
17048     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
17049     function getEscapedTextOfIdentifierOrLiteral(node) {
17050         return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
17051     }
17052     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
17053     function getPropertyNameForUniqueESSymbol(symbol) {
17054         return "__@".concat(ts.getSymbolId(symbol), "@").concat(symbol.escapedName);
17055     }
17056     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
17057     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
17058         return "__#".concat(ts.getSymbolId(containingClassSymbol), "@").concat(description);
17059     }
17060     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
17061     function isKnownSymbol(symbol) {
17062         return ts.startsWith(symbol.escapedName, "__@");
17063     }
17064     ts.isKnownSymbol = isKnownSymbol;
17065     function isPrivateIdentifierSymbol(symbol) {
17066         return ts.startsWith(symbol.escapedName, "__#");
17067     }
17068     ts.isPrivateIdentifierSymbol = isPrivateIdentifierSymbol;
17069     /**
17070      * Includes the word "Symbol" with unicode escapes
17071      */
17072     function isESSymbolIdentifier(node) {
17073         return node.kind === 79 /* Identifier */ && node.escapedText === "Symbol";
17074     }
17075     ts.isESSymbolIdentifier = isESSymbolIdentifier;
17076     function isPushOrUnshiftIdentifier(node) {
17077         return node.escapedText === "push" || node.escapedText === "unshift";
17078     }
17079     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
17080     function isParameterDeclaration(node) {
17081         var root = getRootDeclaration(node);
17082         return root.kind === 163 /* Parameter */;
17083     }
17084     ts.isParameterDeclaration = isParameterDeclaration;
17085     function getRootDeclaration(node) {
17086         while (node.kind === 202 /* BindingElement */) {
17087             node = node.parent.parent;
17088         }
17089         return node;
17090     }
17091     ts.getRootDeclaration = getRootDeclaration;
17092     function nodeStartsNewLexicalEnvironment(node) {
17093         var kind = node.kind;
17094         return kind === 170 /* Constructor */
17095             || kind === 212 /* FunctionExpression */
17096             || kind === 255 /* FunctionDeclaration */
17097             || kind === 213 /* ArrowFunction */
17098             || kind === 168 /* MethodDeclaration */
17099             || kind === 171 /* GetAccessor */
17100             || kind === 172 /* SetAccessor */
17101             || kind === 260 /* ModuleDeclaration */
17102             || kind === 303 /* SourceFile */;
17103     }
17104     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
17105     function nodeIsSynthesized(range) {
17106         return positionIsSynthesized(range.pos)
17107             || positionIsSynthesized(range.end);
17108     }
17109     ts.nodeIsSynthesized = nodeIsSynthesized;
17110     function getOriginalSourceFile(sourceFile) {
17111         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
17112     }
17113     ts.getOriginalSourceFile = getOriginalSourceFile;
17114     var Associativity;
17115     (function (Associativity) {
17116         Associativity[Associativity["Left"] = 0] = "Left";
17117         Associativity[Associativity["Right"] = 1] = "Right";
17118     })(Associativity = ts.Associativity || (ts.Associativity = {}));
17119     function getExpressionAssociativity(expression) {
17120         var operator = getOperator(expression);
17121         var hasArguments = expression.kind === 208 /* NewExpression */ && expression.arguments !== undefined;
17122         return getOperatorAssociativity(expression.kind, operator, hasArguments);
17123     }
17124     ts.getExpressionAssociativity = getExpressionAssociativity;
17125     function getOperatorAssociativity(kind, operator, hasArguments) {
17126         switch (kind) {
17127             case 208 /* NewExpression */:
17128                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
17129             case 218 /* PrefixUnaryExpression */:
17130             case 215 /* TypeOfExpression */:
17131             case 216 /* VoidExpression */:
17132             case 214 /* DeleteExpression */:
17133             case 217 /* AwaitExpression */:
17134             case 221 /* ConditionalExpression */:
17135             case 223 /* YieldExpression */:
17136                 return 1 /* Right */;
17137             case 220 /* BinaryExpression */:
17138                 switch (operator) {
17139                     case 42 /* AsteriskAsteriskToken */:
17140                     case 63 /* EqualsToken */:
17141                     case 64 /* PlusEqualsToken */:
17142                     case 65 /* MinusEqualsToken */:
17143                     case 67 /* AsteriskAsteriskEqualsToken */:
17144                     case 66 /* AsteriskEqualsToken */:
17145                     case 68 /* SlashEqualsToken */:
17146                     case 69 /* PercentEqualsToken */:
17147                     case 70 /* LessThanLessThanEqualsToken */:
17148                     case 71 /* GreaterThanGreaterThanEqualsToken */:
17149                     case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
17150                     case 73 /* AmpersandEqualsToken */:
17151                     case 78 /* CaretEqualsToken */:
17152                     case 74 /* BarEqualsToken */:
17153                     case 75 /* BarBarEqualsToken */:
17154                     case 76 /* AmpersandAmpersandEqualsToken */:
17155                     case 77 /* QuestionQuestionEqualsToken */:
17156                         return 1 /* Right */;
17157                 }
17158         }
17159         return 0 /* Left */;
17160     }
17161     ts.getOperatorAssociativity = getOperatorAssociativity;
17162     function getExpressionPrecedence(expression) {
17163         var operator = getOperator(expression);
17164         var hasArguments = expression.kind === 208 /* NewExpression */ && expression.arguments !== undefined;
17165         return getOperatorPrecedence(expression.kind, operator, hasArguments);
17166     }
17167     ts.getExpressionPrecedence = getExpressionPrecedence;
17168     function getOperator(expression) {
17169         if (expression.kind === 220 /* BinaryExpression */) {
17170             return expression.operatorToken.kind;
17171         }
17172         else if (expression.kind === 218 /* PrefixUnaryExpression */ || expression.kind === 219 /* PostfixUnaryExpression */) {
17173             return expression.operator;
17174         }
17175         else {
17176             return expression.kind;
17177         }
17178     }
17179     ts.getOperator = getOperator;
17180     var OperatorPrecedence;
17181     (function (OperatorPrecedence) {
17182         // Expression:
17183         //     AssignmentExpression
17184         //     Expression `,` AssignmentExpression
17185         OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
17186         // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
17187         // SpreadElement:
17188         //     `...` AssignmentExpression
17189         OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
17190         // AssignmentExpression:
17191         //     ConditionalExpression
17192         //     YieldExpression
17193         //     ArrowFunction
17194         //     AsyncArrowFunction
17195         //     LeftHandSideExpression `=` AssignmentExpression
17196         //     LeftHandSideExpression AssignmentOperator AssignmentExpression
17197         //
17198         // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
17199         //       of the parenthesizer rules.
17200         // AssignmentExpression: YieldExpression
17201         // YieldExpression:
17202         //     `yield`
17203         //     `yield` AssignmentExpression
17204         //     `yield` `*` AssignmentExpression
17205         OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
17206         // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
17207         // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
17208         // AssignmentOperator: one of
17209         //     `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
17210         OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
17211         // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
17212         //       the same precedence.
17213         // AssignmentExpression: ConditionalExpression
17214         // ConditionalExpression:
17215         //     ShortCircuitExpression
17216         //     ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
17217         // ShortCircuitExpression:
17218         //     LogicalORExpression
17219         //     CoalesceExpression
17220         OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
17221         // CoalesceExpression:
17222         //     CoalesceExpressionHead `??` BitwiseORExpression
17223         // CoalesceExpressionHead:
17224         //     CoalesceExpression
17225         //     BitwiseORExpression
17226         OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
17227         // LogicalORExpression:
17228         //     LogicalANDExpression
17229         //     LogicalORExpression `||` LogicalANDExpression
17230         OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
17231         // LogicalANDExpression:
17232         //     BitwiseORExpression
17233         //     LogicalANDExprerssion `&&` BitwiseORExpression
17234         OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
17235         // BitwiseORExpression:
17236         //     BitwiseXORExpression
17237         //     BitwiseORExpression `^` BitwiseXORExpression
17238         OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
17239         // BitwiseXORExpression:
17240         //     BitwiseANDExpression
17241         //     BitwiseXORExpression `^` BitwiseANDExpression
17242         OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
17243         // BitwiseANDExpression:
17244         //     EqualityExpression
17245         //     BitwiseANDExpression `^` EqualityExpression
17246         OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
17247         // EqualityExpression:
17248         //     RelationalExpression
17249         //     EqualityExpression `==` RelationalExpression
17250         //     EqualityExpression `!=` RelationalExpression
17251         //     EqualityExpression `===` RelationalExpression
17252         //     EqualityExpression `!==` RelationalExpression
17253         OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
17254         // RelationalExpression:
17255         //     ShiftExpression
17256         //     RelationalExpression `<` ShiftExpression
17257         //     RelationalExpression `>` ShiftExpression
17258         //     RelationalExpression `<=` ShiftExpression
17259         //     RelationalExpression `>=` ShiftExpression
17260         //     RelationalExpression `instanceof` ShiftExpression
17261         //     RelationalExpression `in` ShiftExpression
17262         //     [+TypeScript] RelationalExpression `as` Type
17263         OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
17264         // ShiftExpression:
17265         //     AdditiveExpression
17266         //     ShiftExpression `<<` AdditiveExpression
17267         //     ShiftExpression `>>` AdditiveExpression
17268         //     ShiftExpression `>>>` AdditiveExpression
17269         OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
17270         // AdditiveExpression:
17271         //     MultiplicativeExpression
17272         //     AdditiveExpression `+` MultiplicativeExpression
17273         //     AdditiveExpression `-` MultiplicativeExpression
17274         OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
17275         // MultiplicativeExpression:
17276         //     ExponentiationExpression
17277         //     MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
17278         // MultiplicativeOperator: one of `*`, `/`, `%`
17279         OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
17280         // ExponentiationExpression:
17281         //     UnaryExpression
17282         //     UpdateExpression `**` ExponentiationExpression
17283         OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
17284         // UnaryExpression:
17285         //     UpdateExpression
17286         //     `delete` UnaryExpression
17287         //     `void` UnaryExpression
17288         //     `typeof` UnaryExpression
17289         //     `+` UnaryExpression
17290         //     `-` UnaryExpression
17291         //     `~` UnaryExpression
17292         //     `!` UnaryExpression
17293         //     AwaitExpression
17294         // UpdateExpression:            // TODO: Do we need to investigate the precedence here?
17295         //     `++` UnaryExpression
17296         //     `--` UnaryExpression
17297         OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
17298         // UpdateExpression:
17299         //     LeftHandSideExpression
17300         //     LeftHandSideExpression `++`
17301         //     LeftHandSideExpression `--`
17302         OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
17303         // LeftHandSideExpression:
17304         //     NewExpression
17305         //     CallExpression
17306         // NewExpression:
17307         //     MemberExpression
17308         //     `new` NewExpression
17309         OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
17310         // CallExpression:
17311         //     CoverCallExpressionAndAsyncArrowHead
17312         //     SuperCall
17313         //     ImportCall
17314         //     CallExpression Arguments
17315         //     CallExpression `[` Expression `]`
17316         //     CallExpression `.` IdentifierName
17317         //     CallExpression TemplateLiteral
17318         // MemberExpression:
17319         //     PrimaryExpression
17320         //     MemberExpression `[` Expression `]`
17321         //     MemberExpression `.` IdentifierName
17322         //     MemberExpression TemplateLiteral
17323         //     SuperProperty
17324         //     MetaProperty
17325         //     `new` MemberExpression Arguments
17326         OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
17327         // TODO: JSXElement?
17328         // PrimaryExpression:
17329         //     `this`
17330         //     IdentifierReference
17331         //     Literal
17332         //     ArrayLiteral
17333         //     ObjectLiteral
17334         //     FunctionExpression
17335         //     ClassExpression
17336         //     GeneratorExpression
17337         //     AsyncFunctionExpression
17338         //     AsyncGeneratorExpression
17339         //     RegularExpressionLiteral
17340         //     TemplateLiteral
17341         //     CoverParenthesizedExpressionAndArrowParameterList
17342         OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
17343         OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
17344         OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
17345         // -1 is lower than all other precedences. Returning it will cause binary expression
17346         // parsing to stop.
17347         OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
17348     })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
17349     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
17350         switch (nodeKind) {
17351             case 349 /* CommaListExpression */:
17352                 return 0 /* Comma */;
17353             case 224 /* SpreadElement */:
17354                 return 1 /* Spread */;
17355             case 223 /* YieldExpression */:
17356                 return 2 /* Yield */;
17357             case 221 /* ConditionalExpression */:
17358                 return 4 /* Conditional */;
17359             case 220 /* BinaryExpression */:
17360                 switch (operatorKind) {
17361                     case 27 /* CommaToken */:
17362                         return 0 /* Comma */;
17363                     case 63 /* EqualsToken */:
17364                     case 64 /* PlusEqualsToken */:
17365                     case 65 /* MinusEqualsToken */:
17366                     case 67 /* AsteriskAsteriskEqualsToken */:
17367                     case 66 /* AsteriskEqualsToken */:
17368                     case 68 /* SlashEqualsToken */:
17369                     case 69 /* PercentEqualsToken */:
17370                     case 70 /* LessThanLessThanEqualsToken */:
17371                     case 71 /* GreaterThanGreaterThanEqualsToken */:
17372                     case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
17373                     case 73 /* AmpersandEqualsToken */:
17374                     case 78 /* CaretEqualsToken */:
17375                     case 74 /* BarEqualsToken */:
17376                     case 75 /* BarBarEqualsToken */:
17377                     case 76 /* AmpersandAmpersandEqualsToken */:
17378                     case 77 /* QuestionQuestionEqualsToken */:
17379                         return 3 /* Assignment */;
17380                     default:
17381                         return getBinaryOperatorPrecedence(operatorKind);
17382                 }
17383             // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
17384             case 210 /* TypeAssertionExpression */:
17385             case 229 /* NonNullExpression */:
17386             case 218 /* PrefixUnaryExpression */:
17387             case 215 /* TypeOfExpression */:
17388             case 216 /* VoidExpression */:
17389             case 214 /* DeleteExpression */:
17390             case 217 /* AwaitExpression */:
17391                 return 16 /* Unary */;
17392             case 219 /* PostfixUnaryExpression */:
17393                 return 17 /* Update */;
17394             case 207 /* CallExpression */:
17395                 return 18 /* LeftHandSide */;
17396             case 208 /* NewExpression */:
17397                 return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
17398             case 209 /* TaggedTemplateExpression */:
17399             case 205 /* PropertyAccessExpression */:
17400             case 206 /* ElementAccessExpression */:
17401             case 230 /* MetaProperty */:
17402                 return 19 /* Member */;
17403             case 228 /* AsExpression */:
17404                 return 11 /* Relational */;
17405             case 108 /* ThisKeyword */:
17406             case 106 /* SuperKeyword */:
17407             case 79 /* Identifier */:
17408             case 80 /* PrivateIdentifier */:
17409             case 104 /* NullKeyword */:
17410             case 110 /* TrueKeyword */:
17411             case 95 /* FalseKeyword */:
17412             case 8 /* NumericLiteral */:
17413             case 9 /* BigIntLiteral */:
17414             case 10 /* StringLiteral */:
17415             case 203 /* ArrayLiteralExpression */:
17416             case 204 /* ObjectLiteralExpression */:
17417             case 212 /* FunctionExpression */:
17418             case 213 /* ArrowFunction */:
17419             case 225 /* ClassExpression */:
17420             case 13 /* RegularExpressionLiteral */:
17421             case 14 /* NoSubstitutionTemplateLiteral */:
17422             case 222 /* TemplateExpression */:
17423             case 211 /* ParenthesizedExpression */:
17424             case 226 /* OmittedExpression */:
17425             case 277 /* JsxElement */:
17426             case 278 /* JsxSelfClosingElement */:
17427             case 281 /* JsxFragment */:
17428                 return 20 /* Primary */;
17429             default:
17430                 return -1 /* Invalid */;
17431         }
17432     }
17433     ts.getOperatorPrecedence = getOperatorPrecedence;
17434     function getBinaryOperatorPrecedence(kind) {
17435         switch (kind) {
17436             case 60 /* QuestionQuestionToken */:
17437                 return 4 /* Coalesce */;
17438             case 56 /* BarBarToken */:
17439                 return 5 /* LogicalOR */;
17440             case 55 /* AmpersandAmpersandToken */:
17441                 return 6 /* LogicalAND */;
17442             case 51 /* BarToken */:
17443                 return 7 /* BitwiseOR */;
17444             case 52 /* CaretToken */:
17445                 return 8 /* BitwiseXOR */;
17446             case 50 /* AmpersandToken */:
17447                 return 9 /* BitwiseAND */;
17448             case 34 /* EqualsEqualsToken */:
17449             case 35 /* ExclamationEqualsToken */:
17450             case 36 /* EqualsEqualsEqualsToken */:
17451             case 37 /* ExclamationEqualsEqualsToken */:
17452                 return 10 /* Equality */;
17453             case 29 /* LessThanToken */:
17454             case 31 /* GreaterThanToken */:
17455             case 32 /* LessThanEqualsToken */:
17456             case 33 /* GreaterThanEqualsToken */:
17457             case 102 /* InstanceOfKeyword */:
17458             case 101 /* InKeyword */:
17459             case 127 /* AsKeyword */:
17460                 return 11 /* Relational */;
17461             case 47 /* LessThanLessThanToken */:
17462             case 48 /* GreaterThanGreaterThanToken */:
17463             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
17464                 return 12 /* Shift */;
17465             case 39 /* PlusToken */:
17466             case 40 /* MinusToken */:
17467                 return 13 /* Additive */;
17468             case 41 /* AsteriskToken */:
17469             case 43 /* SlashToken */:
17470             case 44 /* PercentToken */:
17471                 return 14 /* Multiplicative */;
17472             case 42 /* AsteriskAsteriskToken */:
17473                 return 15 /* Exponentiation */;
17474         }
17475         // -1 is lower than all other precedences.  Returning it will cause binary expression
17476         // parsing to stop.
17477         return -1;
17478     }
17479     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
17480     function getSemanticJsxChildren(children) {
17481         return ts.filter(children, function (i) {
17482             switch (i.kind) {
17483                 case 287 /* JsxExpression */:
17484                     return !!i.expression;
17485                 case 11 /* JsxText */:
17486                     return !i.containsOnlyTriviaWhiteSpaces;
17487                 default:
17488                     return true;
17489             }
17490         });
17491     }
17492     ts.getSemanticJsxChildren = getSemanticJsxChildren;
17493     function createDiagnosticCollection() {
17494         var nonFileDiagnostics = []; // See GH#19873
17495         var filesWithDiagnostics = [];
17496         var fileDiagnostics = new ts.Map();
17497         var hasReadNonFileDiagnostics = false;
17498         return {
17499             add: add,
17500             lookup: lookup,
17501             getGlobalDiagnostics: getGlobalDiagnostics,
17502             getDiagnostics: getDiagnostics,
17503         };
17504         function lookup(diagnostic) {
17505             var diagnostics;
17506             if (diagnostic.file) {
17507                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
17508             }
17509             else {
17510                 diagnostics = nonFileDiagnostics;
17511             }
17512             if (!diagnostics) {
17513                 return undefined;
17514             }
17515             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
17516             if (result >= 0) {
17517                 return diagnostics[result];
17518             }
17519             return undefined;
17520         }
17521         function add(diagnostic) {
17522             var diagnostics;
17523             if (diagnostic.file) {
17524                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
17525                 if (!diagnostics) {
17526                     diagnostics = []; // See GH#19873
17527                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
17528                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
17529                 }
17530             }
17531             else {
17532                 // If we've already read the non-file diagnostics, do not modify the existing array.
17533                 if (hasReadNonFileDiagnostics) {
17534                     hasReadNonFileDiagnostics = false;
17535                     nonFileDiagnostics = nonFileDiagnostics.slice();
17536                 }
17537                 diagnostics = nonFileDiagnostics;
17538             }
17539             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
17540         }
17541         function getGlobalDiagnostics() {
17542             hasReadNonFileDiagnostics = true;
17543             return nonFileDiagnostics;
17544         }
17545         function getDiagnostics(fileName) {
17546             if (fileName) {
17547                 return fileDiagnostics.get(fileName) || [];
17548             }
17549             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
17550             if (!nonFileDiagnostics.length) {
17551                 return fileDiags;
17552             }
17553             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
17554             return fileDiags;
17555         }
17556     }
17557     ts.createDiagnosticCollection = createDiagnosticCollection;
17558     var templateSubstitutionRegExp = /\$\{/g;
17559     function escapeTemplateSubstitution(str) {
17560         return str.replace(templateSubstitutionRegExp, "\\${");
17561     }
17562     /** @internal */
17563     function hasInvalidEscape(template) {
17564         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
17565             ? template.templateFlags
17566             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
17567     }
17568     ts.hasInvalidEscape = hasInvalidEscape;
17569     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
17570     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
17571     // the language service. These characters should be escaped when printing, and if any characters are added,
17572     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
17573     // There is no reason for this other than that JSON.stringify does not handle it either.
17574     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
17575     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
17576     // Template strings preserve simple LF newlines, still encode CRLF (or CR)
17577     var backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g;
17578     var escapedCharsMap = new ts.Map(ts.getEntries({
17579         "\t": "\\t",
17580         "\v": "\\v",
17581         "\f": "\\f",
17582         "\b": "\\b",
17583         "\r": "\\r",
17584         "\n": "\\n",
17585         "\\": "\\\\",
17586         "\"": "\\\"",
17587         "\'": "\\\'",
17588         "\`": "\\\`",
17589         "\u2028": "\\u2028",
17590         "\u2029": "\\u2029",
17591         "\u0085": "\\u0085",
17592         "\r\n": "\\r\\n", // special case for CRLFs in backticks
17593     }));
17594     function encodeUtf16EscapeSequence(charCode) {
17595         var hexCharCode = charCode.toString(16).toUpperCase();
17596         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
17597         return "\\u" + paddedHexCode;
17598     }
17599     function getReplacement(c, offset, input) {
17600         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
17601             var lookAhead = input.charCodeAt(offset + c.length);
17602             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
17603                 // 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)
17604                 return "\\x00";
17605             }
17606             // Otherwise, keep printing a literal \0 for the null character
17607             return "\\0";
17608         }
17609         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
17610     }
17611     /**
17612      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
17613      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
17614      * Note that this doesn't actually wrap the input in double quotes.
17615      */
17616     function escapeString(s, quoteChar) {
17617         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
17618             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
17619                 doubleQuoteEscapedCharsRegExp;
17620         return s.replace(escapedCharsRegExp, getReplacement);
17621     }
17622     ts.escapeString = escapeString;
17623     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
17624     function escapeNonAsciiString(s, quoteChar) {
17625         s = escapeString(s, quoteChar);
17626         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
17627         // Otherwise just return the original string.
17628         return nonAsciiCharacters.test(s) ?
17629             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
17630             s;
17631     }
17632     ts.escapeNonAsciiString = escapeNonAsciiString;
17633     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
17634     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
17635     // the language service. These characters should be escaped when printing, and if any characters are added,
17636     // the map below must be updated.
17637     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
17638     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
17639     var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
17640         "\"": "&quot;",
17641         "\'": "&apos;"
17642     }));
17643     function encodeJsxCharacterEntity(charCode) {
17644         var hexCharCode = charCode.toString(16).toUpperCase();
17645         return "&#x" + hexCharCode + ";";
17646     }
17647     function getJsxAttributeStringReplacement(c) {
17648         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
17649             return "&#0;";
17650         }
17651         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
17652     }
17653     function escapeJsxAttributeString(s, quoteChar) {
17654         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
17655             jsxDoubleQuoteEscapedCharsRegExp;
17656         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
17657     }
17658     ts.escapeJsxAttributeString = escapeJsxAttributeString;
17659     /**
17660      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
17661      *
17662      * @return non-quoted string
17663      */
17664     function stripQuotes(name) {
17665         var length = name.length;
17666         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
17667             return name.substring(1, length - 1);
17668         }
17669         return name;
17670     }
17671     ts.stripQuotes = stripQuotes;
17672     function isQuoteOrBacktick(charCode) {
17673         return charCode === 39 /* singleQuote */ ||
17674             charCode === 34 /* doubleQuote */ ||
17675             charCode === 96 /* backtick */;
17676     }
17677     function isIntrinsicJsxName(name) {
17678         var ch = name.charCodeAt(0);
17679         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-") || ts.stringContains(name, ":");
17680     }
17681     ts.isIntrinsicJsxName = isIntrinsicJsxName;
17682     var indentStrings = ["", "    "];
17683     function getIndentString(level) {
17684         // prepopulate cache
17685         var singleLevel = indentStrings[1];
17686         for (var current = indentStrings.length; current <= level; current++) {
17687             indentStrings.push(indentStrings[current - 1] + singleLevel);
17688         }
17689         return indentStrings[level];
17690     }
17691     ts.getIndentString = getIndentString;
17692     function getIndentSize() {
17693         return indentStrings[1].length;
17694     }
17695     ts.getIndentSize = getIndentSize;
17696     function createTextWriter(newLine) {
17697         var output;
17698         var indent;
17699         var lineStart;
17700         var lineCount;
17701         var linePos;
17702         var hasTrailingComment = false;
17703         function updateLineCountAndPosFor(s) {
17704             var lineStartsOfS = ts.computeLineStarts(s);
17705             if (lineStartsOfS.length > 1) {
17706                 lineCount = lineCount + lineStartsOfS.length - 1;
17707                 linePos = output.length - s.length + ts.last(lineStartsOfS);
17708                 lineStart = (linePos - output.length) === 0;
17709             }
17710             else {
17711                 lineStart = false;
17712             }
17713         }
17714         function writeText(s) {
17715             if (s && s.length) {
17716                 if (lineStart) {
17717                     s = getIndentString(indent) + s;
17718                     lineStart = false;
17719                 }
17720                 output += s;
17721                 updateLineCountAndPosFor(s);
17722             }
17723         }
17724         function write(s) {
17725             if (s)
17726                 hasTrailingComment = false;
17727             writeText(s);
17728         }
17729         function writeComment(s) {
17730             if (s)
17731                 hasTrailingComment = true;
17732             writeText(s);
17733         }
17734         function reset() {
17735             output = "";
17736             indent = 0;
17737             lineStart = true;
17738             lineCount = 0;
17739             linePos = 0;
17740             hasTrailingComment = false;
17741         }
17742         function rawWrite(s) {
17743             if (s !== undefined) {
17744                 output += s;
17745                 updateLineCountAndPosFor(s);
17746                 hasTrailingComment = false;
17747             }
17748         }
17749         function writeLiteral(s) {
17750             if (s && s.length) {
17751                 write(s);
17752             }
17753         }
17754         function writeLine(force) {
17755             if (!lineStart || force) {
17756                 output += newLine;
17757                 lineCount++;
17758                 linePos = output.length;
17759                 lineStart = true;
17760                 hasTrailingComment = false;
17761             }
17762         }
17763         function getTextPosWithWriteLine() {
17764             return lineStart ? output.length : (output.length + newLine.length);
17765         }
17766         reset();
17767         return {
17768             write: write,
17769             rawWrite: rawWrite,
17770             writeLiteral: writeLiteral,
17771             writeLine: writeLine,
17772             increaseIndent: function () { indent++; },
17773             decreaseIndent: function () { indent--; },
17774             getIndent: function () { return indent; },
17775             getTextPos: function () { return output.length; },
17776             getLine: function () { return lineCount; },
17777             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
17778             getText: function () { return output; },
17779             isAtStartOfLine: function () { return lineStart; },
17780             hasTrailingComment: function () { return hasTrailingComment; },
17781             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
17782             clear: reset,
17783             reportInaccessibleThisError: ts.noop,
17784             reportPrivateInBaseOfClassExpression: ts.noop,
17785             reportInaccessibleUniqueSymbolError: ts.noop,
17786             trackSymbol: function () { return false; },
17787             writeKeyword: write,
17788             writeOperator: write,
17789             writeParameter: write,
17790             writeProperty: write,
17791             writePunctuation: write,
17792             writeSpace: write,
17793             writeStringLiteral: write,
17794             writeSymbol: function (s, _) { return write(s); },
17795             writeTrailingSemicolon: write,
17796             writeComment: writeComment,
17797             getTextPosWithWriteLine: getTextPosWithWriteLine
17798         };
17799     }
17800     ts.createTextWriter = createTextWriter;
17801     function getTrailingSemicolonDeferringWriter(writer) {
17802         var pendingTrailingSemicolon = false;
17803         function commitPendingTrailingSemicolon() {
17804             if (pendingTrailingSemicolon) {
17805                 writer.writeTrailingSemicolon(";");
17806                 pendingTrailingSemicolon = false;
17807             }
17808         }
17809         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
17810                 pendingTrailingSemicolon = true;
17811             }, writeLiteral: function (s) {
17812                 commitPendingTrailingSemicolon();
17813                 writer.writeLiteral(s);
17814             }, writeStringLiteral: function (s) {
17815                 commitPendingTrailingSemicolon();
17816                 writer.writeStringLiteral(s);
17817             }, writeSymbol: function (s, sym) {
17818                 commitPendingTrailingSemicolon();
17819                 writer.writeSymbol(s, sym);
17820             }, writePunctuation: function (s) {
17821                 commitPendingTrailingSemicolon();
17822                 writer.writePunctuation(s);
17823             }, writeKeyword: function (s) {
17824                 commitPendingTrailingSemicolon();
17825                 writer.writeKeyword(s);
17826             }, writeOperator: function (s) {
17827                 commitPendingTrailingSemicolon();
17828                 writer.writeOperator(s);
17829             }, writeParameter: function (s) {
17830                 commitPendingTrailingSemicolon();
17831                 writer.writeParameter(s);
17832             }, writeSpace: function (s) {
17833                 commitPendingTrailingSemicolon();
17834                 writer.writeSpace(s);
17835             }, writeProperty: function (s) {
17836                 commitPendingTrailingSemicolon();
17837                 writer.writeProperty(s);
17838             }, writeComment: function (s) {
17839                 commitPendingTrailingSemicolon();
17840                 writer.writeComment(s);
17841             }, writeLine: function () {
17842                 commitPendingTrailingSemicolon();
17843                 writer.writeLine();
17844             }, increaseIndent: function () {
17845                 commitPendingTrailingSemicolon();
17846                 writer.increaseIndent();
17847             }, decreaseIndent: function () {
17848                 commitPendingTrailingSemicolon();
17849                 writer.decreaseIndent();
17850             } });
17851     }
17852     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
17853     function hostUsesCaseSensitiveFileNames(host) {
17854         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
17855     }
17856     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
17857     function hostGetCanonicalFileName(host) {
17858         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
17859     }
17860     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
17861     function getResolvedExternalModuleName(host, file, referenceFile) {
17862         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
17863     }
17864     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
17865     function getCanonicalAbsolutePath(host, path) {
17866         return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory()));
17867     }
17868     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
17869         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
17870         if (!file || file.isDeclarationFile) {
17871             return undefined;
17872         }
17873         // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it
17874         var specifier = getExternalModuleName(declaration);
17875         if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) &&
17876             getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) {
17877             return undefined;
17878         }
17879         return getResolvedExternalModuleName(host, file);
17880     }
17881     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
17882     /**
17883      * Resolves a local path to a path which is absolute to the base of the emit
17884      */
17885     function getExternalModuleNameFromPath(host, fileName, referencePath) {
17886         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
17887         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
17888         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
17889         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
17890         var extensionless = removeFileExtension(relativePath);
17891         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
17892     }
17893     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
17894     function getOwnEmitOutputFilePath(fileName, host, extension) {
17895         var compilerOptions = host.getCompilerOptions();
17896         var emitOutputFilePathWithoutExtension;
17897         if (compilerOptions.outDir) {
17898             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
17899         }
17900         else {
17901             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
17902         }
17903         return emitOutputFilePathWithoutExtension + extension;
17904     }
17905     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
17906     function getDeclarationEmitOutputFilePath(fileName, host) {
17907         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17908     }
17909     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
17910     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17911         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
17912         var path = outputDir
17913             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
17914             : fileName;
17915         var declarationExtension = getDeclarationEmitExtensionForPath(path);
17916         return removeFileExtension(path) + declarationExtension;
17917     }
17918     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
17919     function getDeclarationEmitExtensionForPath(path) {
17920         return ts.fileExtensionIsOneOf(path, [".mjs" /* Mjs */, ".mts" /* Mts */]) ? ".d.mts" /* Dmts */ :
17921             ts.fileExtensionIsOneOf(path, [".cjs" /* Cjs */, ".cts" /* Cts */]) ? ".d.cts" /* Dcts */ :
17922                 ts.fileExtensionIsOneOf(path, [".json" /* Json */]) ? ".json.d.ts" : // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well
17923                     ".d.ts" /* Dts */;
17924     }
17925     ts.getDeclarationEmitExtensionForPath = getDeclarationEmitExtensionForPath;
17926     function outFile(options) {
17927         return options.outFile || options.out;
17928     }
17929     ts.outFile = outFile;
17930     /** Returns 'undefined' if and only if 'options.paths' is undefined. */
17931     function getPathsBasePath(options, host) {
17932         var _a, _b;
17933         if (!options.paths)
17934             return undefined;
17935         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'.");
17936     }
17937     ts.getPathsBasePath = getPathsBasePath;
17938     /**
17939      * Gets the source files that are expected to have an emit output.
17940      *
17941      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
17942      * transformations.
17943      *
17944      * @param host An EmitHost.
17945      * @param targetSourceFile An optional target source file to emit.
17946      */
17947     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
17948         var options = host.getCompilerOptions();
17949         if (outFile(options)) {
17950             var moduleKind = getEmitModuleKind(options);
17951             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
17952             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
17953             return ts.filter(host.getSourceFiles(), function (sourceFile) {
17954                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
17955                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
17956             });
17957         }
17958         else {
17959             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
17960             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
17961         }
17962     }
17963     ts.getSourceFilesToEmit = getSourceFilesToEmit;
17964     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
17965     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
17966         var options = host.getCompilerOptions();
17967         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
17968             !sourceFile.isDeclarationFile &&
17969             !host.isSourceFileFromExternalLibrary(sourceFile) &&
17970             (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
17971                 !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)));
17972     }
17973     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
17974     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
17975         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17976     }
17977     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
17978     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17979         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
17980         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
17981         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
17982         return ts.combinePaths(newDirPath, sourceFilePath);
17983     }
17984     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
17985     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
17986         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
17987             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
17988         }, sourceFiles);
17989     }
17990     ts.writeFile = writeFile;
17991     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
17992         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
17993             var parentDirectory = ts.getDirectoryPath(directoryPath);
17994             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
17995             createDirectory(directoryPath);
17996         }
17997     }
17998     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
17999         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
18000         // and fall back to creating it if the file write fails.
18001         try {
18002             writeFile(path, data, writeByteOrderMark);
18003         }
18004         catch (_a) {
18005             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
18006             writeFile(path, data, writeByteOrderMark);
18007         }
18008     }
18009     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
18010     function getLineOfLocalPosition(sourceFile, pos) {
18011         var lineStarts = ts.getLineStarts(sourceFile);
18012         return ts.computeLineOfPosition(lineStarts, pos);
18013     }
18014     ts.getLineOfLocalPosition = getLineOfLocalPosition;
18015     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
18016         return ts.computeLineOfPosition(lineMap, pos);
18017     }
18018     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
18019     function getFirstConstructorWithBody(node) {
18020         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
18021     }
18022     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
18023     function getSetAccessorValueParameter(accessor) {
18024         if (accessor && accessor.parameters.length > 0) {
18025             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
18026             return accessor.parameters[hasThis ? 1 : 0];
18027         }
18028     }
18029     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
18030     /** Get the type annotation for the value parameter. */
18031     function getSetAccessorTypeAnnotationNode(accessor) {
18032         var parameter = getSetAccessorValueParameter(accessor);
18033         return parameter && parameter.type;
18034     }
18035     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
18036     function getThisParameter(signature) {
18037         // callback tags do not currently support this parameters
18038         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
18039             var thisParameter = signature.parameters[0];
18040             if (parameterIsThisKeyword(thisParameter)) {
18041                 return thisParameter;
18042             }
18043         }
18044     }
18045     ts.getThisParameter = getThisParameter;
18046     function parameterIsThisKeyword(parameter) {
18047         return isThisIdentifier(parameter.name);
18048     }
18049     ts.parameterIsThisKeyword = parameterIsThisKeyword;
18050     function isThisIdentifier(node) {
18051         return !!node && node.kind === 79 /* Identifier */ && identifierIsThisKeyword(node);
18052     }
18053     ts.isThisIdentifier = isThisIdentifier;
18054     function isThisInTypeQuery(node) {
18055         if (!isThisIdentifier(node)) {
18056             return false;
18057         }
18058         while (ts.isQualifiedName(node.parent) && node.parent.left === node) {
18059             node = node.parent;
18060         }
18061         return node.parent.kind === 180 /* TypeQuery */;
18062     }
18063     ts.isThisInTypeQuery = isThisInTypeQuery;
18064     function identifierIsThisKeyword(id) {
18065         return id.originalKeywordKind === 108 /* ThisKeyword */;
18066     }
18067     ts.identifierIsThisKeyword = identifierIsThisKeyword;
18068     function getAllAccessorDeclarations(declarations, accessor) {
18069         // TODO: GH#18217
18070         var firstAccessor;
18071         var secondAccessor;
18072         var getAccessor;
18073         var setAccessor;
18074         if (hasDynamicName(accessor)) {
18075             firstAccessor = accessor;
18076             if (accessor.kind === 171 /* GetAccessor */) {
18077                 getAccessor = accessor;
18078             }
18079             else if (accessor.kind === 172 /* SetAccessor */) {
18080                 setAccessor = accessor;
18081             }
18082             else {
18083                 ts.Debug.fail("Accessor has wrong kind");
18084             }
18085         }
18086         else {
18087             ts.forEach(declarations, function (member) {
18088                 if (ts.isAccessor(member)
18089                     && isStatic(member) === isStatic(accessor)) {
18090                     var memberName = getPropertyNameForPropertyNameNode(member.name);
18091                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
18092                     if (memberName === accessorName) {
18093                         if (!firstAccessor) {
18094                             firstAccessor = member;
18095                         }
18096                         else if (!secondAccessor) {
18097                             secondAccessor = member;
18098                         }
18099                         if (member.kind === 171 /* GetAccessor */ && !getAccessor) {
18100                             getAccessor = member;
18101                         }
18102                         if (member.kind === 172 /* SetAccessor */ && !setAccessor) {
18103                             setAccessor = member;
18104                         }
18105                     }
18106                 }
18107             });
18108         }
18109         return {
18110             firstAccessor: firstAccessor,
18111             secondAccessor: secondAccessor,
18112             getAccessor: getAccessor,
18113             setAccessor: setAccessor
18114         };
18115     }
18116     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
18117     /**
18118      * Gets the effective type annotation of a variable, parameter, or property. If the node was
18119      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
18120      * functions only the JSDoc case.
18121      */
18122     function getEffectiveTypeAnnotationNode(node) {
18123         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
18124             return undefined;
18125         var type = node.type;
18126         if (type || !isInJSFile(node))
18127             return type;
18128         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
18129     }
18130     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
18131     function getTypeAnnotationNode(node) {
18132         return node.type;
18133     }
18134     ts.getTypeAnnotationNode = getTypeAnnotationNode;
18135     /**
18136      * Gets the effective return type annotation of a signature. If the node was parsed in a
18137      * JavaScript file, gets the return type annotation from JSDoc.
18138      */
18139     function getEffectiveReturnTypeNode(node) {
18140         return ts.isJSDocSignature(node) ?
18141             node.type && node.type.typeExpression && node.type.typeExpression.type :
18142             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
18143     }
18144     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
18145     function getJSDocTypeParameterDeclarations(node) {
18146         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
18147     }
18148     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
18149     /** template tags are only available when a typedef isn't already using them */
18150     function isNonTypeAliasTemplate(tag) {
18151         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 318 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
18152     }
18153     /**
18154      * Gets the effective type annotation of the value parameter of a set accessor. If the node
18155      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
18156      */
18157     function getEffectiveSetAccessorTypeAnnotationNode(node) {
18158         var parameter = getSetAccessorValueParameter(node);
18159         return parameter && getEffectiveTypeAnnotationNode(parameter);
18160     }
18161     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
18162     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
18163         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
18164     }
18165     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
18166     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
18167         // If the leading comments start on different line than the start of node, write new line
18168         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
18169             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
18170             writer.writeLine();
18171         }
18172     }
18173     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
18174     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
18175         // If the leading comments start on different line than the start of node, write new line
18176         if (pos !== commentPos &&
18177             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
18178             writer.writeLine();
18179         }
18180     }
18181     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
18182     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
18183         if (comments && comments.length > 0) {
18184             if (leadingSeparator) {
18185                 writer.writeSpace(" ");
18186             }
18187             var emitInterveningSeparator = false;
18188             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
18189                 var comment = comments_1[_i];
18190                 if (emitInterveningSeparator) {
18191                     writer.writeSpace(" ");
18192                     emitInterveningSeparator = false;
18193                 }
18194                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
18195                 if (comment.hasTrailingNewLine) {
18196                     writer.writeLine();
18197                 }
18198                 else {
18199                     emitInterveningSeparator = true;
18200                 }
18201             }
18202             if (emitInterveningSeparator && trailingSeparator) {
18203                 writer.writeSpace(" ");
18204             }
18205         }
18206     }
18207     ts.emitComments = emitComments;
18208     /**
18209      * Detached comment is a comment at the top of file or function body that is separated from
18210      * the next statement by space.
18211      */
18212     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
18213         var leadingComments;
18214         var currentDetachedCommentInfo;
18215         if (removeComments) {
18216             // removeComments is true, only reserve pinned comment at the top of file
18217             // For example:
18218             //      /*! Pinned Comment */
18219             //
18220             //      var x = 10;
18221             if (node.pos === 0) {
18222                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
18223             }
18224         }
18225         else {
18226             // removeComments is false, just get detached as normal and bypass the process to filter comment
18227             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
18228         }
18229         if (leadingComments) {
18230             var detachedComments = [];
18231             var lastComment = void 0;
18232             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
18233                 var comment = leadingComments_1[_i];
18234                 if (lastComment) {
18235                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
18236                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
18237                     if (commentLine >= lastCommentLine + 2) {
18238                         // There was a blank line between the last comment and this comment.  This
18239                         // comment is not part of the copyright comments.  Return what we have so
18240                         // far.
18241                         break;
18242                     }
18243                 }
18244                 detachedComments.push(comment);
18245                 lastComment = comment;
18246             }
18247             if (detachedComments.length) {
18248                 // All comments look like they could have been part of the copyright header.  Make
18249                 // sure there is at least one blank line between it and the node.  If not, it's not
18250                 // a copyright header.
18251                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
18252                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
18253                 if (nodeLine >= lastCommentLine + 2) {
18254                     // Valid detachedComments
18255                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
18256                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
18257                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
18258                 }
18259             }
18260         }
18261         return currentDetachedCommentInfo;
18262         function isPinnedCommentLocal(comment) {
18263             return isPinnedComment(text, comment.pos);
18264         }
18265     }
18266     ts.emitDetachedComments = emitDetachedComments;
18267     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
18268         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
18269             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
18270             var lineCount = lineMap.length;
18271             var firstCommentLineIndent = void 0;
18272             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
18273                 var nextLineStart = (currentLine + 1) === lineCount
18274                     ? text.length + 1
18275                     : lineMap[currentLine + 1];
18276                 if (pos !== commentPos) {
18277                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
18278                     if (firstCommentLineIndent === undefined) {
18279                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
18280                     }
18281                     // These are number of spaces writer is going to write at current indent
18282                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
18283                     // Number of spaces we want to be writing
18284                     // eg: Assume writer indent
18285                     // module m {
18286                     //         /* starts at character 9 this is line 1
18287                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
18288                     //   More left indented comment */                            --2  = 8 - 8 + 2
18289                     //     class c { }
18290                     // }
18291                     // module m {
18292                     //     /* this is line 1 -- Assume current writer indent 8
18293                     //      * line                                                --3 = 8 - 4 + 5
18294                     //            More right indented comment */                  --4 = 8 - 4 + 11
18295                     //     class c { }
18296                     // }
18297                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
18298                     if (spacesToEmit > 0) {
18299                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
18300                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
18301                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
18302                         writer.rawWrite(indentSizeSpaceString);
18303                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
18304                         while (numberOfSingleSpacesToEmit) {
18305                             writer.rawWrite(" ");
18306                             numberOfSingleSpacesToEmit--;
18307                         }
18308                     }
18309                     else {
18310                         // No spaces to emit write empty string
18311                         writer.rawWrite("");
18312                     }
18313                 }
18314                 // Write the comment line text
18315                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
18316                 pos = nextLineStart;
18317             }
18318         }
18319         else {
18320             // Single line comment of style //....
18321             writer.writeComment(text.substring(commentPos, commentEnd));
18322         }
18323     }
18324     ts.writeCommentRange = writeCommentRange;
18325     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
18326         var end = Math.min(commentEnd, nextLineStart - 1);
18327         var currentLineText = ts.trimString(text.substring(pos, end));
18328         if (currentLineText) {
18329             // trimmed forward and ending spaces text
18330             writer.writeComment(currentLineText);
18331             if (end !== commentEnd) {
18332                 writer.writeLine();
18333             }
18334         }
18335         else {
18336             // Empty string - make sure we write empty line
18337             writer.rawWrite(newLine);
18338         }
18339     }
18340     function calculateIndent(text, pos, end) {
18341         var currentLineIndent = 0;
18342         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
18343             if (text.charCodeAt(pos) === 9 /* tab */) {
18344                 // Tabs = TabSize = indent size and go to next tabStop
18345                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
18346             }
18347             else {
18348                 // Single space
18349                 currentLineIndent++;
18350             }
18351         }
18352         return currentLineIndent;
18353     }
18354     function hasEffectiveModifiers(node) {
18355         return getEffectiveModifierFlags(node) !== 0 /* None */;
18356     }
18357     ts.hasEffectiveModifiers = hasEffectiveModifiers;
18358     function hasSyntacticModifiers(node) {
18359         return getSyntacticModifierFlags(node) !== 0 /* None */;
18360     }
18361     ts.hasSyntacticModifiers = hasSyntacticModifiers;
18362     function hasEffectiveModifier(node, flags) {
18363         return !!getSelectedEffectiveModifierFlags(node, flags);
18364     }
18365     ts.hasEffectiveModifier = hasEffectiveModifier;
18366     function hasSyntacticModifier(node, flags) {
18367         return !!getSelectedSyntacticModifierFlags(node, flags);
18368     }
18369     ts.hasSyntacticModifier = hasSyntacticModifier;
18370     function isStatic(node) {
18371         // https://tc39.es/ecma262/#sec-static-semantics-isstatic
18372         return ts.isClassElement(node) && hasStaticModifier(node) || ts.isClassStaticBlockDeclaration(node);
18373     }
18374     ts.isStatic = isStatic;
18375     function hasStaticModifier(node) {
18376         return hasSyntacticModifier(node, 32 /* Static */);
18377     }
18378     ts.hasStaticModifier = hasStaticModifier;
18379     function hasOverrideModifier(node) {
18380         return hasEffectiveModifier(node, 16384 /* Override */);
18381     }
18382     ts.hasOverrideModifier = hasOverrideModifier;
18383     function hasAbstractModifier(node) {
18384         return hasSyntacticModifier(node, 128 /* Abstract */);
18385     }
18386     ts.hasAbstractModifier = hasAbstractModifier;
18387     function hasAmbientModifier(node) {
18388         return hasSyntacticModifier(node, 2 /* Ambient */);
18389     }
18390     ts.hasAmbientModifier = hasAmbientModifier;
18391     function hasEffectiveReadonlyModifier(node) {
18392         return hasEffectiveModifier(node, 64 /* Readonly */);
18393     }
18394     ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
18395     function getSelectedEffectiveModifierFlags(node, flags) {
18396         return getEffectiveModifierFlags(node) & flags;
18397     }
18398     ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
18399     function getSelectedSyntacticModifierFlags(node, flags) {
18400         return getSyntacticModifierFlags(node) & flags;
18401     }
18402     ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
18403     function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
18404         if (node.kind >= 0 /* FirstToken */ && node.kind <= 159 /* LastToken */) {
18405             return 0 /* None */;
18406         }
18407         if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
18408             node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
18409         }
18410         if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
18411             node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
18412         }
18413         return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
18414     }
18415     /**
18416      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
18417      *
18418      * NOTE: This function may use `parent` pointers.
18419      */
18420     function getEffectiveModifierFlags(node) {
18421         return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
18422     }
18423     ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
18424     function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
18425         return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
18426     }
18427     ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
18428     /**
18429      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
18430      *
18431      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
18432      */
18433     function getSyntacticModifierFlags(node) {
18434         return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
18435     }
18436     ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
18437     function getJSDocModifierFlagsNoCache(node) {
18438         var flags = 0 /* None */;
18439         if (!!node.parent && !ts.isParameter(node)) {
18440             if (isInJSFile(node)) {
18441                 if (ts.getJSDocPublicTagNoCache(node))
18442                     flags |= 4 /* Public */;
18443                 if (ts.getJSDocPrivateTagNoCache(node))
18444                     flags |= 8 /* Private */;
18445                 if (ts.getJSDocProtectedTagNoCache(node))
18446                     flags |= 16 /* Protected */;
18447                 if (ts.getJSDocReadonlyTagNoCache(node))
18448                     flags |= 64 /* Readonly */;
18449                 if (ts.getJSDocOverrideTagNoCache(node))
18450                     flags |= 16384 /* Override */;
18451             }
18452             if (ts.getJSDocDeprecatedTagNoCache(node))
18453                 flags |= 8192 /* Deprecated */;
18454         }
18455         return flags;
18456     }
18457     /**
18458      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
18459      *
18460      * NOTE: This function may use `parent` pointers.
18461      */
18462     function getEffectiveModifierFlagsNoCache(node) {
18463         return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
18464     }
18465     ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
18466     /**
18467      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
18468      *
18469      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
18470      */
18471     function getSyntacticModifierFlagsNoCache(node) {
18472         var flags = modifiersToFlags(node.modifiers);
18473         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 79 /* Identifier */ && node.isInJSDocNamespace)) {
18474             flags |= 1 /* Export */;
18475         }
18476         return flags;
18477     }
18478     ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
18479     function modifiersToFlags(modifiers) {
18480         var flags = 0 /* None */;
18481         if (modifiers) {
18482             for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
18483                 var modifier = modifiers_1[_i];
18484                 flags |= modifierToFlag(modifier.kind);
18485             }
18486         }
18487         return flags;
18488     }
18489     ts.modifiersToFlags = modifiersToFlags;
18490     function modifierToFlag(token) {
18491         switch (token) {
18492             case 124 /* StaticKeyword */: return 32 /* Static */;
18493             case 123 /* PublicKeyword */: return 4 /* Public */;
18494             case 122 /* ProtectedKeyword */: return 16 /* Protected */;
18495             case 121 /* PrivateKeyword */: return 8 /* Private */;
18496             case 126 /* AbstractKeyword */: return 128 /* Abstract */;
18497             case 93 /* ExportKeyword */: return 1 /* Export */;
18498             case 135 /* DeclareKeyword */: return 2 /* Ambient */;
18499             case 85 /* ConstKeyword */: return 2048 /* Const */;
18500             case 88 /* DefaultKeyword */: return 512 /* Default */;
18501             case 131 /* AsyncKeyword */: return 256 /* Async */;
18502             case 144 /* ReadonlyKeyword */: return 64 /* Readonly */;
18503             case 158 /* OverrideKeyword */: return 16384 /* Override */;
18504         }
18505         return 0 /* None */;
18506     }
18507     ts.modifierToFlag = modifierToFlag;
18508     function createModifiers(modifierFlags) {
18509         return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined;
18510     }
18511     ts.createModifiers = createModifiers;
18512     function isLogicalOperator(token) {
18513         return token === 56 /* BarBarToken */
18514             || token === 55 /* AmpersandAmpersandToken */
18515             || token === 53 /* ExclamationToken */;
18516     }
18517     ts.isLogicalOperator = isLogicalOperator;
18518     function isLogicalOrCoalescingAssignmentOperator(token) {
18519         return token === 75 /* BarBarEqualsToken */
18520             || token === 76 /* AmpersandAmpersandEqualsToken */
18521             || token === 77 /* QuestionQuestionEqualsToken */;
18522     }
18523     ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
18524     function isLogicalOrCoalescingAssignmentExpression(expr) {
18525         return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
18526     }
18527     ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
18528     function isAssignmentOperator(token) {
18529         return token >= 63 /* FirstAssignment */ && token <= 78 /* LastAssignment */;
18530     }
18531     ts.isAssignmentOperator = isAssignmentOperator;
18532     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
18533     function tryGetClassExtendingExpressionWithTypeArguments(node) {
18534         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
18535         return cls && !cls.isImplements ? cls.class : undefined;
18536     }
18537     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
18538     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
18539         return ts.isExpressionWithTypeArguments(node)
18540             && ts.isHeritageClause(node.parent)
18541             && ts.isClassLike(node.parent.parent)
18542             ? { class: node.parent.parent, isImplements: node.parent.token === 117 /* ImplementsKeyword */ }
18543             : undefined;
18544     }
18545     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
18546     function isAssignmentExpression(node, excludeCompoundAssignment) {
18547         return ts.isBinaryExpression(node)
18548             && (excludeCompoundAssignment
18549                 ? node.operatorToken.kind === 63 /* EqualsToken */
18550                 : isAssignmentOperator(node.operatorToken.kind))
18551             && ts.isLeftHandSideExpression(node.left);
18552     }
18553     ts.isAssignmentExpression = isAssignmentExpression;
18554     function isLeftHandSideOfAssignment(node) {
18555         return isAssignmentExpression(node.parent) && node.parent.left === node;
18556     }
18557     ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment;
18558     function isDestructuringAssignment(node) {
18559         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
18560             var kind = node.left.kind;
18561             return kind === 204 /* ObjectLiteralExpression */
18562                 || kind === 203 /* ArrayLiteralExpression */;
18563         }
18564         return false;
18565     }
18566     ts.isDestructuringAssignment = isDestructuringAssignment;
18567     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
18568         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
18569     }
18570     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
18571     function isEntityNameExpression(node) {
18572         return node.kind === 79 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
18573     }
18574     ts.isEntityNameExpression = isEntityNameExpression;
18575     function getFirstIdentifier(node) {
18576         switch (node.kind) {
18577             case 79 /* Identifier */:
18578                 return node;
18579             case 160 /* QualifiedName */:
18580                 do {
18581                     node = node.left;
18582                 } while (node.kind !== 79 /* Identifier */);
18583                 return node;
18584             case 205 /* PropertyAccessExpression */:
18585                 do {
18586                     node = node.expression;
18587                 } while (node.kind !== 79 /* Identifier */);
18588                 return node;
18589         }
18590     }
18591     ts.getFirstIdentifier = getFirstIdentifier;
18592     function isDottedName(node) {
18593         return node.kind === 79 /* Identifier */
18594             || node.kind === 108 /* ThisKeyword */
18595             || node.kind === 106 /* SuperKeyword */
18596             || node.kind === 230 /* MetaProperty */
18597             || node.kind === 205 /* PropertyAccessExpression */ && isDottedName(node.expression)
18598             || node.kind === 211 /* ParenthesizedExpression */ && isDottedName(node.expression);
18599     }
18600     ts.isDottedName = isDottedName;
18601     function isPropertyAccessEntityNameExpression(node) {
18602         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
18603     }
18604     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
18605     function tryGetPropertyAccessOrIdentifierToString(expr) {
18606         if (ts.isPropertyAccessExpression(expr)) {
18607             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
18608             if (baseStr !== undefined) {
18609                 return baseStr + "." + entityNameToString(expr.name);
18610             }
18611         }
18612         else if (ts.isElementAccessExpression(expr)) {
18613             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
18614             if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) {
18615                 return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression);
18616             }
18617         }
18618         else if (ts.isIdentifier(expr)) {
18619             return ts.unescapeLeadingUnderscores(expr.escapedText);
18620         }
18621         return undefined;
18622     }
18623     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
18624     function isPrototypeAccess(node) {
18625         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
18626     }
18627     ts.isPrototypeAccess = isPrototypeAccess;
18628     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
18629         return (node.parent.kind === 160 /* QualifiedName */ && node.parent.right === node) ||
18630             (node.parent.kind === 205 /* PropertyAccessExpression */ && node.parent.name === node);
18631     }
18632     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
18633     function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node) {
18634         return ts.isQualifiedName(node.parent) && node.parent.right === node
18635             || ts.isPropertyAccessExpression(node.parent) && node.parent.name === node
18636             || ts.isJSDocMemberName(node.parent) && node.parent.right === node;
18637     }
18638     ts.isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName = isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName;
18639     function isEmptyObjectLiteral(expression) {
18640         return expression.kind === 204 /* ObjectLiteralExpression */ &&
18641             expression.properties.length === 0;
18642     }
18643     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
18644     function isEmptyArrayLiteral(expression) {
18645         return expression.kind === 203 /* ArrayLiteralExpression */ &&
18646             expression.elements.length === 0;
18647     }
18648     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
18649     function getLocalSymbolForExportDefault(symbol) {
18650         if (!isExportDefaultSymbol(symbol) || !symbol.declarations)
18651             return undefined;
18652         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
18653             var decl = _a[_i];
18654             if (decl.localSymbol)
18655                 return decl.localSymbol;
18656         }
18657         return undefined;
18658     }
18659     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
18660     function isExportDefaultSymbol(symbol) {
18661         return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
18662     }
18663     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
18664     function tryExtractTSExtension(fileName) {
18665         return ts.find(supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18666     }
18667     ts.tryExtractTSExtension = tryExtractTSExtension;
18668     /**
18669      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
18670      * representing the UTF-8 encoding of the character, and return the expanded char code list.
18671      */
18672     function getExpandedCharCodes(input) {
18673         var output = [];
18674         var length = input.length;
18675         for (var i = 0; i < length; i++) {
18676             var charCode = input.charCodeAt(i);
18677             // handle utf8
18678             if (charCode < 0x80) {
18679                 output.push(charCode);
18680             }
18681             else if (charCode < 0x800) {
18682                 output.push((charCode >> 6) | 192);
18683                 output.push((charCode & 63) | 128);
18684             }
18685             else if (charCode < 0x10000) {
18686                 output.push((charCode >> 12) | 224);
18687                 output.push(((charCode >> 6) & 63) | 128);
18688                 output.push((charCode & 63) | 128);
18689             }
18690             else if (charCode < 0x20000) {
18691                 output.push((charCode >> 18) | 240);
18692                 output.push(((charCode >> 12) & 63) | 128);
18693                 output.push(((charCode >> 6) & 63) | 128);
18694                 output.push((charCode & 63) | 128);
18695             }
18696             else {
18697                 ts.Debug.assert(false, "Unexpected code point");
18698             }
18699         }
18700         return output;
18701     }
18702     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
18703     /**
18704      * Converts a string to a base-64 encoded ASCII string.
18705      */
18706     function convertToBase64(input) {
18707         var result = "";
18708         var charCodes = getExpandedCharCodes(input);
18709         var i = 0;
18710         var length = charCodes.length;
18711         var byte1, byte2, byte3, byte4;
18712         while (i < length) {
18713             // Convert every 6-bits in the input 3 character points
18714             // into a base64 digit
18715             byte1 = charCodes[i] >> 2;
18716             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
18717             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
18718             byte4 = charCodes[i + 2] & 63;
18719             // We are out of characters in the input, set the extra
18720             // digits to 64 (padding character).
18721             if (i + 1 >= length) {
18722                 byte3 = byte4 = 64;
18723             }
18724             else if (i + 2 >= length) {
18725                 byte4 = 64;
18726             }
18727             // Write to the output
18728             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
18729             i += 3;
18730         }
18731         return result;
18732     }
18733     ts.convertToBase64 = convertToBase64;
18734     function getStringFromExpandedCharCodes(codes) {
18735         var output = "";
18736         var i = 0;
18737         var length = codes.length;
18738         while (i < length) {
18739             var charCode = codes[i];
18740             if (charCode < 0x80) {
18741                 output += String.fromCharCode(charCode);
18742                 i++;
18743             }
18744             else if ((charCode & 192) === 192) {
18745                 var value = charCode & 63;
18746                 i++;
18747                 var nextCode = codes[i];
18748                 while ((nextCode & 192) === 128) {
18749                     value = (value << 6) | (nextCode & 63);
18750                     i++;
18751                     nextCode = codes[i];
18752                 }
18753                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
18754                 output += String.fromCharCode(value);
18755             }
18756             else {
18757                 // We don't want to kill the process when decoding fails (due to a following char byte not
18758                 // following a leading char), so we just print the (bad) value
18759                 output += String.fromCharCode(charCode);
18760                 i++;
18761             }
18762         }
18763         return output;
18764     }
18765     function base64encode(host, input) {
18766         if (host && host.base64encode) {
18767             return host.base64encode(input);
18768         }
18769         return convertToBase64(input);
18770     }
18771     ts.base64encode = base64encode;
18772     function base64decode(host, input) {
18773         if (host && host.base64decode) {
18774             return host.base64decode(input);
18775         }
18776         var length = input.length;
18777         var expandedCharCodes = [];
18778         var i = 0;
18779         while (i < length) {
18780             // Stop decoding once padding characters are present
18781             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
18782                 break;
18783             }
18784             // convert 4 input digits into three characters, ignoring padding characters at the end
18785             var ch1 = base64Digits.indexOf(input[i]);
18786             var ch2 = base64Digits.indexOf(input[i + 1]);
18787             var ch3 = base64Digits.indexOf(input[i + 2]);
18788             var ch4 = base64Digits.indexOf(input[i + 3]);
18789             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
18790             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
18791             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
18792             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
18793                 expandedCharCodes.push(code1);
18794             }
18795             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
18796                 expandedCharCodes.push(code1, code2);
18797             }
18798             else {
18799                 expandedCharCodes.push(code1, code2, code3);
18800             }
18801             i += 4;
18802         }
18803         return getStringFromExpandedCharCodes(expandedCharCodes);
18804     }
18805     ts.base64decode = base64decode;
18806     function readJson(path, host) {
18807         try {
18808             var jsonText = host.readFile(path);
18809             if (!jsonText)
18810                 return {};
18811             var result = ts.parseConfigFileTextToJson(path, jsonText);
18812             if (result.error) {
18813                 return {};
18814             }
18815             return result.config;
18816         }
18817         catch (e) {
18818             // gracefully handle if readFile fails or returns not JSON
18819             return {};
18820         }
18821     }
18822     ts.readJson = readJson;
18823     function directoryProbablyExists(directoryName, host) {
18824         // if host does not support 'directoryExists' assume that directory will exist
18825         return !host.directoryExists || host.directoryExists(directoryName);
18826     }
18827     ts.directoryProbablyExists = directoryProbablyExists;
18828     var carriageReturnLineFeed = "\r\n";
18829     var lineFeed = "\n";
18830     function getNewLineCharacter(options, getNewLine) {
18831         switch (options.newLine) {
18832             case 0 /* CarriageReturnLineFeed */:
18833                 return carriageReturnLineFeed;
18834             case 1 /* LineFeed */:
18835                 return lineFeed;
18836         }
18837         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
18838     }
18839     ts.getNewLineCharacter = getNewLineCharacter;
18840     /**
18841      * Creates a new TextRange from the provided pos and end.
18842      *
18843      * @param pos The start position.
18844      * @param end The end position.
18845      */
18846     function createRange(pos, end) {
18847         if (end === void 0) { end = pos; }
18848         ts.Debug.assert(end >= pos || end === -1);
18849         return { pos: pos, end: end };
18850     }
18851     ts.createRange = createRange;
18852     /**
18853      * Creates a new TextRange from a provided range with a new end position.
18854      *
18855      * @param range A TextRange.
18856      * @param end The new end position.
18857      */
18858     function moveRangeEnd(range, end) {
18859         return createRange(range.pos, end);
18860     }
18861     ts.moveRangeEnd = moveRangeEnd;
18862     /**
18863      * Creates a new TextRange from a provided range with a new start position.
18864      *
18865      * @param range A TextRange.
18866      * @param pos The new Start position.
18867      */
18868     function moveRangePos(range, pos) {
18869         return createRange(pos, range.end);
18870     }
18871     ts.moveRangePos = moveRangePos;
18872     /**
18873      * Moves the start position of a range past any decorators.
18874      */
18875     function moveRangePastDecorators(node) {
18876         return node.decorators && node.decorators.length > 0
18877             ? moveRangePos(node, node.decorators.end)
18878             : node;
18879     }
18880     ts.moveRangePastDecorators = moveRangePastDecorators;
18881     /**
18882      * Moves the start position of a range past any decorators or modifiers.
18883      */
18884     function moveRangePastModifiers(node) {
18885         return node.modifiers && node.modifiers.length > 0
18886             ? moveRangePos(node, node.modifiers.end)
18887             : moveRangePastDecorators(node);
18888     }
18889     ts.moveRangePastModifiers = moveRangePastModifiers;
18890     /**
18891      * Determines whether a TextRange has the same start and end positions.
18892      *
18893      * @param range A TextRange.
18894      */
18895     function isCollapsedRange(range) {
18896         return range.pos === range.end;
18897     }
18898     ts.isCollapsedRange = isCollapsedRange;
18899     /**
18900      * Creates a new TextRange for a token at the provides start position.
18901      *
18902      * @param pos The start position.
18903      * @param token The token.
18904      */
18905     function createTokenRange(pos, token) {
18906         return createRange(pos, pos + ts.tokenToString(token).length);
18907     }
18908     ts.createTokenRange = createTokenRange;
18909     function rangeIsOnSingleLine(range, sourceFile) {
18910         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
18911     }
18912     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
18913     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
18914         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
18915     }
18916     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
18917     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
18918         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
18919     }
18920     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
18921     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
18922         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
18923     }
18924     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
18925     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
18926         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
18927     }
18928     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
18929     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
18930         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
18931         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
18932     }
18933     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
18934     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
18935         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
18936     }
18937     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
18938     function isNodeArrayMultiLine(list, sourceFile) {
18939         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
18940     }
18941     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
18942     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
18943         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
18944     }
18945     ts.positionsAreOnSameLine = positionsAreOnSameLine;
18946     function getStartPositionOfRange(range, sourceFile, includeComments) {
18947         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
18948     }
18949     ts.getStartPositionOfRange = getStartPositionOfRange;
18950     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
18951         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
18952         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
18953         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
18954     }
18955     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
18956     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
18957         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
18958         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
18959     }
18960     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
18961     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
18962         if (stopPos === void 0) { stopPos = 0; }
18963         while (pos-- > stopPos) {
18964             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
18965                 return pos;
18966             }
18967         }
18968     }
18969     /**
18970      * Determines whether a name was originally the declaration name of an enum or namespace
18971      * declaration.
18972      */
18973     function isDeclarationNameOfEnumOrNamespace(node) {
18974         var parseNode = ts.getParseTreeNode(node);
18975         if (parseNode) {
18976             switch (parseNode.parent.kind) {
18977                 case 259 /* EnumDeclaration */:
18978                 case 260 /* ModuleDeclaration */:
18979                     return parseNode === parseNode.parent.name;
18980             }
18981         }
18982         return false;
18983     }
18984     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
18985     function getInitializedVariables(node) {
18986         return ts.filter(node.declarations, isInitializedVariable);
18987     }
18988     ts.getInitializedVariables = getInitializedVariables;
18989     function isInitializedVariable(node) {
18990         return node.initializer !== undefined;
18991     }
18992     function isWatchSet(options) {
18993         // Firefox has Object.prototype.watch
18994         return options.watch && options.hasOwnProperty("watch");
18995     }
18996     ts.isWatchSet = isWatchSet;
18997     function closeFileWatcher(watcher) {
18998         watcher.close();
18999     }
19000     ts.closeFileWatcher = closeFileWatcher;
19001     function getCheckFlags(symbol) {
19002         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
19003     }
19004     ts.getCheckFlags = getCheckFlags;
19005     function getDeclarationModifierFlagsFromSymbol(s, isWrite) {
19006         if (isWrite === void 0) { isWrite = false; }
19007         if (s.valueDeclaration) {
19008             var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 172 /* SetAccessor */; })) || s.valueDeclaration;
19009             var flags = ts.getCombinedModifierFlags(declaration);
19010             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
19011         }
19012         if (getCheckFlags(s) & 6 /* Synthetic */) {
19013             var checkFlags = s.checkFlags;
19014             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
19015                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
19016                     16 /* Protected */;
19017             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
19018             return accessModifier | staticModifier;
19019         }
19020         if (s.flags & 4194304 /* Prototype */) {
19021             return 4 /* Public */ | 32 /* Static */;
19022         }
19023         return 0;
19024     }
19025     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
19026     function skipAlias(symbol, checker) {
19027         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
19028     }
19029     ts.skipAlias = skipAlias;
19030     /** See comment on `declareModuleMember` in `binder.ts`. */
19031     function getCombinedLocalAndExportSymbolFlags(symbol) {
19032         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
19033     }
19034     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
19035     function isWriteOnlyAccess(node) {
19036         return accessKind(node) === 1 /* Write */;
19037     }
19038     ts.isWriteOnlyAccess = isWriteOnlyAccess;
19039     function isWriteAccess(node) {
19040         return accessKind(node) !== 0 /* Read */;
19041     }
19042     ts.isWriteAccess = isWriteAccess;
19043     var AccessKind;
19044     (function (AccessKind) {
19045         /** Only reads from a variable. */
19046         AccessKind[AccessKind["Read"] = 0] = "Read";
19047         /** Only writes to a variable without using the result. E.g.: `x++;`. */
19048         AccessKind[AccessKind["Write"] = 1] = "Write";
19049         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
19050         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
19051     })(AccessKind || (AccessKind = {}));
19052     function accessKind(node) {
19053         var parent = node.parent;
19054         if (!parent)
19055             return 0 /* Read */;
19056         switch (parent.kind) {
19057             case 211 /* ParenthesizedExpression */:
19058                 return accessKind(parent);
19059             case 219 /* PostfixUnaryExpression */:
19060             case 218 /* PrefixUnaryExpression */:
19061                 var operator = parent.operator;
19062                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
19063             case 220 /* BinaryExpression */:
19064                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
19065                 return left === node && isAssignmentOperator(operatorToken.kind) ?
19066                     operatorToken.kind === 63 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
19067                     : 0 /* Read */;
19068             case 205 /* PropertyAccessExpression */:
19069                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
19070             case 294 /* PropertyAssignment */: {
19071                 var parentAccess = accessKind(parent.parent);
19072                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
19073                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
19074             }
19075             case 295 /* ShorthandPropertyAssignment */:
19076                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
19077                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
19078             case 203 /* ArrayLiteralExpression */:
19079                 return accessKind(parent);
19080             default:
19081                 return 0 /* Read */;
19082         }
19083         function writeOrReadWrite() {
19084             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
19085             return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === 237 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
19086         }
19087     }
19088     function reverseAccessKind(a) {
19089         switch (a) {
19090             case 0 /* Read */:
19091                 return 1 /* Write */;
19092             case 1 /* Write */:
19093                 return 0 /* Read */;
19094             case 2 /* ReadWrite */:
19095                 return 2 /* ReadWrite */;
19096             default:
19097                 return ts.Debug.assertNever(a);
19098         }
19099     }
19100     function compareDataObjects(dst, src) {
19101         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
19102             return false;
19103         }
19104         for (var e in dst) {
19105             if (typeof dst[e] === "object") {
19106                 if (!compareDataObjects(dst[e], src[e])) {
19107                     return false;
19108                 }
19109             }
19110             else if (typeof dst[e] !== "function") {
19111                 if (dst[e] !== src[e]) {
19112                     return false;
19113                 }
19114             }
19115         }
19116         return true;
19117     }
19118     ts.compareDataObjects = compareDataObjects;
19119     /**
19120      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
19121      */
19122     function clearMap(map, onDeleteValue) {
19123         // Remove all
19124         map.forEach(onDeleteValue);
19125         map.clear();
19126     }
19127     ts.clearMap = clearMap;
19128     /**
19129      * Mutates the map with newMap such that keys in map will be same as newMap.
19130      */
19131     function mutateMapSkippingNewValues(map, newMap, options) {
19132         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
19133         // Needs update
19134         map.forEach(function (existingValue, key) {
19135             var valueInNewMap = newMap.get(key);
19136             // Not present any more in new map, remove it
19137             if (valueInNewMap === undefined) {
19138                 map.delete(key);
19139                 onDeleteValue(existingValue, key);
19140             }
19141             // If present notify about existing values
19142             else if (onExistingValue) {
19143                 onExistingValue(existingValue, valueInNewMap, key);
19144             }
19145         });
19146     }
19147     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
19148     /**
19149      * Mutates the map with newMap such that keys in map will be same as newMap.
19150      */
19151     function mutateMap(map, newMap, options) {
19152         // Needs update
19153         mutateMapSkippingNewValues(map, newMap, options);
19154         var createNewValue = options.createNewValue;
19155         // Add new values that are not already present
19156         newMap.forEach(function (valueInNewMap, key) {
19157             if (!map.has(key)) {
19158                 // New values
19159                 map.set(key, createNewValue(key, valueInNewMap));
19160             }
19161         });
19162     }
19163     ts.mutateMap = mutateMap;
19164     function isAbstractConstructorSymbol(symbol) {
19165         if (symbol.flags & 32 /* Class */) {
19166             var declaration = getClassLikeDeclarationOfSymbol(symbol);
19167             return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
19168         }
19169         return false;
19170     }
19171     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
19172     function getClassLikeDeclarationOfSymbol(symbol) {
19173         var _a;
19174         return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike);
19175     }
19176     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
19177     function getObjectFlags(type) {
19178         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
19179     }
19180     ts.getObjectFlags = getObjectFlags;
19181     function typeHasCallOrConstructSignatures(type, checker) {
19182         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
19183     }
19184     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
19185     function forSomeAncestorDirectory(directory, callback) {
19186         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
19187     }
19188     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
19189     function isUMDExportSymbol(symbol) {
19190         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
19191     }
19192     ts.isUMDExportSymbol = isUMDExportSymbol;
19193     function showModuleSpecifier(_a) {
19194         var moduleSpecifier = _a.moduleSpecifier;
19195         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
19196     }
19197     ts.showModuleSpecifier = showModuleSpecifier;
19198     function getLastChild(node) {
19199         var lastChild;
19200         ts.forEachChild(node, function (child) {
19201             if (nodeIsPresent(child))
19202                 lastChild = child;
19203         }, function (children) {
19204             // As an optimization, jump straight to the end of the list.
19205             for (var i = children.length - 1; i >= 0; i--) {
19206                 if (nodeIsPresent(children[i])) {
19207                     lastChild = children[i];
19208                     break;
19209                 }
19210             }
19211         });
19212         return lastChild;
19213     }
19214     ts.getLastChild = getLastChild;
19215     function addToSeen(seen, key, value) {
19216         if (value === void 0) { value = true; }
19217         if (seen.has(key)) {
19218             return false;
19219         }
19220         seen.set(key, value);
19221         return true;
19222     }
19223     ts.addToSeen = addToSeen;
19224     function isObjectTypeDeclaration(node) {
19225         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
19226     }
19227     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
19228     function isTypeNodeKind(kind) {
19229         return (kind >= 176 /* FirstTypeNode */ && kind <= 199 /* LastTypeNode */)
19230             || kind === 130 /* AnyKeyword */
19231             || kind === 154 /* UnknownKeyword */
19232             || kind === 146 /* NumberKeyword */
19233             || kind === 157 /* BigIntKeyword */
19234             || kind === 147 /* ObjectKeyword */
19235             || kind === 133 /* BooleanKeyword */
19236             || kind === 149 /* StringKeyword */
19237             || kind === 150 /* SymbolKeyword */
19238             || kind === 114 /* VoidKeyword */
19239             || kind === 152 /* UndefinedKeyword */
19240             || kind === 143 /* NeverKeyword */
19241             || kind === 227 /* ExpressionWithTypeArguments */
19242             || kind === 310 /* JSDocAllType */
19243             || kind === 311 /* JSDocUnknownType */
19244             || kind === 312 /* JSDocNullableType */
19245             || kind === 313 /* JSDocNonNullableType */
19246             || kind === 314 /* JSDocOptionalType */
19247             || kind === 315 /* JSDocFunctionType */
19248             || kind === 316 /* JSDocVariadicType */;
19249     }
19250     ts.isTypeNodeKind = isTypeNodeKind;
19251     function isAccessExpression(node) {
19252         return node.kind === 205 /* PropertyAccessExpression */ || node.kind === 206 /* ElementAccessExpression */;
19253     }
19254     ts.isAccessExpression = isAccessExpression;
19255     function getNameOfAccessExpression(node) {
19256         if (node.kind === 205 /* PropertyAccessExpression */) {
19257             return node.name;
19258         }
19259         ts.Debug.assert(node.kind === 206 /* ElementAccessExpression */);
19260         return node.argumentExpression;
19261     }
19262     ts.getNameOfAccessExpression = getNameOfAccessExpression;
19263     function isBundleFileTextLike(section) {
19264         switch (section.kind) {
19265             case "text" /* Text */:
19266             case "internal" /* Internal */:
19267                 return true;
19268             default:
19269                 return false;
19270         }
19271     }
19272     ts.isBundleFileTextLike = isBundleFileTextLike;
19273     function isNamedImportsOrExports(node) {
19274         return node.kind === 268 /* NamedImports */ || node.kind === 272 /* NamedExports */;
19275     }
19276     ts.isNamedImportsOrExports = isNamedImportsOrExports;
19277     function getLeftmostAccessExpression(expr) {
19278         while (isAccessExpression(expr)) {
19279             expr = expr.expression;
19280         }
19281         return expr;
19282     }
19283     ts.getLeftmostAccessExpression = getLeftmostAccessExpression;
19284     function getLeftmostExpression(node, stopAtCallExpressions) {
19285         while (true) {
19286             switch (node.kind) {
19287                 case 219 /* PostfixUnaryExpression */:
19288                     node = node.operand;
19289                     continue;
19290                 case 220 /* BinaryExpression */:
19291                     node = node.left;
19292                     continue;
19293                 case 221 /* ConditionalExpression */:
19294                     node = node.condition;
19295                     continue;
19296                 case 209 /* TaggedTemplateExpression */:
19297                     node = node.tag;
19298                     continue;
19299                 case 207 /* CallExpression */:
19300                     if (stopAtCallExpressions) {
19301                         return node;
19302                     }
19303                 // falls through
19304                 case 228 /* AsExpression */:
19305                 case 206 /* ElementAccessExpression */:
19306                 case 205 /* PropertyAccessExpression */:
19307                 case 229 /* NonNullExpression */:
19308                 case 348 /* PartiallyEmittedExpression */:
19309                     node = node.expression;
19310                     continue;
19311             }
19312             return node;
19313         }
19314     }
19315     ts.getLeftmostExpression = getLeftmostExpression;
19316     function Symbol(flags, name) {
19317         this.flags = flags;
19318         this.escapedName = name;
19319         this.declarations = undefined;
19320         this.valueDeclaration = undefined;
19321         this.id = undefined;
19322         this.mergeId = undefined;
19323         this.parent = undefined;
19324     }
19325     function Type(checker, flags) {
19326         this.flags = flags;
19327         if (ts.Debug.isDebugging || ts.tracing) {
19328             this.checker = checker;
19329         }
19330     }
19331     function Signature(checker, flags) {
19332         this.flags = flags;
19333         if (ts.Debug.isDebugging) {
19334             this.checker = checker;
19335         }
19336     }
19337     function Node(kind, pos, end) {
19338         this.pos = pos;
19339         this.end = end;
19340         this.kind = kind;
19341         this.id = 0;
19342         this.flags = 0 /* None */;
19343         this.modifierFlagsCache = 0 /* None */;
19344         this.transformFlags = 0 /* None */;
19345         this.parent = undefined;
19346         this.original = undefined;
19347     }
19348     function Token(kind, pos, end) {
19349         this.pos = pos;
19350         this.end = end;
19351         this.kind = kind;
19352         this.id = 0;
19353         this.flags = 0 /* None */;
19354         this.transformFlags = 0 /* None */;
19355         this.parent = undefined;
19356     }
19357     function Identifier(kind, pos, end) {
19358         this.pos = pos;
19359         this.end = end;
19360         this.kind = kind;
19361         this.id = 0;
19362         this.flags = 0 /* None */;
19363         this.transformFlags = 0 /* None */;
19364         this.parent = undefined;
19365         this.original = undefined;
19366         this.flowNode = undefined;
19367     }
19368     function SourceMapSource(fileName, text, skipTrivia) {
19369         this.fileName = fileName;
19370         this.text = text;
19371         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
19372     }
19373     // eslint-disable-next-line prefer-const
19374     ts.objectAllocator = {
19375         getNodeConstructor: function () { return Node; },
19376         getTokenConstructor: function () { return Token; },
19377         getIdentifierConstructor: function () { return Identifier; },
19378         getPrivateIdentifierConstructor: function () { return Node; },
19379         getSourceFileConstructor: function () { return Node; },
19380         getSymbolConstructor: function () { return Symbol; },
19381         getTypeConstructor: function () { return Type; },
19382         getSignatureConstructor: function () { return Signature; },
19383         getSourceMapSourceConstructor: function () { return SourceMapSource; },
19384     };
19385     function setObjectAllocator(alloc) {
19386         ts.objectAllocator = alloc;
19387     }
19388     ts.setObjectAllocator = setObjectAllocator;
19389     function formatStringFromArgs(text, args, baseIndex) {
19390         if (baseIndex === void 0) { baseIndex = 0; }
19391         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
19392     }
19393     ts.formatStringFromArgs = formatStringFromArgs;
19394     /* @internal */
19395     function setLocalizedDiagnosticMessages(messages) {
19396         ts.localizedDiagnosticMessages = messages;
19397     }
19398     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
19399     function getLocaleSpecificMessage(message) {
19400         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
19401     }
19402     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
19403     function createDetachedDiagnostic(fileName, start, length, message) {
19404         assertDiagnosticLocation(/*file*/ undefined, start, length);
19405         var text = getLocaleSpecificMessage(message);
19406         if (arguments.length > 4) {
19407             text = formatStringFromArgs(text, arguments, 4);
19408         }
19409         return {
19410             file: undefined,
19411             start: start,
19412             length: length,
19413             messageText: text,
19414             category: message.category,
19415             code: message.code,
19416             reportsUnnecessary: message.reportsUnnecessary,
19417             fileName: fileName,
19418         };
19419     }
19420     ts.createDetachedDiagnostic = createDetachedDiagnostic;
19421     function isDiagnosticWithDetachedLocation(diagnostic) {
19422         return diagnostic.file === undefined
19423             && diagnostic.start !== undefined
19424             && diagnostic.length !== undefined
19425             && typeof diagnostic.fileName === "string";
19426     }
19427     function attachFileToDiagnostic(diagnostic, file) {
19428         var fileName = file.fileName || "";
19429         var length = file.text.length;
19430         ts.Debug.assertEqual(diagnostic.fileName, fileName);
19431         ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
19432         ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
19433         var diagnosticWithLocation = {
19434             file: file,
19435             start: diagnostic.start,
19436             length: diagnostic.length,
19437             messageText: diagnostic.messageText,
19438             category: diagnostic.category,
19439             code: diagnostic.code,
19440             reportsUnnecessary: diagnostic.reportsUnnecessary
19441         };
19442         if (diagnostic.relatedInformation) {
19443             diagnosticWithLocation.relatedInformation = [];
19444             for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
19445                 var related = _a[_i];
19446                 if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
19447                     ts.Debug.assertLessThanOrEqual(related.start, length);
19448                     ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
19449                     diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
19450                 }
19451                 else {
19452                     diagnosticWithLocation.relatedInformation.push(related);
19453                 }
19454             }
19455         }
19456         return diagnosticWithLocation;
19457     }
19458     function attachFileToDiagnostics(diagnostics, file) {
19459         var diagnosticsWithLocation = [];
19460         for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
19461             var diagnostic = diagnostics_1[_i];
19462             diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
19463         }
19464         return diagnosticsWithLocation;
19465     }
19466     ts.attachFileToDiagnostics = attachFileToDiagnostics;
19467     function createFileDiagnostic(file, start, length, message) {
19468         assertDiagnosticLocation(file, start, length);
19469         var text = getLocaleSpecificMessage(message);
19470         if (arguments.length > 4) {
19471             text = formatStringFromArgs(text, arguments, 4);
19472         }
19473         return {
19474             file: file,
19475             start: start,
19476             length: length,
19477             messageText: text,
19478             category: message.category,
19479             code: message.code,
19480             reportsUnnecessary: message.reportsUnnecessary,
19481             reportsDeprecated: message.reportsDeprecated
19482         };
19483     }
19484     ts.createFileDiagnostic = createFileDiagnostic;
19485     function formatMessage(_dummy, message) {
19486         var text = getLocaleSpecificMessage(message);
19487         if (arguments.length > 2) {
19488             text = formatStringFromArgs(text, arguments, 2);
19489         }
19490         return text;
19491     }
19492     ts.formatMessage = formatMessage;
19493     function createCompilerDiagnostic(message) {
19494         var text = getLocaleSpecificMessage(message);
19495         if (arguments.length > 1) {
19496             text = formatStringFromArgs(text, arguments, 1);
19497         }
19498         return {
19499             file: undefined,
19500             start: undefined,
19501             length: undefined,
19502             messageText: text,
19503             category: message.category,
19504             code: message.code,
19505             reportsUnnecessary: message.reportsUnnecessary,
19506             reportsDeprecated: message.reportsDeprecated
19507         };
19508     }
19509     ts.createCompilerDiagnostic = createCompilerDiagnostic;
19510     function createCompilerDiagnosticFromMessageChain(chain, relatedInformation) {
19511         return {
19512             file: undefined,
19513             start: undefined,
19514             length: undefined,
19515             code: chain.code,
19516             category: chain.category,
19517             messageText: chain.next ? chain : chain.messageText,
19518             relatedInformation: relatedInformation
19519         };
19520     }
19521     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
19522     function chainDiagnosticMessages(details, message) {
19523         var text = getLocaleSpecificMessage(message);
19524         if (arguments.length > 2) {
19525             text = formatStringFromArgs(text, arguments, 2);
19526         }
19527         return {
19528             messageText: text,
19529             category: message.category,
19530             code: message.code,
19531             next: details === undefined || Array.isArray(details) ? details : [details]
19532         };
19533     }
19534     ts.chainDiagnosticMessages = chainDiagnosticMessages;
19535     function concatenateDiagnosticMessageChains(headChain, tailChain) {
19536         var lastChain = headChain;
19537         while (lastChain.next) {
19538             lastChain = lastChain.next[0];
19539         }
19540         lastChain.next = [tailChain];
19541     }
19542     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
19543     function getDiagnosticFilePath(diagnostic) {
19544         return diagnostic.file ? diagnostic.file.path : undefined;
19545     }
19546     function compareDiagnostics(d1, d2) {
19547         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
19548             compareRelatedInformation(d1, d2) ||
19549             0 /* EqualTo */;
19550     }
19551     ts.compareDiagnostics = compareDiagnostics;
19552     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
19553         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
19554             ts.compareValues(d1.start, d2.start) ||
19555             ts.compareValues(d1.length, d2.length) ||
19556             ts.compareValues(d1.code, d2.code) ||
19557             compareMessageText(d1.messageText, d2.messageText) ||
19558             0 /* EqualTo */;
19559     }
19560     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
19561     function compareRelatedInformation(d1, d2) {
19562         if (!d1.relatedInformation && !d2.relatedInformation) {
19563             return 0 /* EqualTo */;
19564         }
19565         if (d1.relatedInformation && d2.relatedInformation) {
19566             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
19567                 var d2i = d2.relatedInformation[index];
19568                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
19569             }) || 0 /* EqualTo */;
19570         }
19571         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
19572     }
19573     function compareMessageText(t1, t2) {
19574         if (typeof t1 === "string" && typeof t2 === "string") {
19575             return ts.compareStringsCaseSensitive(t1, t2);
19576         }
19577         else if (typeof t1 === "string") {
19578             return -1 /* LessThan */;
19579         }
19580         else if (typeof t2 === "string") {
19581             return 1 /* GreaterThan */;
19582         }
19583         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
19584         if (res) {
19585             return res;
19586         }
19587         if (!t1.next && !t2.next) {
19588             return 0 /* EqualTo */;
19589         }
19590         if (!t1.next) {
19591             return -1 /* LessThan */;
19592         }
19593         if (!t2.next) {
19594             return 1 /* GreaterThan */;
19595         }
19596         var len = Math.min(t1.next.length, t2.next.length);
19597         for (var i = 0; i < len; i++) {
19598             res = compareMessageText(t1.next[i], t2.next[i]);
19599             if (res) {
19600                 return res;
19601             }
19602         }
19603         if (t1.next.length < t2.next.length) {
19604             return -1 /* LessThan */;
19605         }
19606         else if (t1.next.length > t2.next.length) {
19607             return 1 /* GreaterThan */;
19608         }
19609         return 0 /* EqualTo */;
19610     }
19611     function getLanguageVariant(scriptKind) {
19612         // .tsx and .jsx files are treated as jsx language variant.
19613         return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19614     }
19615     ts.getLanguageVariant = getLanguageVariant;
19616     function getEmitScriptTarget(compilerOptions) {
19617         return compilerOptions.target ||
19618             (compilerOptions.module === ts.ModuleKind.Node12 && 7 /* ES2020 */) ||
19619             (compilerOptions.module === ts.ModuleKind.NodeNext && 99 /* ESNext */) ||
19620             0 /* ES3 */;
19621     }
19622     ts.getEmitScriptTarget = getEmitScriptTarget;
19623     function getEmitModuleKind(compilerOptions) {
19624         return typeof compilerOptions.module === "number" ?
19625             compilerOptions.module :
19626             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
19627     }
19628     ts.getEmitModuleKind = getEmitModuleKind;
19629     function getEmitModuleResolutionKind(compilerOptions) {
19630         var moduleResolution = compilerOptions.moduleResolution;
19631         if (moduleResolution === undefined) {
19632             switch (getEmitModuleKind(compilerOptions)) {
19633                 case ts.ModuleKind.CommonJS:
19634                     moduleResolution = ts.ModuleResolutionKind.NodeJs;
19635                     break;
19636                 case ts.ModuleKind.Node12:
19637                     moduleResolution = ts.ModuleResolutionKind.Node12;
19638                     break;
19639                 case ts.ModuleKind.NodeNext:
19640                     moduleResolution = ts.ModuleResolutionKind.NodeNext;
19641                     break;
19642                 default:
19643                     moduleResolution = ts.ModuleResolutionKind.Classic;
19644                     break;
19645             }
19646         }
19647         return moduleResolution;
19648     }
19649     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
19650     function hasJsonModuleEmitEnabled(options) {
19651         switch (getEmitModuleKind(options)) {
19652             case ts.ModuleKind.CommonJS:
19653             case ts.ModuleKind.AMD:
19654             case ts.ModuleKind.ES2015:
19655             case ts.ModuleKind.ES2020:
19656             case ts.ModuleKind.ES2022:
19657             case ts.ModuleKind.ESNext:
19658             case ts.ModuleKind.Node12:
19659             case ts.ModuleKind.NodeNext:
19660                 return true;
19661             default:
19662                 return false;
19663         }
19664     }
19665     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
19666     function unreachableCodeIsError(options) {
19667         return options.allowUnreachableCode === false;
19668     }
19669     ts.unreachableCodeIsError = unreachableCodeIsError;
19670     function unusedLabelIsError(options) {
19671         return options.allowUnusedLabels === false;
19672     }
19673     ts.unusedLabelIsError = unusedLabelIsError;
19674     function getAreDeclarationMapsEnabled(options) {
19675         return !!(getEmitDeclarations(options) && options.declarationMap);
19676     }
19677     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
19678     function getESModuleInterop(compilerOptions) {
19679         if (compilerOptions.esModuleInterop !== undefined) {
19680             return compilerOptions.esModuleInterop;
19681         }
19682         switch (getEmitModuleKind(compilerOptions)) {
19683             case ts.ModuleKind.Node12:
19684             case ts.ModuleKind.NodeNext:
19685                 return true;
19686         }
19687         return undefined;
19688     }
19689     ts.getESModuleInterop = getESModuleInterop;
19690     function getAllowSyntheticDefaultImports(compilerOptions) {
19691         var moduleKind = getEmitModuleKind(compilerOptions);
19692         return compilerOptions.allowSyntheticDefaultImports !== undefined
19693             ? compilerOptions.allowSyntheticDefaultImports
19694             : getESModuleInterop(compilerOptions) ||
19695                 moduleKind === ts.ModuleKind.System;
19696     }
19697     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
19698     function getEmitDeclarations(compilerOptions) {
19699         return !!(compilerOptions.declaration || compilerOptions.composite);
19700     }
19701     ts.getEmitDeclarations = getEmitDeclarations;
19702     function shouldPreserveConstEnums(compilerOptions) {
19703         return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
19704     }
19705     ts.shouldPreserveConstEnums = shouldPreserveConstEnums;
19706     function isIncrementalCompilation(options) {
19707         return !!(options.incremental || options.composite);
19708     }
19709     ts.isIncrementalCompilation = isIncrementalCompilation;
19710     function getStrictOptionValue(compilerOptions, flag) {
19711         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
19712     }
19713     ts.getStrictOptionValue = getStrictOptionValue;
19714     function getAllowJSCompilerOption(compilerOptions) {
19715         return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs;
19716     }
19717     ts.getAllowJSCompilerOption = getAllowJSCompilerOption;
19718     function getUseDefineForClassFields(compilerOptions) {
19719         return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ : compilerOptions.useDefineForClassFields;
19720     }
19721     ts.getUseDefineForClassFields = getUseDefineForClassFields;
19722     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
19723         return optionsHaveChanges(oldOptions, newOptions, ts.semanticDiagnosticsOptionDeclarations);
19724     }
19725     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
19726     function compilerOptionsAffectEmit(newOptions, oldOptions) {
19727         return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations);
19728     }
19729     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
19730     function getCompilerOptionValue(options, option) {
19731         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
19732     }
19733     ts.getCompilerOptionValue = getCompilerOptionValue;
19734     function getJSXTransformEnabled(options) {
19735         var jsx = options.jsx;
19736         return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */;
19737     }
19738     ts.getJSXTransformEnabled = getJSXTransformEnabled;
19739     function getJSXImplicitImportBase(compilerOptions, file) {
19740         var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource");
19741         var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas;
19742         return compilerOptions.jsx === 4 /* ReactJSX */ ||
19743             compilerOptions.jsx === 5 /* ReactJSXDev */ ||
19744             compilerOptions.jsxImportSource ||
19745             jsxImportSourcePragma ?
19746             (jsxImportSourcePragma === null || jsxImportSourcePragma === void 0 ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" :
19747             undefined;
19748     }
19749     ts.getJSXImplicitImportBase = getJSXImplicitImportBase;
19750     function getJSXRuntimeImport(base, options) {
19751         return base ? "".concat(base, "/").concat(options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined;
19752     }
19753     ts.getJSXRuntimeImport = getJSXRuntimeImport;
19754     function hasZeroOrOneAsteriskCharacter(str) {
19755         var seenAsterisk = false;
19756         for (var i = 0; i < str.length; i++) {
19757             if (str.charCodeAt(i) === 42 /* asterisk */) {
19758                 if (!seenAsterisk) {
19759                     seenAsterisk = true;
19760                 }
19761                 else {
19762                     // have already seen asterisk
19763                     return false;
19764                 }
19765             }
19766         }
19767         return true;
19768     }
19769     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
19770     function createSymlinkCache(cwd, getCanonicalFileName) {
19771         var symlinkedDirectories;
19772         var symlinkedDirectoriesByRealpath;
19773         var symlinkedFiles;
19774         var hasProcessedResolutions = false;
19775         return {
19776             getSymlinkedFiles: function () { return symlinkedFiles; },
19777             getSymlinkedDirectories: function () { return symlinkedDirectories; },
19778             getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; },
19779             setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
19780             setSymlinkedDirectory: function (symlink, real) {
19781                 // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks
19782                 // where both the realpath and the symlink path are inside node_modules/.pnpm. Since
19783                 // this path is never a candidate for a module specifier, we can ignore it entirely.
19784                 var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName);
19785                 if (!containsIgnoredPath(symlinkPath)) {
19786                     symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath);
19787                     if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) {
19788                         (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink);
19789                     }
19790                     (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real);
19791                 }
19792             },
19793             setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) {
19794                 this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real);
19795                 var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1];
19796                 if (commonResolved && commonOriginal) {
19797                     this.setSymlinkedDirectory(commonOriginal, {
19798                         real: commonResolved,
19799                         realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName),
19800                     });
19801                 }
19802             },
19803             setSymlinksFromResolutions: function (files, typeReferenceDirectives) {
19804                 var _this = this;
19805                 var _a;
19806                 ts.Debug.assert(!hasProcessedResolutions);
19807                 hasProcessedResolutions = true;
19808                 for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
19809                     var file = files_1[_i];
19810                     (_a = file.resolvedModules) === null || _a === void 0 ? void 0 : _a.forEach(function (resolution) { return processResolution(_this, resolution); });
19811                 }
19812                 typeReferenceDirectives === null || typeReferenceDirectives === void 0 ? void 0 : typeReferenceDirectives.forEach(function (resolution) { return processResolution(_this, resolution); });
19813             },
19814             hasProcessedResolutions: function () { return hasProcessedResolutions; },
19815         };
19816         function processResolution(cache, resolution) {
19817             if (!resolution || !resolution.originalPath || !resolution.resolvedFileName)
19818                 return;
19819             var resolvedFileName = resolution.resolvedFileName, originalPath = resolution.originalPath;
19820             cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName);
19821             var _a = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1];
19822             if (commonResolved && commonOriginal) {
19823                 cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
19824             }
19825         }
19826     }
19827     ts.createSymlinkCache = createSymlinkCache;
19828     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
19829         var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd));
19830         var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd));
19831         var isDirectory = false;
19832         while (aParts.length >= 2 && bParts.length >= 2 &&
19833             !isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
19834             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
19835             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
19836             aParts.pop();
19837             bParts.pop();
19838             isDirectory = true;
19839         }
19840         return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
19841     }
19842     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
19843     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
19844     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
19845         return s !== undefined && (getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"));
19846     }
19847     function stripLeadingDirectorySeparator(s) {
19848         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
19849     }
19850     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
19851         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
19852         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
19853     }
19854     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
19855     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
19856     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
19857     // proof.
19858     var reservedCharacterPattern = /[^\w\s\/]/g;
19859     function regExpEscape(text) {
19860         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
19861     }
19862     ts.regExpEscape = regExpEscape;
19863     function escapeRegExpCharacter(match) {
19864         return "\\" + match;
19865     }
19866     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
19867     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
19868     var implicitExcludePathRegexPattern = "(?!(".concat(ts.commonPackageFolders.join("|"), ")(/|$))");
19869     var filesMatcher = {
19870         /**
19871          * Matches any single directory segment unless it is the last segment and a .min.js file
19872          * Breakdown:
19873          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
19874          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
19875          */
19876         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
19877         /**
19878          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
19879          * files or directories, does not match subdirectories that start with a . character
19880          */
19881         doubleAsteriskRegexFragment: "(/".concat(implicitExcludePathRegexPattern, "[^/.][^/]*)*?"),
19882         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
19883     };
19884     var directoriesMatcher = {
19885         singleAsteriskRegexFragment: "[^/]*",
19886         /**
19887          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
19888          * files or directories, does not match subdirectories that start with a . character
19889          */
19890         doubleAsteriskRegexFragment: "(/".concat(implicitExcludePathRegexPattern, "[^/.][^/]*)*?"),
19891         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
19892     };
19893     var excludeMatcher = {
19894         singleAsteriskRegexFragment: "[^/]*",
19895         doubleAsteriskRegexFragment: "(/.+?)?",
19896         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
19897     };
19898     var wildcardMatchers = {
19899         files: filesMatcher,
19900         directories: directoriesMatcher,
19901         exclude: excludeMatcher
19902     };
19903     function getRegularExpressionForWildcard(specs, basePath, usage) {
19904         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
19905         if (!patterns || !patterns.length) {
19906             return undefined;
19907         }
19908         var pattern = patterns.map(function (pattern) { return "(".concat(pattern, ")"); }).join("|");
19909         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
19910         var terminator = usage === "exclude" ? "($|/)" : "$";
19911         return "^(".concat(pattern, ")").concat(terminator);
19912     }
19913     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
19914     function getRegularExpressionsForWildcards(specs, basePath, usage) {
19915         if (specs === undefined || specs.length === 0) {
19916             return undefined;
19917         }
19918         return ts.flatMap(specs, function (spec) {
19919             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
19920         });
19921     }
19922     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
19923     /**
19924      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
19925      * and does not contain any glob characters itself.
19926      */
19927     function isImplicitGlob(lastPathComponent) {
19928         return !/[.*?]/.test(lastPathComponent);
19929     }
19930     ts.isImplicitGlob = isImplicitGlob;
19931     function getPatternFromSpec(spec, basePath, usage) {
19932         var pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
19933         return pattern && "^(".concat(pattern, ")").concat(usage === "exclude" ? "($|/)" : "$");
19934     }
19935     ts.getPatternFromSpec = getPatternFromSpec;
19936     function getSubPatternFromSpec(spec, basePath, usage, _a) {
19937         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
19938         var subpattern = "";
19939         var hasWrittenComponent = false;
19940         var components = ts.getNormalizedPathComponents(spec, basePath);
19941         var lastComponent = ts.last(components);
19942         if (usage !== "exclude" && lastComponent === "**") {
19943             return undefined;
19944         }
19945         // getNormalizedPathComponents includes the separator for the root component.
19946         // We need to remove to create our regex correctly.
19947         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
19948         if (isImplicitGlob(lastComponent)) {
19949             components.push("**", "*");
19950         }
19951         var optionalCount = 0;
19952         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
19953             var component = components_1[_i];
19954             if (component === "**") {
19955                 subpattern += doubleAsteriskRegexFragment;
19956             }
19957             else {
19958                 if (usage === "directories") {
19959                     subpattern += "(";
19960                     optionalCount++;
19961                 }
19962                 if (hasWrittenComponent) {
19963                     subpattern += ts.directorySeparator;
19964                 }
19965                 if (usage !== "exclude") {
19966                     var componentPattern = "";
19967                     // The * and ? wildcards should not match directories or files that start with . if they
19968                     // appear first in a component. Dotted directories and files can be included explicitly
19969                     // like so: **/.*/.*
19970                     if (component.charCodeAt(0) === 42 /* asterisk */) {
19971                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
19972                         component = component.substr(1);
19973                     }
19974                     else if (component.charCodeAt(0) === 63 /* question */) {
19975                         componentPattern += "[^./]";
19976                         component = component.substr(1);
19977                     }
19978                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
19979                     // Patterns should not include subfolders like node_modules unless they are
19980                     // explicitly included as part of the path.
19981                     //
19982                     // As an optimization, if the component pattern is the same as the component,
19983                     // then there definitely were no wildcard characters and we do not need to
19984                     // add the exclusion pattern.
19985                     if (componentPattern !== component) {
19986                         subpattern += implicitExcludePathRegexPattern;
19987                     }
19988                     subpattern += componentPattern;
19989                 }
19990                 else {
19991                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
19992                 }
19993             }
19994             hasWrittenComponent = true;
19995         }
19996         while (optionalCount > 0) {
19997             subpattern += ")?";
19998             optionalCount--;
19999         }
20000         return subpattern;
20001     }
20002     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
20003         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
20004     }
20005     /** @param path directory of the tsconfig.json */
20006     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
20007         path = ts.normalizePath(path);
20008         currentDirectory = ts.normalizePath(currentDirectory);
20009         var absolutePath = ts.combinePaths(currentDirectory, path);
20010         return {
20011             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^".concat(pattern, "$"); }),
20012             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
20013             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
20014             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
20015             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
20016         };
20017     }
20018     ts.getFileMatcherPatterns = getFileMatcherPatterns;
20019     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
20020         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
20021     }
20022     ts.getRegexFromPattern = getRegexFromPattern;
20023     /** @param path directory of the tsconfig.json */
20024     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
20025         path = ts.normalizePath(path);
20026         currentDirectory = ts.normalizePath(currentDirectory);
20027         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
20028         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
20029         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
20030         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
20031         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
20032         // If there are no "includes", then just put everything in results[0].
20033         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
20034         var visited = new ts.Map();
20035         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
20036         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
20037             var basePath = _a[_i];
20038             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
20039         }
20040         return ts.flatten(results);
20041         function visitDirectory(path, absolutePath, depth) {
20042             var canonicalPath = toCanonical(realpath(absolutePath));
20043             if (visited.has(canonicalPath))
20044                 return;
20045             visited.set(canonicalPath, true);
20046             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
20047             var _loop_1 = function (current) {
20048                 var name = ts.combinePaths(path, current);
20049                 var absoluteName = ts.combinePaths(absolutePath, current);
20050                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
20051                     return "continue";
20052                 if (excludeRegex && excludeRegex.test(absoluteName))
20053                     return "continue";
20054                 if (!includeFileRegexes) {
20055                     results[0].push(name);
20056                 }
20057                 else {
20058                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
20059                     if (includeIndex !== -1) {
20060                         results[includeIndex].push(name);
20061                     }
20062                 }
20063             };
20064             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
20065                 var current = _b[_i];
20066                 _loop_1(current);
20067             }
20068             if (depth !== undefined) {
20069                 depth--;
20070                 if (depth === 0) {
20071                     return;
20072                 }
20073             }
20074             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
20075                 var current = _d[_c];
20076                 var name = ts.combinePaths(path, current);
20077                 var absoluteName = ts.combinePaths(absolutePath, current);
20078                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
20079                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
20080                     visitDirectory(name, absoluteName, depth);
20081                 }
20082             }
20083         }
20084     }
20085     ts.matchFiles = matchFiles;
20086     /**
20087      * Computes the unique non-wildcard base paths amongst the provided include patterns.
20088      */
20089     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
20090         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
20091         var basePaths = [path];
20092         if (includes) {
20093             // Storage for literal base paths amongst the include patterns.
20094             var includeBasePaths = [];
20095             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
20096                 var include = includes_1[_i];
20097                 // We also need to check the relative paths by converting them to absolute and normalizing
20098                 // in case they escape the base path (e.g "..\somedirectory")
20099                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
20100                 // Append the literal and canonical candidate base paths.
20101                 includeBasePaths.push(getIncludeBasePath(absolute));
20102             }
20103             // Sort the offsets array using either the literal or canonical path representations.
20104             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
20105             var _loop_2 = function (includeBasePath) {
20106                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
20107                     basePaths.push(includeBasePath);
20108                 }
20109             };
20110             // Iterate over each include base path and include unique base paths that are not a
20111             // subpath of an existing base path
20112             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
20113                 var includeBasePath = includeBasePaths_1[_a];
20114                 _loop_2(includeBasePath);
20115             }
20116         }
20117         return basePaths;
20118     }
20119     function getIncludeBasePath(absolute) {
20120         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
20121         if (wildcardOffset < 0) {
20122             // No "*" or "?" in the path
20123             return !ts.hasExtension(absolute)
20124                 ? absolute
20125                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
20126         }
20127         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
20128     }
20129     function ensureScriptKind(fileName, scriptKind) {
20130         // Using scriptKind as a condition handles both:
20131         // - 'scriptKind' is unspecified and thus it is `undefined`
20132         // - 'scriptKind' is set and it is `Unknown` (0)
20133         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
20134         // to get the ScriptKind from the file name. If it cannot be resolved
20135         // from the file name then the default 'TS' script kind is returned.
20136         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
20137     }
20138     ts.ensureScriptKind = ensureScriptKind;
20139     function getScriptKindFromFileName(fileName) {
20140         var ext = fileName.substr(fileName.lastIndexOf("."));
20141         switch (ext.toLowerCase()) {
20142             case ".js" /* Js */:
20143             case ".cjs" /* Cjs */:
20144             case ".mjs" /* Mjs */:
20145                 return 1 /* JS */;
20146             case ".jsx" /* Jsx */:
20147                 return 2 /* JSX */;
20148             case ".ts" /* Ts */:
20149             case ".cts" /* Cts */:
20150             case ".mts" /* Mts */:
20151                 return 3 /* TS */;
20152             case ".tsx" /* Tsx */:
20153                 return 4 /* TSX */;
20154             case ".json" /* Json */:
20155                 return 6 /* JSON */;
20156             default:
20157                 return 0 /* Unknown */;
20158         }
20159     }
20160     ts.getScriptKindFromFileName = getScriptKindFromFileName;
20161     /**
20162      *  Groups of supported extensions in order of file resolution precedence. (eg, TS > TSX > DTS and seperately, CTS > DCTS)
20163      */
20164     ts.supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]];
20165     ts.supportedTSExtensionsFlat = ts.flatten(ts.supportedTSExtensions);
20166     var supportedTSExtensionsWithJson = __spreadArray(__spreadArray([], ts.supportedTSExtensions, true), [[".json" /* Json */]], false);
20167     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
20168     var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */];
20169     ts.supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]];
20170     ts.supportedJSExtensionsFlat = ts.flatten(ts.supportedJSExtensions);
20171     var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]];
20172     var allSupportedExtensionsWithJson = __spreadArray(__spreadArray([], allSupportedExtensions, true), [[".json" /* Json */]], false);
20173     function getSupportedExtensions(options, extraFileExtensions) {
20174         var needJsExtensions = options && getAllowJSCompilerOption(options);
20175         if (!extraFileExtensions || extraFileExtensions.length === 0) {
20176             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
20177         }
20178         var builtins = needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
20179         var flatBuiltins = ts.flatten(builtins);
20180         var extensions = __spreadArray(__spreadArray([], builtins, true), ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension) === -1 ? [x.extension] : undefined; }), true);
20181         return extensions;
20182     }
20183     ts.getSupportedExtensions = getSupportedExtensions;
20184     function getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
20185         if (!options || !options.resolveJsonModule)
20186             return supportedExtensions;
20187         if (supportedExtensions === allSupportedExtensions)
20188             return allSupportedExtensionsWithJson;
20189         if (supportedExtensions === ts.supportedTSExtensions)
20190             return supportedTSExtensionsWithJson;
20191         return __spreadArray(__spreadArray([], supportedExtensions, true), [[".json" /* Json */]], false);
20192     }
20193     ts.getSupportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule;
20194     function isJSLike(scriptKind) {
20195         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
20196     }
20197     function hasJSFileExtension(fileName) {
20198         return ts.some(ts.supportedJSExtensionsFlat, function (extension) { return ts.fileExtensionIs(fileName, extension); });
20199     }
20200     ts.hasJSFileExtension = hasJSFileExtension;
20201     function hasTSFileExtension(fileName) {
20202         return ts.some(ts.supportedTSExtensionsFlat, function (extension) { return ts.fileExtensionIs(fileName, extension); });
20203     }
20204     ts.hasTSFileExtension = hasTSFileExtension;
20205     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
20206         if (!fileName)
20207             return false;
20208         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
20209         for (var _i = 0, _a = ts.flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)); _i < _a.length; _i++) {
20210             var extension = _a[_i];
20211             if (ts.fileExtensionIs(fileName, extension)) {
20212                 return true;
20213             }
20214         }
20215         return false;
20216     }
20217     ts.isSupportedSourceFileName = isSupportedSourceFileName;
20218     function numberOfDirectorySeparators(str) {
20219         var match = str.match(/\//g);
20220         return match ? match.length : 0;
20221     }
20222     function compareNumberOfDirectorySeparators(path1, path2) {
20223         return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2));
20224     }
20225     ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators;
20226     var extensionsToRemove = [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".mjs" /* Mjs */, ".mts" /* Mts */, ".cjs" /* Cjs */, ".cts" /* Cts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
20227     function removeFileExtension(path) {
20228         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
20229             var ext = extensionsToRemove_1[_i];
20230             var extensionless = tryRemoveExtension(path, ext);
20231             if (extensionless !== undefined) {
20232                 return extensionless;
20233             }
20234         }
20235         return path;
20236     }
20237     ts.removeFileExtension = removeFileExtension;
20238     function tryRemoveExtension(path, extension) {
20239         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
20240     }
20241     ts.tryRemoveExtension = tryRemoveExtension;
20242     function removeExtension(path, extension) {
20243         return path.substring(0, path.length - extension.length);
20244     }
20245     ts.removeExtension = removeExtension;
20246     function changeExtension(path, newExtension) {
20247         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
20248     }
20249     ts.changeExtension = changeExtension;
20250     /**
20251      * Returns the input if there are no stars, a pattern if there is exactly one,
20252      * and undefined if there are more.
20253      */
20254     function tryParsePattern(pattern) {
20255         var indexOfStar = pattern.indexOf("*");
20256         if (indexOfStar === -1) {
20257             return pattern;
20258         }
20259         return pattern.indexOf("*", indexOfStar + 1) !== -1
20260             ? undefined
20261             : {
20262                 prefix: pattern.substr(0, indexOfStar),
20263                 suffix: pattern.substr(indexOfStar + 1)
20264             };
20265     }
20266     ts.tryParsePattern = tryParsePattern;
20267     function tryParsePatterns(paths) {
20268         return ts.mapDefined(ts.getOwnKeys(paths), function (path) { return tryParsePattern(path); });
20269     }
20270     ts.tryParsePatterns = tryParsePatterns;
20271     function positionIsSynthesized(pos) {
20272         // This is a fast way of testing the following conditions:
20273         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
20274         return !(pos >= 0);
20275     }
20276     ts.positionIsSynthesized = positionIsSynthesized;
20277     /** True if an extension is one of the supported TypeScript extensions. */
20278     function extensionIsTS(ext) {
20279         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */ || ext === ".cts" /* Cts */ || ext === ".mts" /* Mts */ || ext === ".d.mts" /* Dmts */ || ext === ".d.cts" /* Dcts */;
20280     }
20281     ts.extensionIsTS = extensionIsTS;
20282     function resolutionExtensionIsTSOrJson(ext) {
20283         return extensionIsTS(ext) || ext === ".json" /* Json */;
20284     }
20285     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
20286     /**
20287      * Gets the extension from a path.
20288      * Path must have a valid extension.
20289      */
20290     function extensionFromPath(path) {
20291         var ext = tryGetExtensionFromPath(path);
20292         return ext !== undefined ? ext : ts.Debug.fail("File ".concat(path, " has unknown extension."));
20293     }
20294     ts.extensionFromPath = extensionFromPath;
20295     function isAnySupportedFileExtension(path) {
20296         return tryGetExtensionFromPath(path) !== undefined;
20297     }
20298     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
20299     function tryGetExtensionFromPath(path) {
20300         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
20301     }
20302     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
20303     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
20304         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
20305     }
20306     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
20307     ts.emptyFileSystemEntries = {
20308         files: ts.emptyArray,
20309         directories: ts.emptyArray
20310     };
20311     /**
20312      * patternOrStrings contains both patterns (containing "*") and regular strings.
20313      * Return an exact match if possible, or a pattern match, or undefined.
20314      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
20315      */
20316     function matchPatternOrExact(patternOrStrings, candidate) {
20317         var patterns = [];
20318         for (var _i = 0, patternOrStrings_1 = patternOrStrings; _i < patternOrStrings_1.length; _i++) {
20319             var patternOrString = patternOrStrings_1[_i];
20320             if (patternOrString === candidate) {
20321                 return candidate;
20322             }
20323             if (!ts.isString(patternOrString)) {
20324                 patterns.push(patternOrString);
20325             }
20326         }
20327         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
20328     }
20329     ts.matchPatternOrExact = matchPatternOrExact;
20330     function sliceAfter(arr, value) {
20331         var index = arr.indexOf(value);
20332         ts.Debug.assert(index !== -1);
20333         return arr.slice(index);
20334     }
20335     ts.sliceAfter = sliceAfter;
20336     function addRelatedInfo(diagnostic) {
20337         var _a;
20338         var relatedInformation = [];
20339         for (var _i = 1; _i < arguments.length; _i++) {
20340             relatedInformation[_i - 1] = arguments[_i];
20341         }
20342         if (!relatedInformation.length) {
20343             return diagnostic;
20344         }
20345         if (!diagnostic.relatedInformation) {
20346             diagnostic.relatedInformation = [];
20347         }
20348         ts.Debug.assert(diagnostic.relatedInformation !== ts.emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!");
20349         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
20350         return diagnostic;
20351     }
20352     ts.addRelatedInfo = addRelatedInfo;
20353     function minAndMax(arr, getValue) {
20354         ts.Debug.assert(arr.length !== 0);
20355         var min = getValue(arr[0]);
20356         var max = min;
20357         for (var i = 1; i < arr.length; i++) {
20358             var value = getValue(arr[i]);
20359             if (value < min) {
20360                 min = value;
20361             }
20362             else if (value > max) {
20363                 max = value;
20364             }
20365         }
20366         return { min: min, max: max };
20367     }
20368     ts.minAndMax = minAndMax;
20369     function rangeOfNode(node) {
20370         return { pos: getTokenPosOfNode(node), end: node.end };
20371     }
20372     ts.rangeOfNode = rangeOfNode;
20373     function rangeOfTypeParameters(sourceFile, typeParameters) {
20374         // Include the `<>`
20375         var pos = typeParameters.pos - 1;
20376         var end = ts.skipTrivia(sourceFile.text, typeParameters.end) + 1;
20377         return { pos: pos, end: end };
20378     }
20379     ts.rangeOfTypeParameters = rangeOfTypeParameters;
20380     function skipTypeChecking(sourceFile, options, host) {
20381         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
20382         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
20383         // '/// <reference no-default-lib="true"/>' directive.
20384         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
20385             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
20386             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
20387     }
20388     ts.skipTypeChecking = skipTypeChecking;
20389     function isJsonEqual(a, b) {
20390         // eslint-disable-next-line no-null/no-null
20391         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
20392     }
20393     ts.isJsonEqual = isJsonEqual;
20394     /**
20395      * Converts a bigint literal string, e.g. `0x1234n`,
20396      * to its decimal string representation, e.g. `4660`.
20397      */
20398     function parsePseudoBigInt(stringValue) {
20399         var log2Base;
20400         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
20401             case 98 /* b */:
20402             case 66 /* B */: // 0b or 0B
20403                 log2Base = 1;
20404                 break;
20405             case 111 /* o */:
20406             case 79 /* O */: // 0o or 0O
20407                 log2Base = 3;
20408                 break;
20409             case 120 /* x */:
20410             case 88 /* X */: // 0x or 0X
20411                 log2Base = 4;
20412                 break;
20413             default: // already in decimal; omit trailing "n"
20414                 var nIndex = stringValue.length - 1;
20415                 // Skip leading 0s
20416                 var nonZeroStart = 0;
20417                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
20418                     nonZeroStart++;
20419                 }
20420                 return stringValue.slice(nonZeroStart, nIndex) || "0";
20421         }
20422         // Omit leading "0b", "0o", or "0x", and trailing "n"
20423         var startIndex = 2, endIndex = stringValue.length - 1;
20424         var bitsNeeded = (endIndex - startIndex) * log2Base;
20425         // Stores the value specified by the string as a LE array of 16-bit integers
20426         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
20427         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
20428         // Add the digits, one at a time
20429         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
20430             var segment = bitOffset >>> 4;
20431             var digitChar = stringValue.charCodeAt(i);
20432             // Find character range: 0-9 < A-F < a-f
20433             var digit = digitChar <= 57 /* _9 */
20434                 ? digitChar - 48 /* _0 */
20435                 : 10 + digitChar -
20436                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
20437             var shiftedDigit = digit << (bitOffset & 15);
20438             segments[segment] |= shiftedDigit;
20439             var residual = shiftedDigit >>> 16;
20440             if (residual)
20441                 segments[segment + 1] |= residual; // overflows segment
20442         }
20443         // Repeatedly divide segments by 10 and add remainder to base10Value
20444         var base10Value = "";
20445         var firstNonzeroSegment = segments.length - 1;
20446         var segmentsRemaining = true;
20447         while (segmentsRemaining) {
20448             var mod10 = 0;
20449             segmentsRemaining = false;
20450             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
20451                 var newSegment = mod10 << 16 | segments[segment];
20452                 var segmentValue = (newSegment / 10) | 0;
20453                 segments[segment] = segmentValue;
20454                 mod10 = newSegment - segmentValue * 10;
20455                 if (segmentValue && !segmentsRemaining) {
20456                     firstNonzeroSegment = segment;
20457                     segmentsRemaining = true;
20458                 }
20459             }
20460             base10Value = mod10 + base10Value;
20461         }
20462         return base10Value;
20463     }
20464     ts.parsePseudoBigInt = parsePseudoBigInt;
20465     function pseudoBigIntToString(_a) {
20466         var negative = _a.negative, base10Value = _a.base10Value;
20467         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
20468     }
20469     ts.pseudoBigIntToString = pseudoBigIntToString;
20470     function isValidTypeOnlyAliasUseSite(useSite) {
20471         return !!(useSite.flags & 8388608 /* Ambient */)
20472             || isPartOfTypeQuery(useSite)
20473             || isIdentifierInNonEmittingHeritageClause(useSite)
20474             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
20475             || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite));
20476     }
20477     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
20478     function isShorthandPropertyNameUseSite(useSite) {
20479         return ts.isIdentifier(useSite) && ts.isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite;
20480     }
20481     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
20482         while (node.kind === 79 /* Identifier */ || node.kind === 205 /* PropertyAccessExpression */) {
20483             node = node.parent;
20484         }
20485         if (node.kind !== 161 /* ComputedPropertyName */) {
20486             return false;
20487         }
20488         if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
20489             return true;
20490         }
20491         var containerKind = node.parent.parent.kind;
20492         return containerKind === 257 /* InterfaceDeclaration */ || containerKind === 181 /* TypeLiteral */;
20493     }
20494     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
20495     function isIdentifierInNonEmittingHeritageClause(node) {
20496         if (node.kind !== 79 /* Identifier */)
20497             return false;
20498         var heritageClause = ts.findAncestor(node.parent, function (parent) {
20499             switch (parent.kind) {
20500                 case 290 /* HeritageClause */:
20501                     return true;
20502                 case 205 /* PropertyAccessExpression */:
20503                 case 227 /* ExpressionWithTypeArguments */:
20504                     return false;
20505                 default:
20506                     return "quit";
20507             }
20508         });
20509         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 117 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 257 /* InterfaceDeclaration */;
20510     }
20511     function isIdentifierTypeReference(node) {
20512         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
20513     }
20514     ts.isIdentifierTypeReference = isIdentifierTypeReference;
20515     function arrayIsHomogeneous(array, comparer) {
20516         if (comparer === void 0) { comparer = ts.equateValues; }
20517         if (array.length < 2)
20518             return true;
20519         var first = array[0];
20520         for (var i = 1, length_1 = array.length; i < length_1; i++) {
20521             var target = array[i];
20522             if (!comparer(first, target))
20523                 return false;
20524         }
20525         return true;
20526     }
20527     ts.arrayIsHomogeneous = arrayIsHomogeneous;
20528     /**
20529      * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
20530      */
20531     /* @internal */
20532     function setTextRangePos(range, pos) {
20533         range.pos = pos;
20534         return range;
20535     }
20536     ts.setTextRangePos = setTextRangePos;
20537     /**
20538      * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
20539      */
20540     /* @internal */
20541     function setTextRangeEnd(range, end) {
20542         range.end = end;
20543         return range;
20544     }
20545     ts.setTextRangeEnd = setTextRangeEnd;
20546     /**
20547      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
20548      */
20549     /* @internal */
20550     function setTextRangePosEnd(range, pos, end) {
20551         return setTextRangeEnd(setTextRangePos(range, pos), end);
20552     }
20553     ts.setTextRangePosEnd = setTextRangePosEnd;
20554     /**
20555      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
20556      * provided position and width.
20557      */
20558     /* @internal */
20559     function setTextRangePosWidth(range, pos, width) {
20560         return setTextRangePosEnd(range, pos, pos + width);
20561     }
20562     ts.setTextRangePosWidth = setTextRangePosWidth;
20563     function setNodeFlags(node, newFlags) {
20564         if (node) {
20565             node.flags = newFlags;
20566         }
20567         return node;
20568     }
20569     ts.setNodeFlags = setNodeFlags;
20570     function setParent(child, parent) {
20571         if (child && parent) {
20572             child.parent = parent;
20573         }
20574         return child;
20575     }
20576     ts.setParent = setParent;
20577     function setEachParent(children, parent) {
20578         if (children) {
20579             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
20580                 var child = children_1[_i];
20581                 setParent(child, parent);
20582             }
20583         }
20584         return children;
20585     }
20586     ts.setEachParent = setEachParent;
20587     function setParentRecursive(rootNode, incremental) {
20588         if (!rootNode)
20589             return rootNode;
20590         ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
20591         return rootNode;
20592         function bindParentToChildIgnoringJSDoc(child, parent) {
20593             if (incremental && child.parent === parent) {
20594                 return "skip";
20595             }
20596             setParent(child, parent);
20597         }
20598         function bindJSDoc(child) {
20599             if (ts.hasJSDocNodes(child)) {
20600                 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
20601                     var doc = _a[_i];
20602                     bindParentToChildIgnoringJSDoc(doc, child);
20603                     ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
20604                 }
20605             }
20606         }
20607         function bindParentToChild(child, parent) {
20608             return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
20609         }
20610     }
20611     ts.setParentRecursive = setParentRecursive;
20612     function isPackedElement(node) {
20613         return !ts.isOmittedExpression(node);
20614     }
20615     /**
20616      * Determines whether the provided node is an ArrayLiteralExpression that contains no missing elements.
20617      */
20618     function isPackedArrayLiteral(node) {
20619         return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
20620     }
20621     ts.isPackedArrayLiteral = isPackedArrayLiteral;
20622     /**
20623      * Indicates whether the result of an `Expression` will be unused.
20624      *
20625      * NOTE: This requires a node with a valid `parent` pointer.
20626      */
20627     function expressionResultIsUnused(node) {
20628         ts.Debug.assertIsDefined(node.parent);
20629         while (true) {
20630             var parent = node.parent;
20631             // walk up parenthesized expressions, but keep a pointer to the top-most parenthesized expression
20632             if (ts.isParenthesizedExpression(parent)) {
20633                 node = parent;
20634                 continue;
20635             }
20636             // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop
20637             if (ts.isExpressionStatement(parent) ||
20638                 ts.isVoidExpression(parent) ||
20639                 ts.isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) {
20640                 return true;
20641             }
20642             if (ts.isCommaListExpression(parent)) {
20643                 // left side of comma is always unused
20644                 if (node !== ts.last(parent.elements))
20645                     return true;
20646                 // right side of comma is unused if parent is unused
20647                 node = parent;
20648                 continue;
20649             }
20650             if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 27 /* CommaToken */) {
20651                 // left side of comma is always unused
20652                 if (node === parent.left)
20653                     return true;
20654                 // right side of comma is unused if parent is unused
20655                 node = parent;
20656                 continue;
20657             }
20658             return false;
20659         }
20660     }
20661     ts.expressionResultIsUnused = expressionResultIsUnused;
20662     function containsIgnoredPath(path) {
20663         return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); });
20664     }
20665     ts.containsIgnoredPath = containsIgnoredPath;
20666     function getContainingNodeArray(node) {
20667         if (!node.parent)
20668             return undefined;
20669         switch (node.kind) {
20670             case 162 /* TypeParameter */:
20671                 var parent_1 = node.parent;
20672                 return parent_1.kind === 189 /* InferType */ ? undefined : parent_1.typeParameters;
20673             case 163 /* Parameter */:
20674                 return node.parent.parameters;
20675             case 198 /* TemplateLiteralTypeSpan */:
20676                 return node.parent.templateSpans;
20677             case 232 /* TemplateSpan */:
20678                 return node.parent.templateSpans;
20679             case 164 /* Decorator */:
20680                 return node.parent.decorators;
20681             case 290 /* HeritageClause */:
20682                 return node.parent.heritageClauses;
20683         }
20684         var parent = node.parent;
20685         if (ts.isJSDocTag(node)) {
20686             return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags;
20687         }
20688         switch (parent.kind) {
20689             case 181 /* TypeLiteral */:
20690             case 257 /* InterfaceDeclaration */:
20691                 return ts.isTypeElement(node) ? parent.members : undefined;
20692             case 186 /* UnionType */:
20693             case 187 /* IntersectionType */:
20694                 return parent.types;
20695             case 183 /* TupleType */:
20696             case 203 /* ArrayLiteralExpression */:
20697             case 349 /* CommaListExpression */:
20698             case 268 /* NamedImports */:
20699             case 272 /* NamedExports */:
20700                 return parent.elements;
20701             case 204 /* ObjectLiteralExpression */:
20702             case 285 /* JsxAttributes */:
20703                 return parent.properties;
20704             case 207 /* CallExpression */:
20705             case 208 /* NewExpression */:
20706                 return ts.isTypeNode(node) ? parent.typeArguments :
20707                     parent.expression === node ? undefined :
20708                         parent.arguments;
20709             case 277 /* JsxElement */:
20710             case 281 /* JsxFragment */:
20711                 return ts.isJsxChild(node) ? parent.children : undefined;
20712             case 279 /* JsxOpeningElement */:
20713             case 278 /* JsxSelfClosingElement */:
20714                 return ts.isTypeNode(node) ? parent.typeArguments : undefined;
20715             case 234 /* Block */:
20716             case 288 /* CaseClause */:
20717             case 289 /* DefaultClause */:
20718             case 261 /* ModuleBlock */:
20719                 return parent.statements;
20720             case 262 /* CaseBlock */:
20721                 return parent.clauses;
20722             case 256 /* ClassDeclaration */:
20723             case 225 /* ClassExpression */:
20724                 return ts.isClassElement(node) ? parent.members : undefined;
20725             case 259 /* EnumDeclaration */:
20726                 return ts.isEnumMember(node) ? parent.members : undefined;
20727             case 303 /* SourceFile */:
20728                 return parent.statements;
20729         }
20730     }
20731     ts.getContainingNodeArray = getContainingNodeArray;
20732     function hasContextSensitiveParameters(node) {
20733         // Functions with type parameters are not context sensitive.
20734         if (!node.typeParameters) {
20735             // Functions with any parameters that lack type annotations are context sensitive.
20736             if (ts.some(node.parameters, function (p) { return !getEffectiveTypeAnnotationNode(p); })) {
20737                 return true;
20738             }
20739             if (node.kind !== 213 /* ArrowFunction */) {
20740                 // If the first parameter is not an explicit 'this' parameter, then the function has
20741                 // an implicit 'this' parameter which is subject to contextual typing.
20742                 var parameter = ts.firstOrUndefined(node.parameters);
20743                 if (!(parameter && parameterIsThisKeyword(parameter))) {
20744                     return true;
20745                 }
20746             }
20747         }
20748         return false;
20749     }
20750     ts.hasContextSensitiveParameters = hasContextSensitiveParameters;
20751     /* @internal */
20752     function isInfinityOrNaNString(name) {
20753         return name === "Infinity" || name === "-Infinity" || name === "NaN";
20754     }
20755     ts.isInfinityOrNaNString = isInfinityOrNaNString;
20756     function isCatchClauseVariableDeclaration(node) {
20757         return node.kind === 253 /* VariableDeclaration */ && node.parent.kind === 291 /* CatchClause */;
20758     }
20759     ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration;
20760     function isParameterOrCatchClauseVariable(symbol) {
20761         var declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration);
20762         return !!declaration && (ts.isParameter(declaration) || isCatchClauseVariableDeclaration(declaration));
20763     }
20764     ts.isParameterOrCatchClauseVariable = isParameterOrCatchClauseVariable;
20765     function isFunctionExpressionOrArrowFunction(node) {
20766         return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */;
20767     }
20768     ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction;
20769     function escapeSnippetText(text) {
20770         return text.replace(/\$/gm, "\\$");
20771     }
20772     ts.escapeSnippetText = escapeSnippetText;
20773 })(ts || (ts = {}));
20774 /* @internal */
20775 var ts;
20776 (function (ts) {
20777     /**
20778      * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
20779      */
20780     function createBaseNodeFactory() {
20781         // tslint:disable variable-name
20782         var NodeConstructor;
20783         var TokenConstructor;
20784         var IdentifierConstructor;
20785         var PrivateIdentifierConstructor;
20786         var SourceFileConstructor;
20787         // tslint:enable variable-name
20788         return {
20789             createBaseSourceFileNode: createBaseSourceFileNode,
20790             createBaseIdentifierNode: createBaseIdentifierNode,
20791             createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
20792             createBaseTokenNode: createBaseTokenNode,
20793             createBaseNode: createBaseNode
20794         };
20795         function createBaseSourceFileNode(kind) {
20796             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
20797         }
20798         function createBaseIdentifierNode(kind) {
20799             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
20800         }
20801         function createBasePrivateIdentifierNode(kind) {
20802             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
20803         }
20804         function createBaseTokenNode(kind) {
20805             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
20806         }
20807         function createBaseNode(kind) {
20808             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
20809         }
20810     }
20811     ts.createBaseNodeFactory = createBaseNodeFactory;
20812 })(ts || (ts = {}));
20813 /* @internal */
20814 var ts;
20815 (function (ts) {
20816     function createParenthesizerRules(factory) {
20817         var binaryLeftOperandParenthesizerCache;
20818         var binaryRightOperandParenthesizerCache;
20819         return {
20820             getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator,
20821             getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator,
20822             parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
20823             parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
20824             parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
20825             parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
20826             parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
20827             parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
20828             parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
20829             parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
20830             parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
20831             parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
20832             parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
20833             parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
20834             parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
20835             parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
20836             parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
20837             parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
20838             parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
20839             parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
20840             parenthesizeTypeArguments: parenthesizeTypeArguments,
20841         };
20842         function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) {
20843             binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map());
20844             var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind);
20845             if (!parenthesizerRule) {
20846                 parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); };
20847                 binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
20848             }
20849             return parenthesizerRule;
20850         }
20851         function getParenthesizeRightSideOfBinaryForOperator(operatorKind) {
20852             binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map());
20853             var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind);
20854             if (!parenthesizerRule) {
20855                 parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); };
20856                 binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule);
20857             }
20858             return parenthesizerRule;
20859         }
20860         /**
20861          * Determines whether the operand to a BinaryExpression needs to be parenthesized.
20862          *
20863          * @param binaryOperator The operator for the BinaryExpression.
20864          * @param operand The operand for the BinaryExpression.
20865          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
20866          *                           BinaryExpression.
20867          */
20868         function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
20869             // If the operand has lower precedence, then it needs to be parenthesized to preserve the
20870             // intent of the expression. For example, if the operand is `a + b` and the operator is
20871             // `*`, then we need to parenthesize the operand to preserve the intended order of
20872             // operations: `(a + b) * x`.
20873             //
20874             // If the operand has higher precedence, then it does not need to be parenthesized. For
20875             // example, if the operand is `a * b` and the operator is `+`, then we do not need to
20876             // parenthesize to preserve the intended order of operations: `a * b + x`.
20877             //
20878             // If the operand has the same precedence, then we need to check the associativity of
20879             // the operator based on whether this is the left or right operand of the expression.
20880             //
20881             // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
20882             // to preserve the intended order of operations: `x * (a / d)`
20883             //
20884             // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
20885             // the intended order of operations: `(a ** b) ** c`
20886             var binaryOperatorPrecedence = ts.getOperatorPrecedence(220 /* BinaryExpression */, binaryOperator);
20887             var binaryOperatorAssociativity = ts.getOperatorAssociativity(220 /* BinaryExpression */, binaryOperator);
20888             var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
20889             if (!isLeftSideOfBinary && operand.kind === 213 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
20890                 // We need to parenthesize arrow functions on the right side to avoid it being
20891                 // parsed as parenthesized expression: `a && (() => {})`
20892                 return true;
20893             }
20894             var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
20895             switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
20896                 case -1 /* LessThan */:
20897                     // If the operand is the right side of a right-associative binary operation
20898                     // and is a yield expression, then we do not need parentheses.
20899                     if (!isLeftSideOfBinary
20900                         && binaryOperatorAssociativity === 1 /* Right */
20901                         && operand.kind === 223 /* YieldExpression */) {
20902                         return false;
20903                     }
20904                     return true;
20905                 case 1 /* GreaterThan */:
20906                     return false;
20907                 case 0 /* EqualTo */:
20908                     if (isLeftSideOfBinary) {
20909                         // No need to parenthesize the left operand when the binary operator is
20910                         // left associative:
20911                         //  (a*b)/x    -> a*b/x
20912                         //  (a**b)/x   -> a**b/x
20913                         //
20914                         // Parentheses are needed for the left operand when the binary operator is
20915                         // right associative:
20916                         //  (a/b)**x   -> (a/b)**x
20917                         //  (a**b)**x  -> (a**b)**x
20918                         return binaryOperatorAssociativity === 1 /* Right */;
20919                     }
20920                     else {
20921                         if (ts.isBinaryExpression(emittedOperand)
20922                             && emittedOperand.operatorToken.kind === binaryOperator) {
20923                             // No need to parenthesize the right operand when the binary operator and
20924                             // operand are the same and one of the following:
20925                             //  x*(a*b)     => x*a*b
20926                             //  x|(a|b)     => x|a|b
20927                             //  x&(a&b)     => x&a&b
20928                             //  x^(a^b)     => x^a^b
20929                             if (operatorHasAssociativeProperty(binaryOperator)) {
20930                                 return false;
20931                             }
20932                             // No need to parenthesize the right operand when the binary operator
20933                             // is plus (+) if both the left and right operands consist solely of either
20934                             // literals of the same kind or binary plus (+) expressions for literals of
20935                             // the same kind (recursively).
20936                             //  "a"+(1+2)       => "a"+(1+2)
20937                             //  "a"+("b"+"c")   => "a"+"b"+"c"
20938                             if (binaryOperator === 39 /* PlusToken */) {
20939                                 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
20940                                 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
20941                                     return false;
20942                                 }
20943                             }
20944                         }
20945                         // No need to parenthesize the right operand when the operand is right
20946                         // associative:
20947                         //  x/(a**b)    -> x/a**b
20948                         //  x**(a**b)   -> x**a**b
20949                         //
20950                         // Parentheses are needed for the right operand when the operand is left
20951                         // associative:
20952                         //  x/(a*b)     -> x/(a*b)
20953                         //  x**(a/b)    -> x**(a/b)
20954                         var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
20955                         return operandAssociativity === 0 /* Left */;
20956                     }
20957             }
20958         }
20959         /**
20960          * Determines whether a binary operator is mathematically associative.
20961          *
20962          * @param binaryOperator The binary operator.
20963          */
20964         function operatorHasAssociativeProperty(binaryOperator) {
20965             // The following operators are associative in JavaScript:
20966             //  (a*b)*c     -> a*(b*c)  -> a*b*c
20967             //  (a|b)|c     -> a|(b|c)  -> a|b|c
20968             //  (a&b)&c     -> a&(b&c)  -> a&b&c
20969             //  (a^b)^c     -> a^(b^c)  -> a^b^c
20970             //
20971             // While addition is associative in mathematics, JavaScript's `+` is not
20972             // guaranteed to be associative as it is overloaded with string concatenation.
20973             return binaryOperator === 41 /* AsteriskToken */
20974                 || binaryOperator === 51 /* BarToken */
20975                 || binaryOperator === 50 /* AmpersandToken */
20976                 || binaryOperator === 52 /* CaretToken */;
20977         }
20978         /**
20979          * This function determines whether an expression consists of a homogeneous set of
20980          * literal expressions or binary plus expressions that all share the same literal kind.
20981          * It is used to determine whether the right-hand operand of a binary plus expression can be
20982          * emitted without parentheses.
20983          */
20984         function getLiteralKindOfBinaryPlusOperand(node) {
20985             node = ts.skipPartiallyEmittedExpressions(node);
20986             if (ts.isLiteralKind(node.kind)) {
20987                 return node.kind;
20988             }
20989             if (node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
20990                 if (node.cachedLiteralKind !== undefined) {
20991                     return node.cachedLiteralKind;
20992                 }
20993                 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
20994                 var literalKind = ts.isLiteralKind(leftKind)
20995                     && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
20996                     ? leftKind
20997                     : 0 /* Unknown */;
20998                 node.cachedLiteralKind = literalKind;
20999                 return literalKind;
21000             }
21001             return 0 /* Unknown */;
21002         }
21003         /**
21004          * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
21005          * order of operations.
21006          *
21007          * @param binaryOperator The operator for the BinaryExpression.
21008          * @param operand The operand for the BinaryExpression.
21009          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
21010          *                           BinaryExpression.
21011          */
21012         function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
21013             var skipped = ts.skipPartiallyEmittedExpressions(operand);
21014             // If the resulting expression is already parenthesized, we do not need to do any further processing.
21015             if (skipped.kind === 211 /* ParenthesizedExpression */) {
21016                 return operand;
21017             }
21018             return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
21019                 ? factory.createParenthesizedExpression(operand)
21020                 : operand;
21021         }
21022         function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
21023             return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
21024         }
21025         function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
21026             return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
21027         }
21028         function parenthesizeExpressionOfComputedPropertyName(expression) {
21029             return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
21030         }
21031         function parenthesizeConditionOfConditionalExpression(condition) {
21032             var conditionalPrecedence = ts.getOperatorPrecedence(221 /* ConditionalExpression */, 57 /* QuestionToken */);
21033             var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
21034             var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
21035             if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
21036                 return factory.createParenthesizedExpression(condition);
21037             }
21038             return condition;
21039         }
21040         function parenthesizeBranchOfConditionalExpression(branch) {
21041             // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
21042             // so in case when comma expression is introduced as a part of previous transformations
21043             // if should be wrapped in parens since comma operator has the lowest precedence
21044             var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
21045             return ts.isCommaSequence(emittedExpression)
21046                 ? factory.createParenthesizedExpression(branch)
21047                 : branch;
21048         }
21049         /**
21050          *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
21051          *  has a lookahead restriction for `function`, `async function`, and `class`.
21052          *
21053          * Basically, that means we need to parenthesize in the following cases:
21054          *
21055          * - BinaryExpression of CommaToken
21056          * - CommaList (synthetic list of multiple comma expressions)
21057          * - FunctionExpression
21058          * - ClassExpression
21059          */
21060         function parenthesizeExpressionOfExportDefault(expression) {
21061             var check = ts.skipPartiallyEmittedExpressions(expression);
21062             var needsParens = ts.isCommaSequence(check);
21063             if (!needsParens) {
21064                 switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
21065                     case 225 /* ClassExpression */:
21066                     case 212 /* FunctionExpression */:
21067                         needsParens = true;
21068                 }
21069             }
21070             return needsParens ? factory.createParenthesizedExpression(expression) : expression;
21071         }
21072         /**
21073          * Wraps an expression in parentheses if it is needed in order to use the expression
21074          * as the expression of a `NewExpression` node.
21075          */
21076         function parenthesizeExpressionOfNew(expression) {
21077             var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
21078             switch (leftmostExpr.kind) {
21079                 case 207 /* CallExpression */:
21080                     return factory.createParenthesizedExpression(expression);
21081                 case 208 /* NewExpression */:
21082                     return !leftmostExpr.arguments
21083                         ? factory.createParenthesizedExpression(expression)
21084                         : expression; // TODO(rbuckton): Verify this assertion holds
21085             }
21086             return parenthesizeLeftSideOfAccess(expression);
21087         }
21088         /**
21089          * Wraps an expression in parentheses if it is needed in order to use the expression for
21090          * property or element access.
21091          */
21092         function parenthesizeLeftSideOfAccess(expression) {
21093             // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
21094             // to parenthesize the expression before a dot. The known exception is:
21095             //
21096             //    NewExpression:
21097             //       new C.x        -> not the same as (new C).x
21098             //
21099             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
21100             if (ts.isLeftHandSideExpression(emittedExpression)
21101                 && (emittedExpression.kind !== 208 /* NewExpression */ || emittedExpression.arguments)) {
21102                 // TODO(rbuckton): Verify whether this assertion holds.
21103                 return expression;
21104             }
21105             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21106             return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
21107         }
21108         function parenthesizeOperandOfPostfixUnary(operand) {
21109             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21110             return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
21111         }
21112         function parenthesizeOperandOfPrefixUnary(operand) {
21113             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21114             return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
21115         }
21116         function parenthesizeExpressionsOfCommaDelimitedList(elements) {
21117             var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
21118             return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
21119         }
21120         function parenthesizeExpressionForDisallowedComma(expression) {
21121             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
21122             var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
21123             var commaPrecedence = ts.getOperatorPrecedence(220 /* BinaryExpression */, 27 /* CommaToken */);
21124             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21125             return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
21126         }
21127         function parenthesizeExpressionOfExpressionStatement(expression) {
21128             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
21129             if (ts.isCallExpression(emittedExpression)) {
21130                 var callee = emittedExpression.expression;
21131                 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
21132                 if (kind === 212 /* FunctionExpression */ || kind === 213 /* ArrowFunction */) {
21133                     // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21134                     var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
21135                     return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
21136                 }
21137             }
21138             var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
21139             if (leftmostExpressionKind === 204 /* ObjectLiteralExpression */ || leftmostExpressionKind === 212 /* FunctionExpression */) {
21140                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21141                 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
21142             }
21143             return expression;
21144         }
21145         function parenthesizeConciseBodyOfArrowFunction(body) {
21146             if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 204 /* ObjectLiteralExpression */)) {
21147                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
21148                 return ts.setTextRange(factory.createParenthesizedExpression(body), body);
21149             }
21150             return body;
21151         }
21152         function parenthesizeMemberOfConditionalType(member) {
21153             return member.kind === 188 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
21154         }
21155         function parenthesizeMemberOfElementType(member) {
21156             switch (member.kind) {
21157                 case 186 /* UnionType */:
21158                 case 187 /* IntersectionType */:
21159                 case 178 /* FunctionType */:
21160                 case 179 /* ConstructorType */:
21161                     return factory.createParenthesizedType(member);
21162             }
21163             return parenthesizeMemberOfConditionalType(member);
21164         }
21165         function parenthesizeElementTypeOfArrayType(member) {
21166             switch (member.kind) {
21167                 case 180 /* TypeQuery */:
21168                 case 192 /* TypeOperator */:
21169                 case 189 /* InferType */:
21170                     return factory.createParenthesizedType(member);
21171             }
21172             return parenthesizeMemberOfElementType(member);
21173         }
21174         function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
21175             return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
21176         }
21177         function parenthesizeOrdinalTypeArgument(node, i) {
21178             return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
21179         }
21180         function parenthesizeTypeArguments(typeArguments) {
21181             if (ts.some(typeArguments)) {
21182                 return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
21183             }
21184         }
21185     }
21186     ts.createParenthesizerRules = createParenthesizerRules;
21187     ts.nullParenthesizerRules = {
21188         getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; },
21189         getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; },
21190         parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
21191         parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
21192         parenthesizeExpressionOfComputedPropertyName: ts.identity,
21193         parenthesizeConditionOfConditionalExpression: ts.identity,
21194         parenthesizeBranchOfConditionalExpression: ts.identity,
21195         parenthesizeExpressionOfExportDefault: ts.identity,
21196         parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
21197         parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
21198         parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
21199         parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
21200         parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
21201         parenthesizeExpressionForDisallowedComma: ts.identity,
21202         parenthesizeExpressionOfExpressionStatement: ts.identity,
21203         parenthesizeConciseBodyOfArrowFunction: ts.identity,
21204         parenthesizeMemberOfConditionalType: ts.identity,
21205         parenthesizeMemberOfElementType: ts.identity,
21206         parenthesizeElementTypeOfArrayType: ts.identity,
21207         parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
21208         parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
21209     };
21210 })(ts || (ts = {}));
21211 /* @internal */
21212 var ts;
21213 (function (ts) {
21214     function createNodeConverters(factory) {
21215         return {
21216             convertToFunctionBlock: convertToFunctionBlock,
21217             convertToFunctionExpression: convertToFunctionExpression,
21218             convertToArrayAssignmentElement: convertToArrayAssignmentElement,
21219             convertToObjectAssignmentElement: convertToObjectAssignmentElement,
21220             convertToAssignmentPattern: convertToAssignmentPattern,
21221             convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
21222             convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
21223             convertToAssignmentElementTarget: convertToAssignmentElementTarget,
21224         };
21225         function convertToFunctionBlock(node, multiLine) {
21226             if (ts.isBlock(node))
21227                 return node;
21228             var returnStatement = factory.createReturnStatement(node);
21229             ts.setTextRange(returnStatement, node);
21230             var body = factory.createBlock([returnStatement], multiLine);
21231             ts.setTextRange(body, node);
21232             return body;
21233         }
21234         function convertToFunctionExpression(node) {
21235             if (!node.body)
21236                 return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
21237             var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
21238             ts.setOriginalNode(updated, node);
21239             ts.setTextRange(updated, node);
21240             if (ts.getStartsOnNewLine(node)) {
21241                 ts.setStartsOnNewLine(updated, /*newLine*/ true);
21242             }
21243             return updated;
21244         }
21245         function convertToArrayAssignmentElement(element) {
21246             if (ts.isBindingElement(element)) {
21247                 if (element.dotDotDotToken) {
21248                     ts.Debug.assertNode(element.name, ts.isIdentifier);
21249                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
21250                 }
21251                 var expression = convertToAssignmentElementTarget(element.name);
21252                 return element.initializer
21253                     ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
21254                     : expression;
21255             }
21256             return ts.cast(element, ts.isExpression);
21257         }
21258         function convertToObjectAssignmentElement(element) {
21259             if (ts.isBindingElement(element)) {
21260                 if (element.dotDotDotToken) {
21261                     ts.Debug.assertNode(element.name, ts.isIdentifier);
21262                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
21263                 }
21264                 if (element.propertyName) {
21265                     var expression = convertToAssignmentElementTarget(element.name);
21266                     return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
21267                 }
21268                 ts.Debug.assertNode(element.name, ts.isIdentifier);
21269                 return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
21270             }
21271             return ts.cast(element, ts.isObjectLiteralElementLike);
21272         }
21273         function convertToAssignmentPattern(node) {
21274             switch (node.kind) {
21275                 case 201 /* ArrayBindingPattern */:
21276                 case 203 /* ArrayLiteralExpression */:
21277                     return convertToArrayAssignmentPattern(node);
21278                 case 200 /* ObjectBindingPattern */:
21279                 case 204 /* ObjectLiteralExpression */:
21280                     return convertToObjectAssignmentPattern(node);
21281             }
21282         }
21283         function convertToObjectAssignmentPattern(node) {
21284             if (ts.isObjectBindingPattern(node)) {
21285                 return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
21286             }
21287             return ts.cast(node, ts.isObjectLiteralExpression);
21288         }
21289         function convertToArrayAssignmentPattern(node) {
21290             if (ts.isArrayBindingPattern(node)) {
21291                 return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
21292             }
21293             return ts.cast(node, ts.isArrayLiteralExpression);
21294         }
21295         function convertToAssignmentElementTarget(node) {
21296             if (ts.isBindingPattern(node)) {
21297                 return convertToAssignmentPattern(node);
21298             }
21299             return ts.cast(node, ts.isExpression);
21300         }
21301     }
21302     ts.createNodeConverters = createNodeConverters;
21303     ts.nullNodeConverters = {
21304         convertToFunctionBlock: ts.notImplemented,
21305         convertToFunctionExpression: ts.notImplemented,
21306         convertToArrayAssignmentElement: ts.notImplemented,
21307         convertToObjectAssignmentElement: ts.notImplemented,
21308         convertToAssignmentPattern: ts.notImplemented,
21309         convertToObjectAssignmentPattern: ts.notImplemented,
21310         convertToArrayAssignmentPattern: ts.notImplemented,
21311         convertToAssignmentElementTarget: ts.notImplemented,
21312     };
21313 })(ts || (ts = {}));
21314 var ts;
21315 (function (ts) {
21316     var nextAutoGenerateId = 0;
21317     /* @internal */
21318     var NodeFactoryFlags;
21319     (function (NodeFactoryFlags) {
21320         NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
21321         // Disables the parenthesizer rules for the factory.
21322         NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
21323         // Disables the node converters for the factory.
21324         NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
21325         // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
21326         NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
21327         // Do not set an `original` pointer when updating a node.
21328         NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
21329     })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
21330     /**
21331      * Creates a `NodeFactory` that can be used to create and update a syntax tree.
21332      * @param flags Flags that control factory behavior.
21333      * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
21334      */
21335     /* @internal */
21336     function createNodeFactory(flags, baseFactory) {
21337         var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
21338         // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
21339         var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
21340         var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
21341         // lazy initializaton of common operator factories
21342         var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
21343         var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
21344         var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
21345         var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
21346         var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
21347         var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
21348         var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
21349         var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
21350         var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
21351         var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
21352         var factory = {
21353             get parenthesizer() { return parenthesizerRules(); },
21354             get converters() { return converters(); },
21355             createNodeArray: createNodeArray,
21356             createNumericLiteral: createNumericLiteral,
21357             createBigIntLiteral: createBigIntLiteral,
21358             createStringLiteral: createStringLiteral,
21359             createStringLiteralFromNode: createStringLiteralFromNode,
21360             createRegularExpressionLiteral: createRegularExpressionLiteral,
21361             createLiteralLikeNode: createLiteralLikeNode,
21362             createIdentifier: createIdentifier,
21363             updateIdentifier: updateIdentifier,
21364             createTempVariable: createTempVariable,
21365             createLoopVariable: createLoopVariable,
21366             createUniqueName: createUniqueName,
21367             getGeneratedNameForNode: getGeneratedNameForNode,
21368             createPrivateIdentifier: createPrivateIdentifier,
21369             createToken: createToken,
21370             createSuper: createSuper,
21371             createThis: createThis,
21372             createNull: createNull,
21373             createTrue: createTrue,
21374             createFalse: createFalse,
21375             createModifier: createModifier,
21376             createModifiersFromModifierFlags: createModifiersFromModifierFlags,
21377             createQualifiedName: createQualifiedName,
21378             updateQualifiedName: updateQualifiedName,
21379             createComputedPropertyName: createComputedPropertyName,
21380             updateComputedPropertyName: updateComputedPropertyName,
21381             createTypeParameterDeclaration: createTypeParameterDeclaration,
21382             updateTypeParameterDeclaration: updateTypeParameterDeclaration,
21383             createParameterDeclaration: createParameterDeclaration,
21384             updateParameterDeclaration: updateParameterDeclaration,
21385             createDecorator: createDecorator,
21386             updateDecorator: updateDecorator,
21387             createPropertySignature: createPropertySignature,
21388             updatePropertySignature: updatePropertySignature,
21389             createPropertyDeclaration: createPropertyDeclaration,
21390             updatePropertyDeclaration: updatePropertyDeclaration,
21391             createMethodSignature: createMethodSignature,
21392             updateMethodSignature: updateMethodSignature,
21393             createMethodDeclaration: createMethodDeclaration,
21394             updateMethodDeclaration: updateMethodDeclaration,
21395             createConstructorDeclaration: createConstructorDeclaration,
21396             updateConstructorDeclaration: updateConstructorDeclaration,
21397             createGetAccessorDeclaration: createGetAccessorDeclaration,
21398             updateGetAccessorDeclaration: updateGetAccessorDeclaration,
21399             createSetAccessorDeclaration: createSetAccessorDeclaration,
21400             updateSetAccessorDeclaration: updateSetAccessorDeclaration,
21401             createCallSignature: createCallSignature,
21402             updateCallSignature: updateCallSignature,
21403             createConstructSignature: createConstructSignature,
21404             updateConstructSignature: updateConstructSignature,
21405             createIndexSignature: createIndexSignature,
21406             updateIndexSignature: updateIndexSignature,
21407             createClassStaticBlockDeclaration: createClassStaticBlockDeclaration,
21408             updateClassStaticBlockDeclaration: updateClassStaticBlockDeclaration,
21409             createTemplateLiteralTypeSpan: createTemplateLiteralTypeSpan,
21410             updateTemplateLiteralTypeSpan: updateTemplateLiteralTypeSpan,
21411             createKeywordTypeNode: createKeywordTypeNode,
21412             createTypePredicateNode: createTypePredicateNode,
21413             updateTypePredicateNode: updateTypePredicateNode,
21414             createTypeReferenceNode: createTypeReferenceNode,
21415             updateTypeReferenceNode: updateTypeReferenceNode,
21416             createFunctionTypeNode: createFunctionTypeNode,
21417             updateFunctionTypeNode: updateFunctionTypeNode,
21418             createConstructorTypeNode: createConstructorTypeNode,
21419             updateConstructorTypeNode: updateConstructorTypeNode,
21420             createTypeQueryNode: createTypeQueryNode,
21421             updateTypeQueryNode: updateTypeQueryNode,
21422             createTypeLiteralNode: createTypeLiteralNode,
21423             updateTypeLiteralNode: updateTypeLiteralNode,
21424             createArrayTypeNode: createArrayTypeNode,
21425             updateArrayTypeNode: updateArrayTypeNode,
21426             createTupleTypeNode: createTupleTypeNode,
21427             updateTupleTypeNode: updateTupleTypeNode,
21428             createNamedTupleMember: createNamedTupleMember,
21429             updateNamedTupleMember: updateNamedTupleMember,
21430             createOptionalTypeNode: createOptionalTypeNode,
21431             updateOptionalTypeNode: updateOptionalTypeNode,
21432             createRestTypeNode: createRestTypeNode,
21433             updateRestTypeNode: updateRestTypeNode,
21434             createUnionTypeNode: createUnionTypeNode,
21435             updateUnionTypeNode: updateUnionTypeNode,
21436             createIntersectionTypeNode: createIntersectionTypeNode,
21437             updateIntersectionTypeNode: updateIntersectionTypeNode,
21438             createConditionalTypeNode: createConditionalTypeNode,
21439             updateConditionalTypeNode: updateConditionalTypeNode,
21440             createInferTypeNode: createInferTypeNode,
21441             updateInferTypeNode: updateInferTypeNode,
21442             createImportTypeNode: createImportTypeNode,
21443             updateImportTypeNode: updateImportTypeNode,
21444             createParenthesizedType: createParenthesizedType,
21445             updateParenthesizedType: updateParenthesizedType,
21446             createThisTypeNode: createThisTypeNode,
21447             createTypeOperatorNode: createTypeOperatorNode,
21448             updateTypeOperatorNode: updateTypeOperatorNode,
21449             createIndexedAccessTypeNode: createIndexedAccessTypeNode,
21450             updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
21451             createMappedTypeNode: createMappedTypeNode,
21452             updateMappedTypeNode: updateMappedTypeNode,
21453             createLiteralTypeNode: createLiteralTypeNode,
21454             updateLiteralTypeNode: updateLiteralTypeNode,
21455             createTemplateLiteralType: createTemplateLiteralType,
21456             updateTemplateLiteralType: updateTemplateLiteralType,
21457             createObjectBindingPattern: createObjectBindingPattern,
21458             updateObjectBindingPattern: updateObjectBindingPattern,
21459             createArrayBindingPattern: createArrayBindingPattern,
21460             updateArrayBindingPattern: updateArrayBindingPattern,
21461             createBindingElement: createBindingElement,
21462             updateBindingElement: updateBindingElement,
21463             createArrayLiteralExpression: createArrayLiteralExpression,
21464             updateArrayLiteralExpression: updateArrayLiteralExpression,
21465             createObjectLiteralExpression: createObjectLiteralExpression,
21466             updateObjectLiteralExpression: updateObjectLiteralExpression,
21467             createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
21468                 function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
21469                 createPropertyAccessExpression,
21470             updatePropertyAccessExpression: updatePropertyAccessExpression,
21471             createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
21472                 function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
21473                 createPropertyAccessChain,
21474             updatePropertyAccessChain: updatePropertyAccessChain,
21475             createElementAccessExpression: createElementAccessExpression,
21476             updateElementAccessExpression: updateElementAccessExpression,
21477             createElementAccessChain: createElementAccessChain,
21478             updateElementAccessChain: updateElementAccessChain,
21479             createCallExpression: createCallExpression,
21480             updateCallExpression: updateCallExpression,
21481             createCallChain: createCallChain,
21482             updateCallChain: updateCallChain,
21483             createNewExpression: createNewExpression,
21484             updateNewExpression: updateNewExpression,
21485             createTaggedTemplateExpression: createTaggedTemplateExpression,
21486             updateTaggedTemplateExpression: updateTaggedTemplateExpression,
21487             createTypeAssertion: createTypeAssertion,
21488             updateTypeAssertion: updateTypeAssertion,
21489             createParenthesizedExpression: createParenthesizedExpression,
21490             updateParenthesizedExpression: updateParenthesizedExpression,
21491             createFunctionExpression: createFunctionExpression,
21492             updateFunctionExpression: updateFunctionExpression,
21493             createArrowFunction: createArrowFunction,
21494             updateArrowFunction: updateArrowFunction,
21495             createDeleteExpression: createDeleteExpression,
21496             updateDeleteExpression: updateDeleteExpression,
21497             createTypeOfExpression: createTypeOfExpression,
21498             updateTypeOfExpression: updateTypeOfExpression,
21499             createVoidExpression: createVoidExpression,
21500             updateVoidExpression: updateVoidExpression,
21501             createAwaitExpression: createAwaitExpression,
21502             updateAwaitExpression: updateAwaitExpression,
21503             createPrefixUnaryExpression: createPrefixUnaryExpression,
21504             updatePrefixUnaryExpression: updatePrefixUnaryExpression,
21505             createPostfixUnaryExpression: createPostfixUnaryExpression,
21506             updatePostfixUnaryExpression: updatePostfixUnaryExpression,
21507             createBinaryExpression: createBinaryExpression,
21508             updateBinaryExpression: updateBinaryExpression,
21509             createConditionalExpression: createConditionalExpression,
21510             updateConditionalExpression: updateConditionalExpression,
21511             createTemplateExpression: createTemplateExpression,
21512             updateTemplateExpression: updateTemplateExpression,
21513             createTemplateHead: createTemplateHead,
21514             createTemplateMiddle: createTemplateMiddle,
21515             createTemplateTail: createTemplateTail,
21516             createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
21517             createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
21518             createYieldExpression: createYieldExpression,
21519             updateYieldExpression: updateYieldExpression,
21520             createSpreadElement: createSpreadElement,
21521             updateSpreadElement: updateSpreadElement,
21522             createClassExpression: createClassExpression,
21523             updateClassExpression: updateClassExpression,
21524             createOmittedExpression: createOmittedExpression,
21525             createExpressionWithTypeArguments: createExpressionWithTypeArguments,
21526             updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
21527             createAsExpression: createAsExpression,
21528             updateAsExpression: updateAsExpression,
21529             createNonNullExpression: createNonNullExpression,
21530             updateNonNullExpression: updateNonNullExpression,
21531             createNonNullChain: createNonNullChain,
21532             updateNonNullChain: updateNonNullChain,
21533             createMetaProperty: createMetaProperty,
21534             updateMetaProperty: updateMetaProperty,
21535             createTemplateSpan: createTemplateSpan,
21536             updateTemplateSpan: updateTemplateSpan,
21537             createSemicolonClassElement: createSemicolonClassElement,
21538             createBlock: createBlock,
21539             updateBlock: updateBlock,
21540             createVariableStatement: createVariableStatement,
21541             updateVariableStatement: updateVariableStatement,
21542             createEmptyStatement: createEmptyStatement,
21543             createExpressionStatement: createExpressionStatement,
21544             updateExpressionStatement: updateExpressionStatement,
21545             createIfStatement: createIfStatement,
21546             updateIfStatement: updateIfStatement,
21547             createDoStatement: createDoStatement,
21548             updateDoStatement: updateDoStatement,
21549             createWhileStatement: createWhileStatement,
21550             updateWhileStatement: updateWhileStatement,
21551             createForStatement: createForStatement,
21552             updateForStatement: updateForStatement,
21553             createForInStatement: createForInStatement,
21554             updateForInStatement: updateForInStatement,
21555             createForOfStatement: createForOfStatement,
21556             updateForOfStatement: updateForOfStatement,
21557             createContinueStatement: createContinueStatement,
21558             updateContinueStatement: updateContinueStatement,
21559             createBreakStatement: createBreakStatement,
21560             updateBreakStatement: updateBreakStatement,
21561             createReturnStatement: createReturnStatement,
21562             updateReturnStatement: updateReturnStatement,
21563             createWithStatement: createWithStatement,
21564             updateWithStatement: updateWithStatement,
21565             createSwitchStatement: createSwitchStatement,
21566             updateSwitchStatement: updateSwitchStatement,
21567             createLabeledStatement: createLabeledStatement,
21568             updateLabeledStatement: updateLabeledStatement,
21569             createThrowStatement: createThrowStatement,
21570             updateThrowStatement: updateThrowStatement,
21571             createTryStatement: createTryStatement,
21572             updateTryStatement: updateTryStatement,
21573             createDebuggerStatement: createDebuggerStatement,
21574             createVariableDeclaration: createVariableDeclaration,
21575             updateVariableDeclaration: updateVariableDeclaration,
21576             createVariableDeclarationList: createVariableDeclarationList,
21577             updateVariableDeclarationList: updateVariableDeclarationList,
21578             createFunctionDeclaration: createFunctionDeclaration,
21579             updateFunctionDeclaration: updateFunctionDeclaration,
21580             createClassDeclaration: createClassDeclaration,
21581             updateClassDeclaration: updateClassDeclaration,
21582             createInterfaceDeclaration: createInterfaceDeclaration,
21583             updateInterfaceDeclaration: updateInterfaceDeclaration,
21584             createTypeAliasDeclaration: createTypeAliasDeclaration,
21585             updateTypeAliasDeclaration: updateTypeAliasDeclaration,
21586             createEnumDeclaration: createEnumDeclaration,
21587             updateEnumDeclaration: updateEnumDeclaration,
21588             createModuleDeclaration: createModuleDeclaration,
21589             updateModuleDeclaration: updateModuleDeclaration,
21590             createModuleBlock: createModuleBlock,
21591             updateModuleBlock: updateModuleBlock,
21592             createCaseBlock: createCaseBlock,
21593             updateCaseBlock: updateCaseBlock,
21594             createNamespaceExportDeclaration: createNamespaceExportDeclaration,
21595             updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
21596             createImportEqualsDeclaration: createImportEqualsDeclaration,
21597             updateImportEqualsDeclaration: updateImportEqualsDeclaration,
21598             createImportDeclaration: createImportDeclaration,
21599             updateImportDeclaration: updateImportDeclaration,
21600             createImportClause: createImportClause,
21601             updateImportClause: updateImportClause,
21602             createAssertClause: createAssertClause,
21603             updateAssertClause: updateAssertClause,
21604             createAssertEntry: createAssertEntry,
21605             updateAssertEntry: updateAssertEntry,
21606             createNamespaceImport: createNamespaceImport,
21607             updateNamespaceImport: updateNamespaceImport,
21608             createNamespaceExport: createNamespaceExport,
21609             updateNamespaceExport: updateNamespaceExport,
21610             createNamedImports: createNamedImports,
21611             updateNamedImports: updateNamedImports,
21612             createImportSpecifier: createImportSpecifier,
21613             updateImportSpecifier: updateImportSpecifier,
21614             createExportAssignment: createExportAssignment,
21615             updateExportAssignment: updateExportAssignment,
21616             createExportDeclaration: createExportDeclaration,
21617             updateExportDeclaration: updateExportDeclaration,
21618             createNamedExports: createNamedExports,
21619             updateNamedExports: updateNamedExports,
21620             createExportSpecifier: createExportSpecifier,
21621             updateExportSpecifier: updateExportSpecifier,
21622             createMissingDeclaration: createMissingDeclaration,
21623             createExternalModuleReference: createExternalModuleReference,
21624             updateExternalModuleReference: updateExternalModuleReference,
21625             // lazily load factory members for JSDoc types with similar structure
21626             get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(310 /* JSDocAllType */); },
21627             get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(311 /* JSDocUnknownType */); },
21628             get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(313 /* JSDocNonNullableType */); },
21629             get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(313 /* JSDocNonNullableType */); },
21630             get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(312 /* JSDocNullableType */); },
21631             get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(312 /* JSDocNullableType */); },
21632             get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(314 /* JSDocOptionalType */); },
21633             get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(314 /* JSDocOptionalType */); },
21634             get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(316 /* JSDocVariadicType */); },
21635             get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(316 /* JSDocVariadicType */); },
21636             get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(317 /* JSDocNamepathType */); },
21637             get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(317 /* JSDocNamepathType */); },
21638             createJSDocFunctionType: createJSDocFunctionType,
21639             updateJSDocFunctionType: updateJSDocFunctionType,
21640             createJSDocTypeLiteral: createJSDocTypeLiteral,
21641             updateJSDocTypeLiteral: updateJSDocTypeLiteral,
21642             createJSDocTypeExpression: createJSDocTypeExpression,
21643             updateJSDocTypeExpression: updateJSDocTypeExpression,
21644             createJSDocSignature: createJSDocSignature,
21645             updateJSDocSignature: updateJSDocSignature,
21646             createJSDocTemplateTag: createJSDocTemplateTag,
21647             updateJSDocTemplateTag: updateJSDocTemplateTag,
21648             createJSDocTypedefTag: createJSDocTypedefTag,
21649             updateJSDocTypedefTag: updateJSDocTypedefTag,
21650             createJSDocParameterTag: createJSDocParameterTag,
21651             updateJSDocParameterTag: updateJSDocParameterTag,
21652             createJSDocPropertyTag: createJSDocPropertyTag,
21653             updateJSDocPropertyTag: updateJSDocPropertyTag,
21654             createJSDocCallbackTag: createJSDocCallbackTag,
21655             updateJSDocCallbackTag: updateJSDocCallbackTag,
21656             createJSDocAugmentsTag: createJSDocAugmentsTag,
21657             updateJSDocAugmentsTag: updateJSDocAugmentsTag,
21658             createJSDocImplementsTag: createJSDocImplementsTag,
21659             updateJSDocImplementsTag: updateJSDocImplementsTag,
21660             createJSDocSeeTag: createJSDocSeeTag,
21661             updateJSDocSeeTag: updateJSDocSeeTag,
21662             createJSDocNameReference: createJSDocNameReference,
21663             updateJSDocNameReference: updateJSDocNameReference,
21664             createJSDocMemberName: createJSDocMemberName,
21665             updateJSDocMemberName: updateJSDocMemberName,
21666             createJSDocLink: createJSDocLink,
21667             updateJSDocLink: updateJSDocLink,
21668             createJSDocLinkCode: createJSDocLinkCode,
21669             updateJSDocLinkCode: updateJSDocLinkCode,
21670             createJSDocLinkPlain: createJSDocLinkPlain,
21671             updateJSDocLinkPlain: updateJSDocLinkPlain,
21672             // lazily load factory members for JSDoc tags with similar structure
21673             get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(341 /* JSDocTypeTag */); },
21674             get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(341 /* JSDocTypeTag */); },
21675             get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(339 /* JSDocReturnTag */); },
21676             get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(339 /* JSDocReturnTag */); },
21677             get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(340 /* JSDocThisTag */); },
21678             get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(340 /* JSDocThisTag */); },
21679             get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(337 /* JSDocEnumTag */); },
21680             get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(337 /* JSDocEnumTag */); },
21681             get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(328 /* JSDocAuthorTag */); },
21682             get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(328 /* JSDocAuthorTag */); },
21683             get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(330 /* JSDocClassTag */); },
21684             get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(330 /* JSDocClassTag */); },
21685             get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(331 /* JSDocPublicTag */); },
21686             get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(331 /* JSDocPublicTag */); },
21687             get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(332 /* JSDocPrivateTag */); },
21688             get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(332 /* JSDocPrivateTag */); },
21689             get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(333 /* JSDocProtectedTag */); },
21690             get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(333 /* JSDocProtectedTag */); },
21691             get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(334 /* JSDocReadonlyTag */); },
21692             get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(334 /* JSDocReadonlyTag */); },
21693             get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(335 /* JSDocOverrideTag */); },
21694             get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(335 /* JSDocOverrideTag */); },
21695             get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(329 /* JSDocDeprecatedTag */); },
21696             get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(329 /* JSDocDeprecatedTag */); },
21697             createJSDocUnknownTag: createJSDocUnknownTag,
21698             updateJSDocUnknownTag: updateJSDocUnknownTag,
21699             createJSDocText: createJSDocText,
21700             updateJSDocText: updateJSDocText,
21701             createJSDocComment: createJSDocComment,
21702             updateJSDocComment: updateJSDocComment,
21703             createJsxElement: createJsxElement,
21704             updateJsxElement: updateJsxElement,
21705             createJsxSelfClosingElement: createJsxSelfClosingElement,
21706             updateJsxSelfClosingElement: updateJsxSelfClosingElement,
21707             createJsxOpeningElement: createJsxOpeningElement,
21708             updateJsxOpeningElement: updateJsxOpeningElement,
21709             createJsxClosingElement: createJsxClosingElement,
21710             updateJsxClosingElement: updateJsxClosingElement,
21711             createJsxFragment: createJsxFragment,
21712             createJsxText: createJsxText,
21713             updateJsxText: updateJsxText,
21714             createJsxOpeningFragment: createJsxOpeningFragment,
21715             createJsxJsxClosingFragment: createJsxJsxClosingFragment,
21716             updateJsxFragment: updateJsxFragment,
21717             createJsxAttribute: createJsxAttribute,
21718             updateJsxAttribute: updateJsxAttribute,
21719             createJsxAttributes: createJsxAttributes,
21720             updateJsxAttributes: updateJsxAttributes,
21721             createJsxSpreadAttribute: createJsxSpreadAttribute,
21722             updateJsxSpreadAttribute: updateJsxSpreadAttribute,
21723             createJsxExpression: createJsxExpression,
21724             updateJsxExpression: updateJsxExpression,
21725             createCaseClause: createCaseClause,
21726             updateCaseClause: updateCaseClause,
21727             createDefaultClause: createDefaultClause,
21728             updateDefaultClause: updateDefaultClause,
21729             createHeritageClause: createHeritageClause,
21730             updateHeritageClause: updateHeritageClause,
21731             createCatchClause: createCatchClause,
21732             updateCatchClause: updateCatchClause,
21733             createPropertyAssignment: createPropertyAssignment,
21734             updatePropertyAssignment: updatePropertyAssignment,
21735             createShorthandPropertyAssignment: createShorthandPropertyAssignment,
21736             updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
21737             createSpreadAssignment: createSpreadAssignment,
21738             updateSpreadAssignment: updateSpreadAssignment,
21739             createEnumMember: createEnumMember,
21740             updateEnumMember: updateEnumMember,
21741             createSourceFile: createSourceFile,
21742             updateSourceFile: updateSourceFile,
21743             createBundle: createBundle,
21744             updateBundle: updateBundle,
21745             createUnparsedSource: createUnparsedSource,
21746             createUnparsedPrologue: createUnparsedPrologue,
21747             createUnparsedPrepend: createUnparsedPrepend,
21748             createUnparsedTextLike: createUnparsedTextLike,
21749             createUnparsedSyntheticReference: createUnparsedSyntheticReference,
21750             createInputFiles: createInputFiles,
21751             createSyntheticExpression: createSyntheticExpression,
21752             createSyntaxList: createSyntaxList,
21753             createNotEmittedStatement: createNotEmittedStatement,
21754             createPartiallyEmittedExpression: createPartiallyEmittedExpression,
21755             updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
21756             createCommaListExpression: createCommaListExpression,
21757             updateCommaListExpression: updateCommaListExpression,
21758             createEndOfDeclarationMarker: createEndOfDeclarationMarker,
21759             createMergeDeclarationMarker: createMergeDeclarationMarker,
21760             createSyntheticReferenceExpression: createSyntheticReferenceExpression,
21761             updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
21762             cloneNode: cloneNode,
21763             // Lazily load factory methods for common operator factories and utilities
21764             get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
21765             get createAssignment() { return getBinaryCreateFunction(63 /* EqualsToken */); },
21766             get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
21767             get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
21768             get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
21769             get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
21770             get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
21771             get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
21772             get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
21773             get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
21774             get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
21775             get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
21776             get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
21777             get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
21778             get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
21779             get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
21780             get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
21781             get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
21782             get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
21783             get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
21784             get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
21785             get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
21786             get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
21787             get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
21788             get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
21789             get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
21790             get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
21791             get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
21792             get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
21793             get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
21794             get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
21795             get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
21796             // Compound nodes
21797             createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
21798             createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
21799             createVoidZero: createVoidZero,
21800             createExportDefault: createExportDefault,
21801             createExternalModuleExport: createExternalModuleExport,
21802             createTypeCheck: createTypeCheck,
21803             createMethodCall: createMethodCall,
21804             createGlobalMethodCall: createGlobalMethodCall,
21805             createFunctionBindCall: createFunctionBindCall,
21806             createFunctionCallCall: createFunctionCallCall,
21807             createFunctionApplyCall: createFunctionApplyCall,
21808             createArraySliceCall: createArraySliceCall,
21809             createArrayConcatCall: createArrayConcatCall,
21810             createObjectDefinePropertyCall: createObjectDefinePropertyCall,
21811             createReflectGetCall: createReflectGetCall,
21812             createReflectSetCall: createReflectSetCall,
21813             createPropertyDescriptor: createPropertyDescriptor,
21814             createCallBinding: createCallBinding,
21815             createAssignmentTargetWrapper: createAssignmentTargetWrapper,
21816             // Utilities
21817             inlineExpressions: inlineExpressions,
21818             getInternalName: getInternalName,
21819             getLocalName: getLocalName,
21820             getExportName: getExportName,
21821             getDeclarationName: getDeclarationName,
21822             getNamespaceMemberName: getNamespaceMemberName,
21823             getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
21824             restoreOuterExpressions: restoreOuterExpressions,
21825             restoreEnclosingLabel: restoreEnclosingLabel,
21826             createUseStrictPrologue: createUseStrictPrologue,
21827             copyPrologue: copyPrologue,
21828             copyStandardPrologue: copyStandardPrologue,
21829             copyCustomPrologue: copyCustomPrologue,
21830             ensureUseStrict: ensureUseStrict,
21831             liftToBlock: liftToBlock,
21832             mergeLexicalEnvironment: mergeLexicalEnvironment,
21833             updateModifiers: updateModifiers,
21834         };
21835         return factory;
21836         // @api
21837         function createNodeArray(elements, hasTrailingComma) {
21838             if (elements === undefined || elements === ts.emptyArray) {
21839                 elements = [];
21840             }
21841             else if (ts.isNodeArray(elements)) {
21842                 if (hasTrailingComma === undefined || elements.hasTrailingComma === hasTrailingComma) {
21843                     // Ensure the transform flags have been aggregated for this NodeArray
21844                     if (elements.transformFlags === undefined) {
21845                         aggregateChildrenFlags(elements);
21846                     }
21847                     ts.Debug.attachNodeArrayDebugInfo(elements);
21848                     return elements;
21849                 }
21850                 // This *was* a `NodeArray`, but the `hasTrailingComma` option differs. Recreate the
21851                 // array with the same elements, text range, and transform flags but with the updated
21852                 // value for `hasTrailingComma`
21853                 var array_8 = elements.slice();
21854                 array_8.pos = elements.pos;
21855                 array_8.end = elements.end;
21856                 array_8.hasTrailingComma = hasTrailingComma;
21857                 array_8.transformFlags = elements.transformFlags;
21858                 ts.Debug.attachNodeArrayDebugInfo(array_8);
21859                 return array_8;
21860             }
21861             // Since the element list of a node array is typically created by starting with an empty array and
21862             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
21863             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
21864             var length = elements.length;
21865             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
21866             ts.setTextRangePosEnd(array, -1, -1);
21867             array.hasTrailingComma = !!hasTrailingComma;
21868             aggregateChildrenFlags(array);
21869             ts.Debug.attachNodeArrayDebugInfo(array);
21870             return array;
21871         }
21872         function createBaseNode(kind) {
21873             return baseFactory.createBaseNode(kind);
21874         }
21875         function createBaseDeclaration(kind, decorators, modifiers) {
21876             var node = createBaseNode(kind);
21877             node.decorators = asNodeArray(decorators);
21878             node.modifiers = asNodeArray(modifiers);
21879             node.transformFlags |=
21880                 propagateChildrenFlags(node.decorators) |
21881                     propagateChildrenFlags(node.modifiers);
21882             // NOTE: The following properties are commonly set by the binder and are added here to
21883             // ensure declarations have a stable shape.
21884             node.symbol = undefined; // initialized by binder
21885             node.localSymbol = undefined; // initialized by binder
21886             node.locals = undefined; // initialized by binder
21887             node.nextContainer = undefined; // initialized by binder
21888             return node;
21889         }
21890         function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
21891             var node = createBaseDeclaration(kind, decorators, modifiers);
21892             name = asName(name);
21893             node.name = name;
21894             // The PropertyName of a member is allowed to be `await`.
21895             // We don't need to exclude `await` for type signatures since types
21896             // don't propagate child flags.
21897             if (name) {
21898                 switch (node.kind) {
21899                     case 168 /* MethodDeclaration */:
21900                     case 171 /* GetAccessor */:
21901                     case 172 /* SetAccessor */:
21902                     case 166 /* PropertyDeclaration */:
21903                     case 294 /* PropertyAssignment */:
21904                         if (ts.isIdentifier(name)) {
21905                             node.transformFlags |= propagateIdentifierNameFlags(name);
21906                             break;
21907                         }
21908                     // fall through
21909                     default:
21910                         node.transformFlags |= propagateChildFlags(name);
21911                         break;
21912                 }
21913             }
21914             return node;
21915         }
21916         function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
21917             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
21918             node.typeParameters = asNodeArray(typeParameters);
21919             node.transformFlags |= propagateChildrenFlags(node.typeParameters);
21920             if (typeParameters)
21921                 node.transformFlags |= 1 /* ContainsTypeScript */;
21922             return node;
21923         }
21924         function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
21925             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
21926             node.parameters = createNodeArray(parameters);
21927             node.type = type;
21928             node.transformFlags |=
21929                 propagateChildrenFlags(node.parameters) |
21930                     propagateChildFlags(node.type);
21931             if (type)
21932                 node.transformFlags |= 1 /* ContainsTypeScript */;
21933             return node;
21934         }
21935         function updateBaseSignatureDeclaration(updated, original) {
21936             // copy children used only for error reporting
21937             if (original.typeArguments)
21938                 updated.typeArguments = original.typeArguments;
21939             return update(updated, original);
21940         }
21941         function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
21942             var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
21943             node.body = body;
21944             node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */;
21945             if (!body)
21946                 node.transformFlags |= 1 /* ContainsTypeScript */;
21947             return node;
21948         }
21949         function updateBaseFunctionLikeDeclaration(updated, original) {
21950             // copy children used only for error reporting
21951             if (original.exclamationToken)
21952                 updated.exclamationToken = original.exclamationToken;
21953             if (original.typeArguments)
21954                 updated.typeArguments = original.typeArguments;
21955             return updateBaseSignatureDeclaration(updated, original);
21956         }
21957         function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
21958             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
21959             node.heritageClauses = asNodeArray(heritageClauses);
21960             node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
21961             return node;
21962         }
21963         function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
21964             var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
21965             node.members = createNodeArray(members);
21966             node.transformFlags |= propagateChildrenFlags(node.members);
21967             return node;
21968         }
21969         function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
21970             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
21971             node.initializer = initializer;
21972             node.transformFlags |= propagateChildFlags(node.initializer);
21973             return node;
21974         }
21975         function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
21976             var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
21977             node.type = type;
21978             node.transformFlags |= propagateChildFlags(type);
21979             if (type)
21980                 node.transformFlags |= 1 /* ContainsTypeScript */;
21981             return node;
21982         }
21983         //
21984         // Literals
21985         //
21986         function createBaseLiteral(kind, text) {
21987             var node = createBaseToken(kind);
21988             node.text = text;
21989             return node;
21990         }
21991         // @api
21992         function createNumericLiteral(value, numericLiteralFlags) {
21993             if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
21994             var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
21995             node.numericLiteralFlags = numericLiteralFlags;
21996             if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
21997                 node.transformFlags |= 512 /* ContainsES2015 */;
21998             return node;
21999         }
22000         // @api
22001         function createBigIntLiteral(value) {
22002             var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
22003             node.transformFlags |= 4 /* ContainsESNext */;
22004             return node;
22005         }
22006         function createBaseStringLiteral(text, isSingleQuote) {
22007             var node = createBaseLiteral(10 /* StringLiteral */, text);
22008             node.singleQuote = isSingleQuote;
22009             return node;
22010         }
22011         // @api
22012         function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
22013             var node = createBaseStringLiteral(text, isSingleQuote);
22014             node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
22015             if (hasExtendedUnicodeEscape)
22016                 node.transformFlags |= 512 /* ContainsES2015 */;
22017             return node;
22018         }
22019         // @api
22020         function createStringLiteralFromNode(sourceNode) {
22021             var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
22022             node.textSourceNode = sourceNode;
22023             return node;
22024         }
22025         // @api
22026         function createRegularExpressionLiteral(text) {
22027             var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
22028             return node;
22029         }
22030         // @api
22031         function createLiteralLikeNode(kind, text) {
22032             switch (kind) {
22033                 case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
22034                 case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
22035                 case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
22036                 case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
22037                 case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
22038                 case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
22039                 case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
22040             }
22041         }
22042         //
22043         // Identifiers
22044         //
22045         function createBaseIdentifier(text, originalKeywordKind) {
22046             if (originalKeywordKind === undefined && text) {
22047                 originalKeywordKind = ts.stringToToken(text);
22048             }
22049             if (originalKeywordKind === 79 /* Identifier */) {
22050                 originalKeywordKind = undefined;
22051             }
22052             var node = baseFactory.createBaseIdentifierNode(79 /* Identifier */);
22053             node.originalKeywordKind = originalKeywordKind;
22054             node.escapedText = ts.escapeLeadingUnderscores(text);
22055             return node;
22056         }
22057         function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
22058             var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
22059             node.autoGenerateFlags = autoGenerateFlags;
22060             node.autoGenerateId = nextAutoGenerateId;
22061             nextAutoGenerateId++;
22062             return node;
22063         }
22064         // @api
22065         function createIdentifier(text, typeArguments, originalKeywordKind) {
22066             var node = createBaseIdentifier(text, originalKeywordKind);
22067             if (typeArguments) {
22068                 // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
22069                 node.typeArguments = createNodeArray(typeArguments);
22070             }
22071             if (node.originalKeywordKind === 132 /* AwaitKeyword */) {
22072                 node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */;
22073             }
22074             return node;
22075         }
22076         // @api
22077         function updateIdentifier(node, typeArguments) {
22078             return node.typeArguments !== typeArguments
22079                 ? update(createIdentifier(ts.idText(node), typeArguments), node)
22080                 : node;
22081         }
22082         // @api
22083         function createTempVariable(recordTempVariable, reservedInNestedScopes) {
22084             var flags = 1 /* Auto */;
22085             if (reservedInNestedScopes)
22086                 flags |= 8 /* ReservedInNestedScopes */;
22087             var name = createBaseGeneratedIdentifier("", flags);
22088             if (recordTempVariable) {
22089                 recordTempVariable(name);
22090             }
22091             return name;
22092         }
22093         /** Create a unique temporary variable for use in a loop. */
22094         // @api
22095         function createLoopVariable(reservedInNestedScopes) {
22096             var flags = 2 /* Loop */;
22097             if (reservedInNestedScopes)
22098                 flags |= 8 /* ReservedInNestedScopes */;
22099             return createBaseGeneratedIdentifier("", flags);
22100         }
22101         /** Create a unique name based on the supplied text. */
22102         // @api
22103         function createUniqueName(text, flags) {
22104             if (flags === void 0) { flags = 0 /* None */; }
22105             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
22106             ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
22107             return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
22108         }
22109         /** Create a unique name generated for a node. */
22110         // @api
22111         function getGeneratedNameForNode(node, flags) {
22112             if (flags === void 0) { flags = 0; }
22113             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
22114             var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
22115             name.original = node;
22116             return name;
22117         }
22118         // @api
22119         function createPrivateIdentifier(text) {
22120             if (!ts.startsWith(text, "#"))
22121                 ts.Debug.fail("First character of private identifier must be #: " + text);
22122             var node = baseFactory.createBasePrivateIdentifierNode(80 /* PrivateIdentifier */);
22123             node.escapedText = ts.escapeLeadingUnderscores(text);
22124             node.transformFlags |= 8388608 /* ContainsClassFields */;
22125             return node;
22126         }
22127         //
22128         // Punctuation
22129         //
22130         function createBaseToken(kind) {
22131             return baseFactory.createBaseTokenNode(kind);
22132         }
22133         function createToken(token) {
22134             ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 159 /* LastToken */, "Invalid token");
22135             ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
22136             ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
22137             ts.Debug.assert(token !== 79 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
22138             var node = createBaseToken(token);
22139             var transformFlags = 0 /* None */;
22140             switch (token) {
22141                 case 131 /* AsyncKeyword */:
22142                     // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
22143                     transformFlags =
22144                         128 /* ContainsES2017 */ |
22145                             64 /* ContainsES2018 */;
22146                     break;
22147                 case 123 /* PublicKeyword */:
22148                 case 121 /* PrivateKeyword */:
22149                 case 122 /* ProtectedKeyword */:
22150                 case 144 /* ReadonlyKeyword */:
22151                 case 126 /* AbstractKeyword */:
22152                 case 135 /* DeclareKeyword */:
22153                 case 85 /* ConstKeyword */:
22154                 case 130 /* AnyKeyword */:
22155                 case 146 /* NumberKeyword */:
22156                 case 157 /* BigIntKeyword */:
22157                 case 143 /* NeverKeyword */:
22158                 case 147 /* ObjectKeyword */:
22159                 case 158 /* OverrideKeyword */:
22160                 case 149 /* StringKeyword */:
22161                 case 133 /* BooleanKeyword */:
22162                 case 150 /* SymbolKeyword */:
22163                 case 114 /* VoidKeyword */:
22164                 case 154 /* UnknownKeyword */:
22165                 case 152 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
22166                     transformFlags = 1 /* ContainsTypeScript */;
22167                     break;
22168                 case 106 /* SuperKeyword */:
22169                     transformFlags = 512 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */;
22170                     break;
22171                 case 124 /* StaticKeyword */:
22172                     transformFlags = 512 /* ContainsES2015 */;
22173                     break;
22174                 case 108 /* ThisKeyword */:
22175                     // 'this' indicates a lexical 'this'
22176                     transformFlags = 8192 /* ContainsLexicalThis */;
22177                     break;
22178             }
22179             if (transformFlags) {
22180                 node.transformFlags |= transformFlags;
22181             }
22182             return node;
22183         }
22184         //
22185         // Reserved words
22186         //
22187         // @api
22188         function createSuper() {
22189             return createToken(106 /* SuperKeyword */);
22190         }
22191         // @api
22192         function createThis() {
22193             return createToken(108 /* ThisKeyword */);
22194         }
22195         // @api
22196         function createNull() {
22197             return createToken(104 /* NullKeyword */);
22198         }
22199         // @api
22200         function createTrue() {
22201             return createToken(110 /* TrueKeyword */);
22202         }
22203         // @api
22204         function createFalse() {
22205             return createToken(95 /* FalseKeyword */);
22206         }
22207         //
22208         // Modifiers
22209         //
22210         // @api
22211         function createModifier(kind) {
22212             return createToken(kind);
22213         }
22214         // @api
22215         function createModifiersFromModifierFlags(flags) {
22216             var result = [];
22217             if (flags & 1 /* Export */)
22218                 result.push(createModifier(93 /* ExportKeyword */));
22219             if (flags & 2 /* Ambient */)
22220                 result.push(createModifier(135 /* DeclareKeyword */));
22221             if (flags & 512 /* Default */)
22222                 result.push(createModifier(88 /* DefaultKeyword */));
22223             if (flags & 2048 /* Const */)
22224                 result.push(createModifier(85 /* ConstKeyword */));
22225             if (flags & 4 /* Public */)
22226                 result.push(createModifier(123 /* PublicKeyword */));
22227             if (flags & 8 /* Private */)
22228                 result.push(createModifier(121 /* PrivateKeyword */));
22229             if (flags & 16 /* Protected */)
22230                 result.push(createModifier(122 /* ProtectedKeyword */));
22231             if (flags & 128 /* Abstract */)
22232                 result.push(createModifier(126 /* AbstractKeyword */));
22233             if (flags & 32 /* Static */)
22234                 result.push(createModifier(124 /* StaticKeyword */));
22235             if (flags & 16384 /* Override */)
22236                 result.push(createModifier(158 /* OverrideKeyword */));
22237             if (flags & 64 /* Readonly */)
22238                 result.push(createModifier(144 /* ReadonlyKeyword */));
22239             if (flags & 256 /* Async */)
22240                 result.push(createModifier(131 /* AsyncKeyword */));
22241             return result;
22242         }
22243         //
22244         // Names
22245         //
22246         // @api
22247         function createQualifiedName(left, right) {
22248             var node = createBaseNode(160 /* QualifiedName */);
22249             node.left = left;
22250             node.right = asName(right);
22251             node.transformFlags |=
22252                 propagateChildFlags(node.left) |
22253                     propagateIdentifierNameFlags(node.right);
22254             return node;
22255         }
22256         // @api
22257         function updateQualifiedName(node, left, right) {
22258             return node.left !== left
22259                 || node.right !== right
22260                 ? update(createQualifiedName(left, right), node)
22261                 : node;
22262         }
22263         // @api
22264         function createComputedPropertyName(expression) {
22265             var node = createBaseNode(161 /* ComputedPropertyName */);
22266             node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
22267             node.transformFlags |=
22268                 propagateChildFlags(node.expression) |
22269                     512 /* ContainsES2015 */ |
22270                     65536 /* ContainsComputedPropertyName */;
22271             return node;
22272         }
22273         // @api
22274         function updateComputedPropertyName(node, expression) {
22275             return node.expression !== expression
22276                 ? update(createComputedPropertyName(expression), node)
22277                 : node;
22278         }
22279         //
22280         // Signature elements
22281         //
22282         // @api
22283         function createTypeParameterDeclaration(name, constraint, defaultType) {
22284             var node = createBaseNamedDeclaration(162 /* TypeParameter */, 
22285             /*decorators*/ undefined, 
22286             /*modifiers*/ undefined, name);
22287             node.constraint = constraint;
22288             node.default = defaultType;
22289             node.transformFlags = 1 /* ContainsTypeScript */;
22290             return node;
22291         }
22292         // @api
22293         function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
22294             return node.name !== name
22295                 || node.constraint !== constraint
22296                 || node.default !== defaultType
22297                 ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
22298                 : node;
22299         }
22300         // @api
22301         function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
22302             var node = createBaseVariableLikeDeclaration(163 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
22303             node.dotDotDotToken = dotDotDotToken;
22304             node.questionToken = questionToken;
22305             if (ts.isThisIdentifier(node.name)) {
22306                 node.transformFlags = 1 /* ContainsTypeScript */;
22307             }
22308             else {
22309                 node.transformFlags |=
22310                     propagateChildFlags(node.dotDotDotToken) |
22311                         propagateChildFlags(node.questionToken);
22312                 if (questionToken)
22313                     node.transformFlags |= 1 /* ContainsTypeScript */;
22314                 if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */)
22315                     node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
22316                 if (initializer || dotDotDotToken)
22317                     node.transformFlags |= 512 /* ContainsES2015 */;
22318             }
22319             return node;
22320         }
22321         // @api
22322         function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
22323             return node.decorators !== decorators
22324                 || node.modifiers !== modifiers
22325                 || node.dotDotDotToken !== dotDotDotToken
22326                 || node.name !== name
22327                 || node.questionToken !== questionToken
22328                 || node.type !== type
22329                 || node.initializer !== initializer
22330                 ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
22331                 : node;
22332         }
22333         // @api
22334         function createDecorator(expression) {
22335             var node = createBaseNode(164 /* Decorator */);
22336             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22337             node.transformFlags |=
22338                 propagateChildFlags(node.expression) |
22339                     1 /* ContainsTypeScript */ |
22340                     4096 /* ContainsTypeScriptClassSyntax */;
22341             return node;
22342         }
22343         // @api
22344         function updateDecorator(node, expression) {
22345             return node.expression !== expression
22346                 ? update(createDecorator(expression), node)
22347                 : node;
22348         }
22349         //
22350         // Type Elements
22351         //
22352         // @api
22353         function createPropertySignature(modifiers, name, questionToken, type) {
22354             var node = createBaseNamedDeclaration(165 /* PropertySignature */, 
22355             /*decorators*/ undefined, modifiers, name);
22356             node.type = type;
22357             node.questionToken = questionToken;
22358             node.transformFlags = 1 /* ContainsTypeScript */;
22359             return node;
22360         }
22361         // @api
22362         function updatePropertySignature(node, modifiers, name, questionToken, type) {
22363             return node.modifiers !== modifiers
22364                 || node.name !== name
22365                 || node.questionToken !== questionToken
22366                 || node.type !== type
22367                 ? update(createPropertySignature(modifiers, name, questionToken, type), node)
22368                 : node;
22369         }
22370         // @api
22371         function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
22372             var node = createBaseVariableLikeDeclaration(166 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
22373             node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
22374             node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
22375             node.transformFlags |=
22376                 propagateChildFlags(node.questionToken) |
22377                     propagateChildFlags(node.exclamationToken) |
22378                     8388608 /* ContainsClassFields */;
22379             if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
22380                 node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
22381             }
22382             if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22383                 node.transformFlags |= 1 /* ContainsTypeScript */;
22384             }
22385             return node;
22386         }
22387         // @api
22388         function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
22389             return node.decorators !== decorators
22390                 || node.modifiers !== modifiers
22391                 || node.name !== name
22392                 || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
22393                 || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
22394                 || node.type !== type
22395                 || node.initializer !== initializer
22396                 ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
22397                 : node;
22398         }
22399         // @api
22400         function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
22401             var node = createBaseSignatureDeclaration(167 /* MethodSignature */, 
22402             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
22403             node.questionToken = questionToken;
22404             node.transformFlags = 1 /* ContainsTypeScript */;
22405             return node;
22406         }
22407         // @api
22408         function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
22409             return node.modifiers !== modifiers
22410                 || node.name !== name
22411                 || node.questionToken !== questionToken
22412                 || node.typeParameters !== typeParameters
22413                 || node.parameters !== parameters
22414                 || node.type !== type
22415                 ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
22416                 : node;
22417         }
22418         // @api
22419         function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
22420             var node = createBaseFunctionLikeDeclaration(168 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
22421             node.asteriskToken = asteriskToken;
22422             node.questionToken = questionToken;
22423             node.transformFlags |=
22424                 propagateChildFlags(node.asteriskToken) |
22425                     propagateChildFlags(node.questionToken) |
22426                     512 /* ContainsES2015 */;
22427             if (questionToken) {
22428                 node.transformFlags |= 1 /* ContainsTypeScript */;
22429             }
22430             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22431                 if (asteriskToken) {
22432                     node.transformFlags |= 64 /* ContainsES2018 */;
22433                 }
22434                 else {
22435                     node.transformFlags |= 128 /* ContainsES2017 */;
22436                 }
22437             }
22438             else if (asteriskToken) {
22439                 node.transformFlags |= 1024 /* ContainsGenerator */;
22440             }
22441             return node;
22442         }
22443         // @api
22444         function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
22445             return node.decorators !== decorators
22446                 || node.modifiers !== modifiers
22447                 || node.asteriskToken !== asteriskToken
22448                 || node.name !== name
22449                 || node.questionToken !== questionToken
22450                 || node.typeParameters !== typeParameters
22451                 || node.parameters !== parameters
22452                 || node.type !== type
22453                 || node.body !== body
22454                 ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
22455                 : node;
22456         }
22457         // @api
22458         function createClassStaticBlockDeclaration(decorators, modifiers, body) {
22459             var node = createBaseGenericNamedDeclaration(169 /* ClassStaticBlockDeclaration */, decorators, modifiers, 
22460             /*name*/ undefined, 
22461             /*typeParameters*/ undefined);
22462             node.body = body;
22463             node.transformFlags = propagateChildFlags(body) | 8388608 /* ContainsClassFields */;
22464             return node;
22465         }
22466         // @api
22467         function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) {
22468             return node.decorators !== decorators
22469                 || node.modifier !== modifiers
22470                 || node.body !== body
22471                 ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node)
22472                 : node;
22473         }
22474         // @api
22475         function createConstructorDeclaration(decorators, modifiers, parameters, body) {
22476             var node = createBaseFunctionLikeDeclaration(170 /* Constructor */, decorators, modifiers, 
22477             /*name*/ undefined, 
22478             /*typeParameters*/ undefined, parameters, 
22479             /*type*/ undefined, body);
22480             node.transformFlags |= 512 /* ContainsES2015 */;
22481             return node;
22482         }
22483         // @api
22484         function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
22485             return node.decorators !== decorators
22486                 || node.modifiers !== modifiers
22487                 || node.parameters !== parameters
22488                 || node.body !== body
22489                 ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
22490                 : node;
22491         }
22492         // @api
22493         function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
22494             return createBaseFunctionLikeDeclaration(171 /* GetAccessor */, decorators, modifiers, name, 
22495             /*typeParameters*/ undefined, parameters, type, body);
22496         }
22497         // @api
22498         function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
22499             return node.decorators !== decorators
22500                 || node.modifiers !== modifiers
22501                 || node.name !== name
22502                 || node.parameters !== parameters
22503                 || node.type !== type
22504                 || node.body !== body
22505                 ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
22506                 : node;
22507         }
22508         // @api
22509         function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
22510             return createBaseFunctionLikeDeclaration(172 /* SetAccessor */, decorators, modifiers, name, 
22511             /*typeParameters*/ undefined, parameters, 
22512             /*type*/ undefined, body);
22513         }
22514         // @api
22515         function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
22516             return node.decorators !== decorators
22517                 || node.modifiers !== modifiers
22518                 || node.name !== name
22519                 || node.parameters !== parameters
22520                 || node.body !== body
22521                 ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
22522                 : node;
22523         }
22524         // @api
22525         function createCallSignature(typeParameters, parameters, type) {
22526             var node = createBaseSignatureDeclaration(173 /* CallSignature */, 
22527             /*decorators*/ undefined, 
22528             /*modifiers*/ undefined, 
22529             /*name*/ undefined, typeParameters, parameters, type);
22530             node.transformFlags = 1 /* ContainsTypeScript */;
22531             return node;
22532         }
22533         // @api
22534         function updateCallSignature(node, typeParameters, parameters, type) {
22535             return node.typeParameters !== typeParameters
22536                 || node.parameters !== parameters
22537                 || node.type !== type
22538                 ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
22539                 : node;
22540         }
22541         // @api
22542         function createConstructSignature(typeParameters, parameters, type) {
22543             var node = createBaseSignatureDeclaration(174 /* ConstructSignature */, 
22544             /*decorators*/ undefined, 
22545             /*modifiers*/ undefined, 
22546             /*name*/ undefined, typeParameters, parameters, type);
22547             node.transformFlags = 1 /* ContainsTypeScript */;
22548             return node;
22549         }
22550         // @api
22551         function updateConstructSignature(node, typeParameters, parameters, type) {
22552             return node.typeParameters !== typeParameters
22553                 || node.parameters !== parameters
22554                 || node.type !== type
22555                 ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
22556                 : node;
22557         }
22558         // @api
22559         function createIndexSignature(decorators, modifiers, parameters, type) {
22560             var node = createBaseSignatureDeclaration(175 /* IndexSignature */, decorators, modifiers, 
22561             /*name*/ undefined, 
22562             /*typeParameters*/ undefined, parameters, type);
22563             node.transformFlags = 1 /* ContainsTypeScript */;
22564             return node;
22565         }
22566         // @api
22567         function updateIndexSignature(node, decorators, modifiers, parameters, type) {
22568             return node.parameters !== parameters
22569                 || node.type !== type
22570                 || node.decorators !== decorators
22571                 || node.modifiers !== modifiers
22572                 ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
22573                 : node;
22574         }
22575         // @api
22576         function createTemplateLiteralTypeSpan(type, literal) {
22577             var node = createBaseNode(198 /* TemplateLiteralTypeSpan */);
22578             node.type = type;
22579             node.literal = literal;
22580             node.transformFlags = 1 /* ContainsTypeScript */;
22581             return node;
22582         }
22583         // @api
22584         function updateTemplateLiteralTypeSpan(node, type, literal) {
22585             return node.type !== type
22586                 || node.literal !== literal
22587                 ? update(createTemplateLiteralTypeSpan(type, literal), node)
22588                 : node;
22589         }
22590         //
22591         // Types
22592         //
22593         // @api
22594         function createKeywordTypeNode(kind) {
22595             return createToken(kind);
22596         }
22597         // @api
22598         function createTypePredicateNode(assertsModifier, parameterName, type) {
22599             var node = createBaseNode(176 /* TypePredicate */);
22600             node.assertsModifier = assertsModifier;
22601             node.parameterName = asName(parameterName);
22602             node.type = type;
22603             node.transformFlags = 1 /* ContainsTypeScript */;
22604             return node;
22605         }
22606         // @api
22607         function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
22608             return node.assertsModifier !== assertsModifier
22609                 || node.parameterName !== parameterName
22610                 || node.type !== type
22611                 ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
22612                 : node;
22613         }
22614         // @api
22615         function createTypeReferenceNode(typeName, typeArguments) {
22616             var node = createBaseNode(177 /* TypeReference */);
22617             node.typeName = asName(typeName);
22618             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
22619             node.transformFlags = 1 /* ContainsTypeScript */;
22620             return node;
22621         }
22622         // @api
22623         function updateTypeReferenceNode(node, typeName, typeArguments) {
22624             return node.typeName !== typeName
22625                 || node.typeArguments !== typeArguments
22626                 ? update(createTypeReferenceNode(typeName, typeArguments), node)
22627                 : node;
22628         }
22629         // @api
22630         function createFunctionTypeNode(typeParameters, parameters, type) {
22631             var node = createBaseSignatureDeclaration(178 /* FunctionType */, 
22632             /*decorators*/ undefined, 
22633             /*modifiers*/ undefined, 
22634             /*name*/ undefined, typeParameters, parameters, type);
22635             node.transformFlags = 1 /* ContainsTypeScript */;
22636             return node;
22637         }
22638         // @api
22639         function updateFunctionTypeNode(node, typeParameters, parameters, type) {
22640             return node.typeParameters !== typeParameters
22641                 || node.parameters !== parameters
22642                 || node.type !== type
22643                 ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
22644                 : node;
22645         }
22646         // @api
22647         function createConstructorTypeNode() {
22648             var args = [];
22649             for (var _i = 0; _i < arguments.length; _i++) {
22650                 args[_i] = arguments[_i];
22651             }
22652             return args.length === 4 ? createConstructorTypeNode1.apply(void 0, args) :
22653                 args.length === 3 ? createConstructorTypeNode2.apply(void 0, args) :
22654                     ts.Debug.fail("Incorrect number of arguments specified.");
22655         }
22656         function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) {
22657             var node = createBaseSignatureDeclaration(179 /* ConstructorType */, 
22658             /*decorators*/ undefined, modifiers, 
22659             /*name*/ undefined, typeParameters, parameters, type);
22660             node.transformFlags = 1 /* ContainsTypeScript */;
22661             return node;
22662         }
22663         /** @deprecated */
22664         function createConstructorTypeNode2(typeParameters, parameters, type) {
22665             return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type);
22666         }
22667         // @api
22668         function updateConstructorTypeNode() {
22669             var args = [];
22670             for (var _i = 0; _i < arguments.length; _i++) {
22671                 args[_i] = arguments[_i];
22672             }
22673             return args.length === 5 ? updateConstructorTypeNode1.apply(void 0, args) :
22674                 args.length === 4 ? updateConstructorTypeNode2.apply(void 0, args) :
22675                     ts.Debug.fail("Incorrect number of arguments specified.");
22676         }
22677         function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) {
22678             return node.modifiers !== modifiers
22679                 || node.typeParameters !== typeParameters
22680                 || node.parameters !== parameters
22681                 || node.type !== type
22682                 ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node)
22683                 : node;
22684         }
22685         /** @deprecated */
22686         function updateConstructorTypeNode2(node, typeParameters, parameters, type) {
22687             return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type);
22688         }
22689         // @api
22690         function createTypeQueryNode(exprName) {
22691             var node = createBaseNode(180 /* TypeQuery */);
22692             node.exprName = exprName;
22693             node.transformFlags = 1 /* ContainsTypeScript */;
22694             return node;
22695         }
22696         // @api
22697         function updateTypeQueryNode(node, exprName) {
22698             return node.exprName !== exprName
22699                 ? update(createTypeQueryNode(exprName), node)
22700                 : node;
22701         }
22702         // @api
22703         function createTypeLiteralNode(members) {
22704             var node = createBaseNode(181 /* TypeLiteral */);
22705             node.members = createNodeArray(members);
22706             node.transformFlags = 1 /* ContainsTypeScript */;
22707             return node;
22708         }
22709         // @api
22710         function updateTypeLiteralNode(node, members) {
22711             return node.members !== members
22712                 ? update(createTypeLiteralNode(members), node)
22713                 : node;
22714         }
22715         // @api
22716         function createArrayTypeNode(elementType) {
22717             var node = createBaseNode(182 /* ArrayType */);
22718             node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
22719             node.transformFlags = 1 /* ContainsTypeScript */;
22720             return node;
22721         }
22722         // @api
22723         function updateArrayTypeNode(node, elementType) {
22724             return node.elementType !== elementType
22725                 ? update(createArrayTypeNode(elementType), node)
22726                 : node;
22727         }
22728         // @api
22729         function createTupleTypeNode(elements) {
22730             var node = createBaseNode(183 /* TupleType */);
22731             node.elements = createNodeArray(elements);
22732             node.transformFlags = 1 /* ContainsTypeScript */;
22733             return node;
22734         }
22735         // @api
22736         function updateTupleTypeNode(node, elements) {
22737             return node.elements !== elements
22738                 ? update(createTupleTypeNode(elements), node)
22739                 : node;
22740         }
22741         // @api
22742         function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
22743             var node = createBaseNode(196 /* NamedTupleMember */);
22744             node.dotDotDotToken = dotDotDotToken;
22745             node.name = name;
22746             node.questionToken = questionToken;
22747             node.type = type;
22748             node.transformFlags = 1 /* ContainsTypeScript */;
22749             return node;
22750         }
22751         // @api
22752         function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
22753             return node.dotDotDotToken !== dotDotDotToken
22754                 || node.name !== name
22755                 || node.questionToken !== questionToken
22756                 || node.type !== type
22757                 ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
22758                 : node;
22759         }
22760         // @api
22761         function createOptionalTypeNode(type) {
22762             var node = createBaseNode(184 /* OptionalType */);
22763             node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
22764             node.transformFlags = 1 /* ContainsTypeScript */;
22765             return node;
22766         }
22767         // @api
22768         function updateOptionalTypeNode(node, type) {
22769             return node.type !== type
22770                 ? update(createOptionalTypeNode(type), node)
22771                 : node;
22772         }
22773         // @api
22774         function createRestTypeNode(type) {
22775             var node = createBaseNode(185 /* RestType */);
22776             node.type = type;
22777             node.transformFlags = 1 /* ContainsTypeScript */;
22778             return node;
22779         }
22780         // @api
22781         function updateRestTypeNode(node, type) {
22782             return node.type !== type
22783                 ? update(createRestTypeNode(type), node)
22784                 : node;
22785         }
22786         function createUnionOrIntersectionTypeNode(kind, types) {
22787             var node = createBaseNode(kind);
22788             node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
22789             node.transformFlags = 1 /* ContainsTypeScript */;
22790             return node;
22791         }
22792         function updateUnionOrIntersectionTypeNode(node, types) {
22793             return node.types !== types
22794                 ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
22795                 : node;
22796         }
22797         // @api
22798         function createUnionTypeNode(types) {
22799             return createUnionOrIntersectionTypeNode(186 /* UnionType */, types);
22800         }
22801         // @api
22802         function updateUnionTypeNode(node, types) {
22803             return updateUnionOrIntersectionTypeNode(node, types);
22804         }
22805         // @api
22806         function createIntersectionTypeNode(types) {
22807             return createUnionOrIntersectionTypeNode(187 /* IntersectionType */, types);
22808         }
22809         // @api
22810         function updateIntersectionTypeNode(node, types) {
22811             return updateUnionOrIntersectionTypeNode(node, types);
22812         }
22813         // @api
22814         function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
22815             var node = createBaseNode(188 /* ConditionalType */);
22816             node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
22817             node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
22818             node.trueType = trueType;
22819             node.falseType = falseType;
22820             node.transformFlags = 1 /* ContainsTypeScript */;
22821             return node;
22822         }
22823         // @api
22824         function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
22825             return node.checkType !== checkType
22826                 || node.extendsType !== extendsType
22827                 || node.trueType !== trueType
22828                 || node.falseType !== falseType
22829                 ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
22830                 : node;
22831         }
22832         // @api
22833         function createInferTypeNode(typeParameter) {
22834             var node = createBaseNode(189 /* InferType */);
22835             node.typeParameter = typeParameter;
22836             node.transformFlags = 1 /* ContainsTypeScript */;
22837             return node;
22838         }
22839         // @api
22840         function updateInferTypeNode(node, typeParameter) {
22841             return node.typeParameter !== typeParameter
22842                 ? update(createInferTypeNode(typeParameter), node)
22843                 : node;
22844         }
22845         // @api
22846         function createTemplateLiteralType(head, templateSpans) {
22847             var node = createBaseNode(197 /* TemplateLiteralType */);
22848             node.head = head;
22849             node.templateSpans = createNodeArray(templateSpans);
22850             node.transformFlags = 1 /* ContainsTypeScript */;
22851             return node;
22852         }
22853         // @api
22854         function updateTemplateLiteralType(node, head, templateSpans) {
22855             return node.head !== head
22856                 || node.templateSpans !== templateSpans
22857                 ? update(createTemplateLiteralType(head, templateSpans), node)
22858                 : node;
22859         }
22860         // @api
22861         function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
22862             if (isTypeOf === void 0) { isTypeOf = false; }
22863             var node = createBaseNode(199 /* ImportType */);
22864             node.argument = argument;
22865             node.qualifier = qualifier;
22866             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
22867             node.isTypeOf = isTypeOf;
22868             node.transformFlags = 1 /* ContainsTypeScript */;
22869             return node;
22870         }
22871         // @api
22872         function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
22873             if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
22874             return node.argument !== argument
22875                 || node.qualifier !== qualifier
22876                 || node.typeArguments !== typeArguments
22877                 || node.isTypeOf !== isTypeOf
22878                 ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
22879                 : node;
22880         }
22881         // @api
22882         function createParenthesizedType(type) {
22883             var node = createBaseNode(190 /* ParenthesizedType */);
22884             node.type = type;
22885             node.transformFlags = 1 /* ContainsTypeScript */;
22886             return node;
22887         }
22888         // @api
22889         function updateParenthesizedType(node, type) {
22890             return node.type !== type
22891                 ? update(createParenthesizedType(type), node)
22892                 : node;
22893         }
22894         // @api
22895         function createThisTypeNode() {
22896             var node = createBaseNode(191 /* ThisType */);
22897             node.transformFlags = 1 /* ContainsTypeScript */;
22898             return node;
22899         }
22900         // @api
22901         function createTypeOperatorNode(operator, type) {
22902             var node = createBaseNode(192 /* TypeOperator */);
22903             node.operator = operator;
22904             node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
22905             node.transformFlags = 1 /* ContainsTypeScript */;
22906             return node;
22907         }
22908         // @api
22909         function updateTypeOperatorNode(node, type) {
22910             return node.type !== type
22911                 ? update(createTypeOperatorNode(node.operator, type), node)
22912                 : node;
22913         }
22914         // @api
22915         function createIndexedAccessTypeNode(objectType, indexType) {
22916             var node = createBaseNode(193 /* IndexedAccessType */);
22917             node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
22918             node.indexType = indexType;
22919             node.transformFlags = 1 /* ContainsTypeScript */;
22920             return node;
22921         }
22922         // @api
22923         function updateIndexedAccessTypeNode(node, objectType, indexType) {
22924             return node.objectType !== objectType
22925                 || node.indexType !== indexType
22926                 ? update(createIndexedAccessTypeNode(objectType, indexType), node)
22927                 : node;
22928         }
22929         // @api
22930         function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) {
22931             var node = createBaseNode(194 /* MappedType */);
22932             node.readonlyToken = readonlyToken;
22933             node.typeParameter = typeParameter;
22934             node.nameType = nameType;
22935             node.questionToken = questionToken;
22936             node.type = type;
22937             node.members = members && createNodeArray(members);
22938             node.transformFlags = 1 /* ContainsTypeScript */;
22939             return node;
22940         }
22941         // @api
22942         function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) {
22943             return node.readonlyToken !== readonlyToken
22944                 || node.typeParameter !== typeParameter
22945                 || node.nameType !== nameType
22946                 || node.questionToken !== questionToken
22947                 || node.type !== type
22948                 || node.members !== members
22949                 ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node)
22950                 : node;
22951         }
22952         // @api
22953         function createLiteralTypeNode(literal) {
22954             var node = createBaseNode(195 /* LiteralType */);
22955             node.literal = literal;
22956             node.transformFlags = 1 /* ContainsTypeScript */;
22957             return node;
22958         }
22959         // @api
22960         function updateLiteralTypeNode(node, literal) {
22961             return node.literal !== literal
22962                 ? update(createLiteralTypeNode(literal), node)
22963                 : node;
22964         }
22965         //
22966         // Binding Patterns
22967         //
22968         // @api
22969         function createObjectBindingPattern(elements) {
22970             var node = createBaseNode(200 /* ObjectBindingPattern */);
22971             node.elements = createNodeArray(elements);
22972             node.transformFlags |=
22973                 propagateChildrenFlags(node.elements) |
22974                     512 /* ContainsES2015 */ |
22975                     262144 /* ContainsBindingPattern */;
22976             if (node.transformFlags & 16384 /* ContainsRestOrSpread */) {
22977                 node.transformFlags |=
22978                     64 /* ContainsES2018 */ |
22979                         32768 /* ContainsObjectRestOrSpread */;
22980             }
22981             return node;
22982         }
22983         // @api
22984         function updateObjectBindingPattern(node, elements) {
22985             return node.elements !== elements
22986                 ? update(createObjectBindingPattern(elements), node)
22987                 : node;
22988         }
22989         // @api
22990         function createArrayBindingPattern(elements) {
22991             var node = createBaseNode(201 /* ArrayBindingPattern */);
22992             node.elements = createNodeArray(elements);
22993             node.transformFlags |=
22994                 propagateChildrenFlags(node.elements) |
22995                     512 /* ContainsES2015 */ |
22996                     262144 /* ContainsBindingPattern */;
22997             return node;
22998         }
22999         // @api
23000         function updateArrayBindingPattern(node, elements) {
23001             return node.elements !== elements
23002                 ? update(createArrayBindingPattern(elements), node)
23003                 : node;
23004         }
23005         // @api
23006         function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
23007             var node = createBaseBindingLikeDeclaration(202 /* BindingElement */, 
23008             /*decorators*/ undefined, 
23009             /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
23010             node.propertyName = asName(propertyName);
23011             node.dotDotDotToken = dotDotDotToken;
23012             node.transformFlags |=
23013                 propagateChildFlags(node.dotDotDotToken) |
23014                     512 /* ContainsES2015 */;
23015             if (node.propertyName) {
23016                 node.transformFlags |= ts.isIdentifier(node.propertyName) ?
23017                     propagateIdentifierNameFlags(node.propertyName) :
23018                     propagateChildFlags(node.propertyName);
23019             }
23020             if (dotDotDotToken)
23021                 node.transformFlags |= 16384 /* ContainsRestOrSpread */;
23022             return node;
23023         }
23024         // @api
23025         function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
23026             return node.propertyName !== propertyName
23027                 || node.dotDotDotToken !== dotDotDotToken
23028                 || node.name !== name
23029                 || node.initializer !== initializer
23030                 ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
23031                 : node;
23032         }
23033         //
23034         // Expression
23035         //
23036         function createBaseExpression(kind) {
23037             var node = createBaseNode(kind);
23038             // the following properties are commonly set by the checker/binder
23039             return node;
23040         }
23041         // @api
23042         function createArrayLiteralExpression(elements, multiLine) {
23043             var node = createBaseExpression(203 /* ArrayLiteralExpression */);
23044             // Ensure we add a trailing comma for something like `[NumericLiteral(1), NumericLiteral(2), OmittedExpresion]` so that
23045             // we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like
23046             // a trailing comma.
23047             var lastElement = elements && ts.lastOrUndefined(elements);
23048             var elementsArray = createNodeArray(elements, lastElement && ts.isOmittedExpression(lastElement) ? true : undefined);
23049             node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray);
23050             node.multiLine = multiLine;
23051             node.transformFlags |= propagateChildrenFlags(node.elements);
23052             return node;
23053         }
23054         // @api
23055         function updateArrayLiteralExpression(node, elements) {
23056             return node.elements !== elements
23057                 ? update(createArrayLiteralExpression(elements, node.multiLine), node)
23058                 : node;
23059         }
23060         // @api
23061         function createObjectLiteralExpression(properties, multiLine) {
23062             var node = createBaseExpression(204 /* ObjectLiteralExpression */);
23063             node.properties = createNodeArray(properties);
23064             node.multiLine = multiLine;
23065             node.transformFlags |= propagateChildrenFlags(node.properties);
23066             return node;
23067         }
23068         // @api
23069         function updateObjectLiteralExpression(node, properties) {
23070             return node.properties !== properties
23071                 ? update(createObjectLiteralExpression(properties, node.multiLine), node)
23072                 : node;
23073         }
23074         // @api
23075         function createPropertyAccessExpression(expression, name) {
23076             var node = createBaseExpression(205 /* PropertyAccessExpression */);
23077             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23078             node.name = asName(name);
23079             node.transformFlags =
23080                 propagateChildFlags(node.expression) |
23081                     (ts.isIdentifier(node.name) ?
23082                         propagateIdentifierNameFlags(node.name) :
23083                         propagateChildFlags(node.name));
23084             if (ts.isSuperKeyword(expression)) {
23085                 // super method calls require a lexical 'this'
23086                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
23087                 node.transformFlags |=
23088                     128 /* ContainsES2017 */ |
23089                         64 /* ContainsES2018 */;
23090             }
23091             return node;
23092         }
23093         // @api
23094         function updatePropertyAccessExpression(node, expression, name) {
23095             if (ts.isPropertyAccessChain(node)) {
23096                 return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
23097             }
23098             return node.expression !== expression
23099                 || node.name !== name
23100                 ? update(createPropertyAccessExpression(expression, name), node)
23101                 : node;
23102         }
23103         // @api
23104         function createPropertyAccessChain(expression, questionDotToken, name) {
23105             var node = createBaseExpression(205 /* PropertyAccessExpression */);
23106             node.flags |= 32 /* OptionalChain */;
23107             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23108             node.questionDotToken = questionDotToken;
23109             node.name = asName(name);
23110             node.transformFlags |=
23111                 16 /* ContainsES2020 */ |
23112                     propagateChildFlags(node.expression) |
23113                     propagateChildFlags(node.questionDotToken) |
23114                     (ts.isIdentifier(node.name) ?
23115                         propagateIdentifierNameFlags(node.name) :
23116                         propagateChildFlags(node.name));
23117             return node;
23118         }
23119         // @api
23120         function updatePropertyAccessChain(node, expression, questionDotToken, name) {
23121             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
23122             // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
23123             // instead of using the default from createPropertyAccess
23124             return node.expression !== expression
23125                 || node.questionDotToken !== questionDotToken
23126                 || node.name !== name
23127                 ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
23128                 : node;
23129         }
23130         // @api
23131         function createElementAccessExpression(expression, index) {
23132             var node = createBaseExpression(206 /* ElementAccessExpression */);
23133             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23134             node.argumentExpression = asExpression(index);
23135             node.transformFlags |=
23136                 propagateChildFlags(node.expression) |
23137                     propagateChildFlags(node.argumentExpression);
23138             if (ts.isSuperKeyword(expression)) {
23139                 // super method calls require a lexical 'this'
23140                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
23141                 node.transformFlags |=
23142                     128 /* ContainsES2017 */ |
23143                         64 /* ContainsES2018 */;
23144             }
23145             return node;
23146         }
23147         // @api
23148         function updateElementAccessExpression(node, expression, argumentExpression) {
23149             if (ts.isElementAccessChain(node)) {
23150                 return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
23151             }
23152             return node.expression !== expression
23153                 || node.argumentExpression !== argumentExpression
23154                 ? update(createElementAccessExpression(expression, argumentExpression), node)
23155                 : node;
23156         }
23157         // @api
23158         function createElementAccessChain(expression, questionDotToken, index) {
23159             var node = createBaseExpression(206 /* ElementAccessExpression */);
23160             node.flags |= 32 /* OptionalChain */;
23161             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23162             node.questionDotToken = questionDotToken;
23163             node.argumentExpression = asExpression(index);
23164             node.transformFlags |=
23165                 propagateChildFlags(node.expression) |
23166                     propagateChildFlags(node.questionDotToken) |
23167                     propagateChildFlags(node.argumentExpression) |
23168                     16 /* ContainsES2020 */;
23169             return node;
23170         }
23171         // @api
23172         function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
23173             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
23174             // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
23175             // instead of using the default from createElementAccess
23176             return node.expression !== expression
23177                 || node.questionDotToken !== questionDotToken
23178                 || node.argumentExpression !== argumentExpression
23179                 ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
23180                 : node;
23181         }
23182         // @api
23183         function createCallExpression(expression, typeArguments, argumentsArray) {
23184             var node = createBaseExpression(207 /* CallExpression */);
23185             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23186             node.typeArguments = asNodeArray(typeArguments);
23187             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
23188             node.transformFlags |=
23189                 propagateChildFlags(node.expression) |
23190                     propagateChildrenFlags(node.typeArguments) |
23191                     propagateChildrenFlags(node.arguments);
23192             if (node.typeArguments) {
23193                 node.transformFlags |= 1 /* ContainsTypeScript */;
23194             }
23195             if (ts.isImportKeyword(node.expression)) {
23196                 node.transformFlags |= 4194304 /* ContainsDynamicImport */;
23197             }
23198             else if (ts.isSuperProperty(node.expression)) {
23199                 node.transformFlags |= 8192 /* ContainsLexicalThis */;
23200             }
23201             return node;
23202         }
23203         // @api
23204         function updateCallExpression(node, expression, typeArguments, argumentsArray) {
23205             if (ts.isCallChain(node)) {
23206                 return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
23207             }
23208             return node.expression !== expression
23209                 || node.typeArguments !== typeArguments
23210                 || node.arguments !== argumentsArray
23211                 ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
23212                 : node;
23213         }
23214         // @api
23215         function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
23216             var node = createBaseExpression(207 /* CallExpression */);
23217             node.flags |= 32 /* OptionalChain */;
23218             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23219             node.questionDotToken = questionDotToken;
23220             node.typeArguments = asNodeArray(typeArguments);
23221             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
23222             node.transformFlags |=
23223                 propagateChildFlags(node.expression) |
23224                     propagateChildFlags(node.questionDotToken) |
23225                     propagateChildrenFlags(node.typeArguments) |
23226                     propagateChildrenFlags(node.arguments) |
23227                     16 /* ContainsES2020 */;
23228             if (node.typeArguments) {
23229                 node.transformFlags |= 1 /* ContainsTypeScript */;
23230             }
23231             if (ts.isSuperProperty(node.expression)) {
23232                 node.transformFlags |= 8192 /* ContainsLexicalThis */;
23233             }
23234             return node;
23235         }
23236         // @api
23237         function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
23238             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
23239             return node.expression !== expression
23240                 || node.questionDotToken !== questionDotToken
23241                 || node.typeArguments !== typeArguments
23242                 || node.arguments !== argumentsArray
23243                 ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
23244                 : node;
23245         }
23246         // @api
23247         function createNewExpression(expression, typeArguments, argumentsArray) {
23248             var node = createBaseExpression(208 /* NewExpression */);
23249             node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
23250             node.typeArguments = asNodeArray(typeArguments);
23251             node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
23252             node.transformFlags |=
23253                 propagateChildFlags(node.expression) |
23254                     propagateChildrenFlags(node.typeArguments) |
23255                     propagateChildrenFlags(node.arguments) |
23256                     16 /* ContainsES2020 */;
23257             if (node.typeArguments) {
23258                 node.transformFlags |= 1 /* ContainsTypeScript */;
23259             }
23260             return node;
23261         }
23262         // @api
23263         function updateNewExpression(node, expression, typeArguments, argumentsArray) {
23264             return node.expression !== expression
23265                 || node.typeArguments !== typeArguments
23266                 || node.arguments !== argumentsArray
23267                 ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
23268                 : node;
23269         }
23270         // @api
23271         function createTaggedTemplateExpression(tag, typeArguments, template) {
23272             var node = createBaseExpression(209 /* TaggedTemplateExpression */);
23273             node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
23274             node.typeArguments = asNodeArray(typeArguments);
23275             node.template = template;
23276             node.transformFlags |=
23277                 propagateChildFlags(node.tag) |
23278                     propagateChildrenFlags(node.typeArguments) |
23279                     propagateChildFlags(node.template) |
23280                     512 /* ContainsES2015 */;
23281             if (node.typeArguments) {
23282                 node.transformFlags |= 1 /* ContainsTypeScript */;
23283             }
23284             if (ts.hasInvalidEscape(node.template)) {
23285                 node.transformFlags |= 64 /* ContainsES2018 */;
23286             }
23287             return node;
23288         }
23289         // @api
23290         function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
23291             return node.tag !== tag
23292                 || node.typeArguments !== typeArguments
23293                 || node.template !== template
23294                 ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
23295                 : node;
23296         }
23297         // @api
23298         function createTypeAssertion(type, expression) {
23299             var node = createBaseExpression(210 /* TypeAssertionExpression */);
23300             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
23301             node.type = type;
23302             node.transformFlags |=
23303                 propagateChildFlags(node.expression) |
23304                     propagateChildFlags(node.type) |
23305                     1 /* ContainsTypeScript */;
23306             return node;
23307         }
23308         // @api
23309         function updateTypeAssertion(node, type, expression) {
23310             return node.type !== type
23311                 || node.expression !== expression
23312                 ? update(createTypeAssertion(type, expression), node)
23313                 : node;
23314         }
23315         // @api
23316         function createParenthesizedExpression(expression) {
23317             var node = createBaseExpression(211 /* ParenthesizedExpression */);
23318             node.expression = expression;
23319             node.transformFlags = propagateChildFlags(node.expression);
23320             return node;
23321         }
23322         // @api
23323         function updateParenthesizedExpression(node, expression) {
23324             return node.expression !== expression
23325                 ? update(createParenthesizedExpression(expression), node)
23326                 : node;
23327         }
23328         // @api
23329         function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
23330             var node = createBaseFunctionLikeDeclaration(212 /* FunctionExpression */, 
23331             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
23332             node.asteriskToken = asteriskToken;
23333             node.transformFlags |= propagateChildFlags(node.asteriskToken);
23334             if (node.typeParameters) {
23335                 node.transformFlags |= 1 /* ContainsTypeScript */;
23336             }
23337             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
23338                 if (node.asteriskToken) {
23339                     node.transformFlags |= 64 /* ContainsES2018 */;
23340                 }
23341                 else {
23342                     node.transformFlags |= 128 /* ContainsES2017 */;
23343                 }
23344             }
23345             else if (node.asteriskToken) {
23346                 node.transformFlags |= 1024 /* ContainsGenerator */;
23347             }
23348             return node;
23349         }
23350         // @api
23351         function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
23352             return node.name !== name
23353                 || node.modifiers !== modifiers
23354                 || node.asteriskToken !== asteriskToken
23355                 || node.typeParameters !== typeParameters
23356                 || node.parameters !== parameters
23357                 || node.type !== type
23358                 || node.body !== body
23359                 ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
23360                 : node;
23361         }
23362         // @api
23363         function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
23364             var node = createBaseFunctionLikeDeclaration(213 /* ArrowFunction */, 
23365             /*decorators*/ undefined, modifiers, 
23366             /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
23367             node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
23368             node.transformFlags |=
23369                 propagateChildFlags(node.equalsGreaterThanToken) |
23370                     512 /* ContainsES2015 */;
23371             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
23372                 node.transformFlags |= 128 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */;
23373             }
23374             return node;
23375         }
23376         // @api
23377         function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
23378             return node.modifiers !== modifiers
23379                 || node.typeParameters !== typeParameters
23380                 || node.parameters !== parameters
23381                 || node.type !== type
23382                 || node.equalsGreaterThanToken !== equalsGreaterThanToken
23383                 || node.body !== body
23384                 ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
23385                 : node;
23386         }
23387         // @api
23388         function createDeleteExpression(expression) {
23389             var node = createBaseExpression(214 /* DeleteExpression */);
23390             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
23391             node.transformFlags |= propagateChildFlags(node.expression);
23392             return node;
23393         }
23394         // @api
23395         function updateDeleteExpression(node, expression) {
23396             return node.expression !== expression
23397                 ? update(createDeleteExpression(expression), node)
23398                 : node;
23399         }
23400         // @api
23401         function createTypeOfExpression(expression) {
23402             var node = createBaseExpression(215 /* TypeOfExpression */);
23403             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
23404             node.transformFlags |= propagateChildFlags(node.expression);
23405             return node;
23406         }
23407         // @api
23408         function updateTypeOfExpression(node, expression) {
23409             return node.expression !== expression
23410                 ? update(createTypeOfExpression(expression), node)
23411                 : node;
23412         }
23413         // @api
23414         function createVoidExpression(expression) {
23415             var node = createBaseExpression(216 /* VoidExpression */);
23416             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
23417             node.transformFlags |= propagateChildFlags(node.expression);
23418             return node;
23419         }
23420         // @api
23421         function updateVoidExpression(node, expression) {
23422             return node.expression !== expression
23423                 ? update(createVoidExpression(expression), node)
23424                 : node;
23425         }
23426         // @api
23427         function createAwaitExpression(expression) {
23428             var node = createBaseExpression(217 /* AwaitExpression */);
23429             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
23430             node.transformFlags |=
23431                 propagateChildFlags(node.expression) |
23432                     128 /* ContainsES2017 */ |
23433                     64 /* ContainsES2018 */ |
23434                     1048576 /* ContainsAwait */;
23435             return node;
23436         }
23437         // @api
23438         function updateAwaitExpression(node, expression) {
23439             return node.expression !== expression
23440                 ? update(createAwaitExpression(expression), node)
23441                 : node;
23442         }
23443         // @api
23444         function createPrefixUnaryExpression(operator, operand) {
23445             var node = createBaseExpression(218 /* PrefixUnaryExpression */);
23446             node.operator = operator;
23447             node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
23448             node.transformFlags |= propagateChildFlags(node.operand);
23449             // Only set this flag for non-generated identifiers and non-"local" names. See the
23450             // comment in `visitPreOrPostfixUnaryExpression` in module.ts
23451             if ((operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */) &&
23452                 ts.isIdentifier(node.operand) &&
23453                 !ts.isGeneratedIdentifier(node.operand) &&
23454                 !ts.isLocalName(node.operand)) {
23455                 node.transformFlags |= 67108864 /* ContainsUpdateExpressionForIdentifier */;
23456             }
23457             return node;
23458         }
23459         // @api
23460         function updatePrefixUnaryExpression(node, operand) {
23461             return node.operand !== operand
23462                 ? update(createPrefixUnaryExpression(node.operator, operand), node)
23463                 : node;
23464         }
23465         // @api
23466         function createPostfixUnaryExpression(operand, operator) {
23467             var node = createBaseExpression(219 /* PostfixUnaryExpression */);
23468             node.operator = operator;
23469             node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
23470             node.transformFlags |= propagateChildFlags(node.operand);
23471             // Only set this flag for non-generated identifiers and non-"local" names. See the
23472             // comment in `visitPreOrPostfixUnaryExpression` in module.ts
23473             if (ts.isIdentifier(node.operand) &&
23474                 !ts.isGeneratedIdentifier(node.operand) &&
23475                 !ts.isLocalName(node.operand)) {
23476                 node.transformFlags |= 67108864 /* ContainsUpdateExpressionForIdentifier */;
23477             }
23478             return node;
23479         }
23480         // @api
23481         function updatePostfixUnaryExpression(node, operand) {
23482             return node.operand !== operand
23483                 ? update(createPostfixUnaryExpression(operand, node.operator), node)
23484                 : node;
23485         }
23486         // @api
23487         function createBinaryExpression(left, operator, right) {
23488             var node = createBaseExpression(220 /* BinaryExpression */);
23489             var operatorToken = asToken(operator);
23490             var operatorKind = operatorToken.kind;
23491             node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
23492             node.operatorToken = operatorToken;
23493             node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
23494             node.transformFlags |=
23495                 propagateChildFlags(node.left) |
23496                     propagateChildFlags(node.operatorToken) |
23497                     propagateChildFlags(node.right);
23498             if (operatorKind === 60 /* QuestionQuestionToken */) {
23499                 node.transformFlags |= 16 /* ContainsES2020 */;
23500             }
23501             else if (operatorKind === 63 /* EqualsToken */) {
23502                 if (ts.isObjectLiteralExpression(node.left)) {
23503                     node.transformFlags |=
23504                         512 /* ContainsES2015 */ |
23505                             64 /* ContainsES2018 */ |
23506                             2048 /* ContainsDestructuringAssignment */ |
23507                             propagateAssignmentPatternFlags(node.left);
23508                 }
23509                 else if (ts.isArrayLiteralExpression(node.left)) {
23510                     node.transformFlags |=
23511                         512 /* ContainsES2015 */ |
23512                             2048 /* ContainsDestructuringAssignment */ |
23513                             propagateAssignmentPatternFlags(node.left);
23514                 }
23515             }
23516             else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 67 /* AsteriskAsteriskEqualsToken */) {
23517                 node.transformFlags |= 256 /* ContainsES2016 */;
23518             }
23519             else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
23520                 node.transformFlags |= 8 /* ContainsES2021 */;
23521             }
23522             return node;
23523         }
23524         function propagateAssignmentPatternFlags(node) {
23525             if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */)
23526                 return 32768 /* ContainsObjectRestOrSpread */;
23527             if (node.transformFlags & 64 /* ContainsES2018 */) {
23528                 // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
23529                 // will not be correctly interpreted by the ES2018 transformer
23530                 for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) {
23531                     var element = _a[_i];
23532                     var target = ts.getTargetOfBindingOrAssignmentElement(element);
23533                     if (target && ts.isAssignmentPattern(target)) {
23534                         if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
23535                             return 32768 /* ContainsObjectRestOrSpread */;
23536                         }
23537                         if (target.transformFlags & 64 /* ContainsES2018 */) {
23538                             var flags_1 = propagateAssignmentPatternFlags(target);
23539                             if (flags_1)
23540                                 return flags_1;
23541                         }
23542                     }
23543                 }
23544             }
23545             return 0 /* None */;
23546         }
23547         // @api
23548         function updateBinaryExpression(node, left, operator, right) {
23549             return node.left !== left
23550                 || node.operatorToken !== operator
23551                 || node.right !== right
23552                 ? update(createBinaryExpression(left, operator, right), node)
23553                 : node;
23554         }
23555         // @api
23556         function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
23557             var node = createBaseExpression(221 /* ConditionalExpression */);
23558             node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
23559             node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
23560             node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
23561             node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
23562             node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
23563             node.transformFlags |=
23564                 propagateChildFlags(node.condition) |
23565                     propagateChildFlags(node.questionToken) |
23566                     propagateChildFlags(node.whenTrue) |
23567                     propagateChildFlags(node.colonToken) |
23568                     propagateChildFlags(node.whenFalse);
23569             return node;
23570         }
23571         // @api
23572         function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
23573             return node.condition !== condition
23574                 || node.questionToken !== questionToken
23575                 || node.whenTrue !== whenTrue
23576                 || node.colonToken !== colonToken
23577                 || node.whenFalse !== whenFalse
23578                 ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
23579                 : node;
23580         }
23581         // @api
23582         function createTemplateExpression(head, templateSpans) {
23583             var node = createBaseExpression(222 /* TemplateExpression */);
23584             node.head = head;
23585             node.templateSpans = createNodeArray(templateSpans);
23586             node.transformFlags |=
23587                 propagateChildFlags(node.head) |
23588                     propagateChildrenFlags(node.templateSpans) |
23589                     512 /* ContainsES2015 */;
23590             return node;
23591         }
23592         // @api
23593         function updateTemplateExpression(node, head, templateSpans) {
23594             return node.head !== head
23595                 || node.templateSpans !== templateSpans
23596                 ? update(createTemplateExpression(head, templateSpans), node)
23597                 : node;
23598         }
23599         function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
23600             if (templateFlags === void 0) { templateFlags = 0 /* None */; }
23601             ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
23602             // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
23603             // eslint-disable-next-line no-undef-init
23604             var cooked = undefined;
23605             if (rawText !== undefined && rawText !== text) {
23606                 cooked = getCookedText(kind, rawText);
23607                 if (typeof cooked === "object") {
23608                     return ts.Debug.fail("Invalid raw text");
23609                 }
23610             }
23611             if (text === undefined) {
23612                 if (cooked === undefined) {
23613                     return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
23614                 }
23615                 text = cooked;
23616             }
23617             else if (cooked !== undefined) {
23618                 ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
23619             }
23620             return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
23621         }
23622         // @api
23623         function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
23624             var node = createBaseToken(kind);
23625             node.text = text;
23626             node.rawText = rawText;
23627             node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
23628             node.transformFlags |= 512 /* ContainsES2015 */;
23629             if (node.templateFlags) {
23630                 node.transformFlags |= 64 /* ContainsES2018 */;
23631             }
23632             return node;
23633         }
23634         // @api
23635         function createTemplateHead(text, rawText, templateFlags) {
23636             return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
23637         }
23638         // @api
23639         function createTemplateMiddle(text, rawText, templateFlags) {
23640             return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
23641         }
23642         // @api
23643         function createTemplateTail(text, rawText, templateFlags) {
23644             return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
23645         }
23646         // @api
23647         function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
23648             return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
23649         }
23650         // @api
23651         function createYieldExpression(asteriskToken, expression) {
23652             ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
23653             var node = createBaseExpression(223 /* YieldExpression */);
23654             node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23655             node.asteriskToken = asteriskToken;
23656             node.transformFlags |=
23657                 propagateChildFlags(node.expression) |
23658                     propagateChildFlags(node.asteriskToken) |
23659                     512 /* ContainsES2015 */ |
23660                     64 /* ContainsES2018 */ |
23661                     524288 /* ContainsYield */;
23662             return node;
23663         }
23664         // @api
23665         function updateYieldExpression(node, asteriskToken, expression) {
23666             return node.expression !== expression
23667                 || node.asteriskToken !== asteriskToken
23668                 ? update(createYieldExpression(asteriskToken, expression), node)
23669                 : node;
23670         }
23671         // @api
23672         function createSpreadElement(expression) {
23673             var node = createBaseExpression(224 /* SpreadElement */);
23674             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23675             node.transformFlags |=
23676                 propagateChildFlags(node.expression) |
23677                     512 /* ContainsES2015 */ |
23678                     16384 /* ContainsRestOrSpread */;
23679             return node;
23680         }
23681         // @api
23682         function updateSpreadElement(node, expression) {
23683             return node.expression !== expression
23684                 ? update(createSpreadElement(expression), node)
23685                 : node;
23686         }
23687         // @api
23688         function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
23689             var node = createBaseClassLikeDeclaration(225 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
23690             node.transformFlags |= 512 /* ContainsES2015 */;
23691             return node;
23692         }
23693         // @api
23694         function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
23695             return node.decorators !== decorators
23696                 || node.modifiers !== modifiers
23697                 || node.name !== name
23698                 || node.typeParameters !== typeParameters
23699                 || node.heritageClauses !== heritageClauses
23700                 || node.members !== members
23701                 ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
23702                 : node;
23703         }
23704         // @api
23705         function createOmittedExpression() {
23706             return createBaseExpression(226 /* OmittedExpression */);
23707         }
23708         // @api
23709         function createExpressionWithTypeArguments(expression, typeArguments) {
23710             var node = createBaseNode(227 /* ExpressionWithTypeArguments */);
23711             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23712             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
23713             node.transformFlags |=
23714                 propagateChildFlags(node.expression) |
23715                     propagateChildrenFlags(node.typeArguments) |
23716                     512 /* ContainsES2015 */;
23717             return node;
23718         }
23719         // @api
23720         function updateExpressionWithTypeArguments(node, expression, typeArguments) {
23721             return node.expression !== expression
23722                 || node.typeArguments !== typeArguments
23723                 ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
23724                 : node;
23725         }
23726         // @api
23727         function createAsExpression(expression, type) {
23728             var node = createBaseExpression(228 /* AsExpression */);
23729             node.expression = expression;
23730             node.type = type;
23731             node.transformFlags |=
23732                 propagateChildFlags(node.expression) |
23733                     propagateChildFlags(node.type) |
23734                     1 /* ContainsTypeScript */;
23735             return node;
23736         }
23737         // @api
23738         function updateAsExpression(node, expression, type) {
23739             return node.expression !== expression
23740                 || node.type !== type
23741                 ? update(createAsExpression(expression, type), node)
23742                 : node;
23743         }
23744         // @api
23745         function createNonNullExpression(expression) {
23746             var node = createBaseExpression(229 /* NonNullExpression */);
23747             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23748             node.transformFlags |=
23749                 propagateChildFlags(node.expression) |
23750                     1 /* ContainsTypeScript */;
23751             return node;
23752         }
23753         // @api
23754         function updateNonNullExpression(node, expression) {
23755             if (ts.isNonNullChain(node)) {
23756                 return updateNonNullChain(node, expression);
23757             }
23758             return node.expression !== expression
23759                 ? update(createNonNullExpression(expression), node)
23760                 : node;
23761         }
23762         // @api
23763         function createNonNullChain(expression) {
23764             var node = createBaseExpression(229 /* NonNullExpression */);
23765             node.flags |= 32 /* OptionalChain */;
23766             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
23767             node.transformFlags |=
23768                 propagateChildFlags(node.expression) |
23769                     1 /* ContainsTypeScript */;
23770             return node;
23771         }
23772         // @api
23773         function updateNonNullChain(node, expression) {
23774             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
23775             return node.expression !== expression
23776                 ? update(createNonNullChain(expression), node)
23777                 : node;
23778         }
23779         // @api
23780         function createMetaProperty(keywordToken, name) {
23781             var node = createBaseExpression(230 /* MetaProperty */);
23782             node.keywordToken = keywordToken;
23783             node.name = name;
23784             node.transformFlags |= propagateChildFlags(node.name);
23785             switch (keywordToken) {
23786                 case 103 /* NewKeyword */:
23787                     node.transformFlags |= 512 /* ContainsES2015 */;
23788                     break;
23789                 case 100 /* ImportKeyword */:
23790                     node.transformFlags |= 4 /* ContainsESNext */;
23791                     break;
23792                 default:
23793                     return ts.Debug.assertNever(keywordToken);
23794             }
23795             return node;
23796         }
23797         // @api
23798         function updateMetaProperty(node, name) {
23799             return node.name !== name
23800                 ? update(createMetaProperty(node.keywordToken, name), node)
23801                 : node;
23802         }
23803         //
23804         // Misc
23805         //
23806         // @api
23807         function createTemplateSpan(expression, literal) {
23808             var node = createBaseNode(232 /* TemplateSpan */);
23809             node.expression = expression;
23810             node.literal = literal;
23811             node.transformFlags |=
23812                 propagateChildFlags(node.expression) |
23813                     propagateChildFlags(node.literal) |
23814                     512 /* ContainsES2015 */;
23815             return node;
23816         }
23817         // @api
23818         function updateTemplateSpan(node, expression, literal) {
23819             return node.expression !== expression
23820                 || node.literal !== literal
23821                 ? update(createTemplateSpan(expression, literal), node)
23822                 : node;
23823         }
23824         // @api
23825         function createSemicolonClassElement() {
23826             var node = createBaseNode(233 /* SemicolonClassElement */);
23827             node.transformFlags |= 512 /* ContainsES2015 */;
23828             return node;
23829         }
23830         //
23831         // Element
23832         //
23833         // @api
23834         function createBlock(statements, multiLine) {
23835             var node = createBaseNode(234 /* Block */);
23836             node.statements = createNodeArray(statements);
23837             node.multiLine = multiLine;
23838             node.transformFlags |= propagateChildrenFlags(node.statements);
23839             return node;
23840         }
23841         // @api
23842         function updateBlock(node, statements) {
23843             return node.statements !== statements
23844                 ? update(createBlock(statements, node.multiLine), node)
23845                 : node;
23846         }
23847         // @api
23848         function createVariableStatement(modifiers, declarationList) {
23849             var node = createBaseDeclaration(236 /* VariableStatement */, /*decorators*/ undefined, modifiers);
23850             node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
23851             node.transformFlags |=
23852                 propagateChildFlags(node.declarationList);
23853             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23854                 node.transformFlags = 1 /* ContainsTypeScript */;
23855             }
23856             return node;
23857         }
23858         // @api
23859         function updateVariableStatement(node, modifiers, declarationList) {
23860             return node.modifiers !== modifiers
23861                 || node.declarationList !== declarationList
23862                 ? update(createVariableStatement(modifiers, declarationList), node)
23863                 : node;
23864         }
23865         // @api
23866         function createEmptyStatement() {
23867             return createBaseNode(235 /* EmptyStatement */);
23868         }
23869         // @api
23870         function createExpressionStatement(expression) {
23871             var node = createBaseNode(237 /* ExpressionStatement */);
23872             node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
23873             node.transformFlags |= propagateChildFlags(node.expression);
23874             return node;
23875         }
23876         // @api
23877         function updateExpressionStatement(node, expression) {
23878             return node.expression !== expression
23879                 ? update(createExpressionStatement(expression), node)
23880                 : node;
23881         }
23882         // @api
23883         function createIfStatement(expression, thenStatement, elseStatement) {
23884             var node = createBaseNode(238 /* IfStatement */);
23885             node.expression = expression;
23886             node.thenStatement = asEmbeddedStatement(thenStatement);
23887             node.elseStatement = asEmbeddedStatement(elseStatement);
23888             node.transformFlags |=
23889                 propagateChildFlags(node.expression) |
23890                     propagateChildFlags(node.thenStatement) |
23891                     propagateChildFlags(node.elseStatement);
23892             return node;
23893         }
23894         // @api
23895         function updateIfStatement(node, expression, thenStatement, elseStatement) {
23896             return node.expression !== expression
23897                 || node.thenStatement !== thenStatement
23898                 || node.elseStatement !== elseStatement
23899                 ? update(createIfStatement(expression, thenStatement, elseStatement), node)
23900                 : node;
23901         }
23902         // @api
23903         function createDoStatement(statement, expression) {
23904             var node = createBaseNode(239 /* DoStatement */);
23905             node.statement = asEmbeddedStatement(statement);
23906             node.expression = expression;
23907             node.transformFlags |=
23908                 propagateChildFlags(node.statement) |
23909                     propagateChildFlags(node.expression);
23910             return node;
23911         }
23912         // @api
23913         function updateDoStatement(node, statement, expression) {
23914             return node.statement !== statement
23915                 || node.expression !== expression
23916                 ? update(createDoStatement(statement, expression), node)
23917                 : node;
23918         }
23919         // @api
23920         function createWhileStatement(expression, statement) {
23921             var node = createBaseNode(240 /* WhileStatement */);
23922             node.expression = expression;
23923             node.statement = asEmbeddedStatement(statement);
23924             node.transformFlags |=
23925                 propagateChildFlags(node.expression) |
23926                     propagateChildFlags(node.statement);
23927             return node;
23928         }
23929         // @api
23930         function updateWhileStatement(node, expression, statement) {
23931             return node.expression !== expression
23932                 || node.statement !== statement
23933                 ? update(createWhileStatement(expression, statement), node)
23934                 : node;
23935         }
23936         // @api
23937         function createForStatement(initializer, condition, incrementor, statement) {
23938             var node = createBaseNode(241 /* ForStatement */);
23939             node.initializer = initializer;
23940             node.condition = condition;
23941             node.incrementor = incrementor;
23942             node.statement = asEmbeddedStatement(statement);
23943             node.transformFlags |=
23944                 propagateChildFlags(node.initializer) |
23945                     propagateChildFlags(node.condition) |
23946                     propagateChildFlags(node.incrementor) |
23947                     propagateChildFlags(node.statement);
23948             return node;
23949         }
23950         // @api
23951         function updateForStatement(node, initializer, condition, incrementor, statement) {
23952             return node.initializer !== initializer
23953                 || node.condition !== condition
23954                 || node.incrementor !== incrementor
23955                 || node.statement !== statement
23956                 ? update(createForStatement(initializer, condition, incrementor, statement), node)
23957                 : node;
23958         }
23959         // @api
23960         function createForInStatement(initializer, expression, statement) {
23961             var node = createBaseNode(242 /* ForInStatement */);
23962             node.initializer = initializer;
23963             node.expression = expression;
23964             node.statement = asEmbeddedStatement(statement);
23965             node.transformFlags |=
23966                 propagateChildFlags(node.initializer) |
23967                     propagateChildFlags(node.expression) |
23968                     propagateChildFlags(node.statement);
23969             return node;
23970         }
23971         // @api
23972         function updateForInStatement(node, initializer, expression, statement) {
23973             return node.initializer !== initializer
23974                 || node.expression !== expression
23975                 || node.statement !== statement
23976                 ? update(createForInStatement(initializer, expression, statement), node)
23977                 : node;
23978         }
23979         // @api
23980         function createForOfStatement(awaitModifier, initializer, expression, statement) {
23981             var node = createBaseNode(243 /* ForOfStatement */);
23982             node.awaitModifier = awaitModifier;
23983             node.initializer = initializer;
23984             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23985             node.statement = asEmbeddedStatement(statement);
23986             node.transformFlags |=
23987                 propagateChildFlags(node.awaitModifier) |
23988                     propagateChildFlags(node.initializer) |
23989                     propagateChildFlags(node.expression) |
23990                     propagateChildFlags(node.statement) |
23991                     512 /* ContainsES2015 */;
23992             if (awaitModifier)
23993                 node.transformFlags |= 64 /* ContainsES2018 */;
23994             return node;
23995         }
23996         // @api
23997         function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
23998             return node.awaitModifier !== awaitModifier
23999                 || node.initializer !== initializer
24000                 || node.expression !== expression
24001                 || node.statement !== statement
24002                 ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
24003                 : node;
24004         }
24005         // @api
24006         function createContinueStatement(label) {
24007             var node = createBaseNode(244 /* ContinueStatement */);
24008             node.label = asName(label);
24009             node.transformFlags |=
24010                 propagateChildFlags(node.label) |
24011                     2097152 /* ContainsHoistedDeclarationOrCompletion */;
24012             return node;
24013         }
24014         // @api
24015         function updateContinueStatement(node, label) {
24016             return node.label !== label
24017                 ? update(createContinueStatement(label), node)
24018                 : node;
24019         }
24020         // @api
24021         function createBreakStatement(label) {
24022             var node = createBaseNode(245 /* BreakStatement */);
24023             node.label = asName(label);
24024             node.transformFlags |=
24025                 propagateChildFlags(node.label) |
24026                     2097152 /* ContainsHoistedDeclarationOrCompletion */;
24027             return node;
24028         }
24029         // @api
24030         function updateBreakStatement(node, label) {
24031             return node.label !== label
24032                 ? update(createBreakStatement(label), node)
24033                 : node;
24034         }
24035         // @api
24036         function createReturnStatement(expression) {
24037             var node = createBaseNode(246 /* ReturnStatement */);
24038             node.expression = expression;
24039             // return in an ES2018 async generator must be awaited
24040             node.transformFlags |=
24041                 propagateChildFlags(node.expression) |
24042                     64 /* ContainsES2018 */ |
24043                     2097152 /* ContainsHoistedDeclarationOrCompletion */;
24044             return node;
24045         }
24046         // @api
24047         function updateReturnStatement(node, expression) {
24048             return node.expression !== expression
24049                 ? update(createReturnStatement(expression), node)
24050                 : node;
24051         }
24052         // @api
24053         function createWithStatement(expression, statement) {
24054             var node = createBaseNode(247 /* WithStatement */);
24055             node.expression = expression;
24056             node.statement = asEmbeddedStatement(statement);
24057             node.transformFlags |=
24058                 propagateChildFlags(node.expression) |
24059                     propagateChildFlags(node.statement);
24060             return node;
24061         }
24062         // @api
24063         function updateWithStatement(node, expression, statement) {
24064             return node.expression !== expression
24065                 || node.statement !== statement
24066                 ? update(createWithStatement(expression, statement), node)
24067                 : node;
24068         }
24069         // @api
24070         function createSwitchStatement(expression, caseBlock) {
24071             var node = createBaseNode(248 /* SwitchStatement */);
24072             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
24073             node.caseBlock = caseBlock;
24074             node.transformFlags |=
24075                 propagateChildFlags(node.expression) |
24076                     propagateChildFlags(node.caseBlock);
24077             return node;
24078         }
24079         // @api
24080         function updateSwitchStatement(node, expression, caseBlock) {
24081             return node.expression !== expression
24082                 || node.caseBlock !== caseBlock
24083                 ? update(createSwitchStatement(expression, caseBlock), node)
24084                 : node;
24085         }
24086         // @api
24087         function createLabeledStatement(label, statement) {
24088             var node = createBaseNode(249 /* LabeledStatement */);
24089             node.label = asName(label);
24090             node.statement = asEmbeddedStatement(statement);
24091             node.transformFlags |=
24092                 propagateChildFlags(node.label) |
24093                     propagateChildFlags(node.statement);
24094             return node;
24095         }
24096         // @api
24097         function updateLabeledStatement(node, label, statement) {
24098             return node.label !== label
24099                 || node.statement !== statement
24100                 ? update(createLabeledStatement(label, statement), node)
24101                 : node;
24102         }
24103         // @api
24104         function createThrowStatement(expression) {
24105             var node = createBaseNode(250 /* ThrowStatement */);
24106             node.expression = expression;
24107             node.transformFlags |= propagateChildFlags(node.expression);
24108             return node;
24109         }
24110         // @api
24111         function updateThrowStatement(node, expression) {
24112             return node.expression !== expression
24113                 ? update(createThrowStatement(expression), node)
24114                 : node;
24115         }
24116         // @api
24117         function createTryStatement(tryBlock, catchClause, finallyBlock) {
24118             var node = createBaseNode(251 /* TryStatement */);
24119             node.tryBlock = tryBlock;
24120             node.catchClause = catchClause;
24121             node.finallyBlock = finallyBlock;
24122             node.transformFlags |=
24123                 propagateChildFlags(node.tryBlock) |
24124                     propagateChildFlags(node.catchClause) |
24125                     propagateChildFlags(node.finallyBlock);
24126             return node;
24127         }
24128         // @api
24129         function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
24130             return node.tryBlock !== tryBlock
24131                 || node.catchClause !== catchClause
24132                 || node.finallyBlock !== finallyBlock
24133                 ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
24134                 : node;
24135         }
24136         // @api
24137         function createDebuggerStatement() {
24138             return createBaseNode(252 /* DebuggerStatement */);
24139         }
24140         // @api
24141         function createVariableDeclaration(name, exclamationToken, type, initializer) {
24142             var node = createBaseVariableLikeDeclaration(253 /* VariableDeclaration */, 
24143             /*decorators*/ undefined, 
24144             /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
24145             node.exclamationToken = exclamationToken;
24146             node.transformFlags |= propagateChildFlags(node.exclamationToken);
24147             if (exclamationToken) {
24148                 node.transformFlags |= 1 /* ContainsTypeScript */;
24149             }
24150             return node;
24151         }
24152         // @api
24153         function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
24154             return node.name !== name
24155                 || node.type !== type
24156                 || node.exclamationToken !== exclamationToken
24157                 || node.initializer !== initializer
24158                 ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
24159                 : node;
24160         }
24161         // @api
24162         function createVariableDeclarationList(declarations, flags) {
24163             if (flags === void 0) { flags = 0 /* None */; }
24164             var node = createBaseNode(254 /* VariableDeclarationList */);
24165             node.flags |= flags & 3 /* BlockScoped */;
24166             node.declarations = createNodeArray(declarations);
24167             node.transformFlags |=
24168                 propagateChildrenFlags(node.declarations) |
24169                     2097152 /* ContainsHoistedDeclarationOrCompletion */;
24170             if (flags & 3 /* BlockScoped */) {
24171                 node.transformFlags |=
24172                     512 /* ContainsES2015 */ |
24173                         131072 /* ContainsBlockScopedBinding */;
24174             }
24175             return node;
24176         }
24177         // @api
24178         function updateVariableDeclarationList(node, declarations) {
24179             return node.declarations !== declarations
24180                 ? update(createVariableDeclarationList(declarations, node.flags), node)
24181                 : node;
24182         }
24183         // @api
24184         function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
24185             var node = createBaseFunctionLikeDeclaration(255 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
24186             node.asteriskToken = asteriskToken;
24187             if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
24188                 node.transformFlags = 1 /* ContainsTypeScript */;
24189             }
24190             else {
24191                 node.transformFlags |=
24192                     propagateChildFlags(node.asteriskToken) |
24193                         2097152 /* ContainsHoistedDeclarationOrCompletion */;
24194                 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
24195                     if (node.asteriskToken) {
24196                         node.transformFlags |= 64 /* ContainsES2018 */;
24197                     }
24198                     else {
24199                         node.transformFlags |= 128 /* ContainsES2017 */;
24200                     }
24201                 }
24202                 else if (node.asteriskToken) {
24203                     node.transformFlags |= 1024 /* ContainsGenerator */;
24204                 }
24205             }
24206             return node;
24207         }
24208         // @api
24209         function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
24210             return node.decorators !== decorators
24211                 || node.modifiers !== modifiers
24212                 || node.asteriskToken !== asteriskToken
24213                 || node.name !== name
24214                 || node.typeParameters !== typeParameters
24215                 || node.parameters !== parameters
24216                 || node.type !== type
24217                 || node.body !== body
24218                 ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
24219                 : node;
24220         }
24221         // @api
24222         function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
24223             var node = createBaseClassLikeDeclaration(256 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
24224             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
24225                 node.transformFlags = 1 /* ContainsTypeScript */;
24226             }
24227             else {
24228                 node.transformFlags |= 512 /* ContainsES2015 */;
24229                 if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) {
24230                     node.transformFlags |= 1 /* ContainsTypeScript */;
24231                 }
24232             }
24233             return node;
24234         }
24235         // @api
24236         function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
24237             return node.decorators !== decorators
24238                 || node.modifiers !== modifiers
24239                 || node.name !== name
24240                 || node.typeParameters !== typeParameters
24241                 || node.heritageClauses !== heritageClauses
24242                 || node.members !== members
24243                 ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
24244                 : node;
24245         }
24246         // @api
24247         function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
24248             var node = createBaseInterfaceOrClassLikeDeclaration(257 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
24249             node.members = createNodeArray(members);
24250             node.transformFlags = 1 /* ContainsTypeScript */;
24251             return node;
24252         }
24253         // @api
24254         function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
24255             return node.decorators !== decorators
24256                 || node.modifiers !== modifiers
24257                 || node.name !== name
24258                 || node.typeParameters !== typeParameters
24259                 || node.heritageClauses !== heritageClauses
24260                 || node.members !== members
24261                 ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
24262                 : node;
24263         }
24264         // @api
24265         function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
24266             var node = createBaseGenericNamedDeclaration(258 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
24267             node.type = type;
24268             node.transformFlags = 1 /* ContainsTypeScript */;
24269             return node;
24270         }
24271         // @api
24272         function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
24273             return node.decorators !== decorators
24274                 || node.modifiers !== modifiers
24275                 || node.name !== name
24276                 || node.typeParameters !== typeParameters
24277                 || node.type !== type
24278                 ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
24279                 : node;
24280         }
24281         // @api
24282         function createEnumDeclaration(decorators, modifiers, name, members) {
24283             var node = createBaseNamedDeclaration(259 /* EnumDeclaration */, decorators, modifiers, name);
24284             node.members = createNodeArray(members);
24285             node.transformFlags |=
24286                 propagateChildrenFlags(node.members) |
24287                     1 /* ContainsTypeScript */;
24288             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
24289             return node;
24290         }
24291         // @api
24292         function updateEnumDeclaration(node, decorators, modifiers, name, members) {
24293             return node.decorators !== decorators
24294                 || node.modifiers !== modifiers
24295                 || node.name !== name
24296                 || node.members !== members
24297                 ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
24298                 : node;
24299         }
24300         // @api
24301         function createModuleDeclaration(decorators, modifiers, name, body, flags) {
24302             if (flags === void 0) { flags = 0 /* None */; }
24303             var node = createBaseDeclaration(260 /* ModuleDeclaration */, decorators, modifiers);
24304             node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
24305             node.name = name;
24306             node.body = body;
24307             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
24308                 node.transformFlags = 1 /* ContainsTypeScript */;
24309             }
24310             else {
24311                 node.transformFlags |=
24312                     propagateChildFlags(node.name) |
24313                         propagateChildFlags(node.body) |
24314                         1 /* ContainsTypeScript */;
24315             }
24316             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
24317             return node;
24318         }
24319         // @api
24320         function updateModuleDeclaration(node, decorators, modifiers, name, body) {
24321             return node.decorators !== decorators
24322                 || node.modifiers !== modifiers
24323                 || node.name !== name
24324                 || node.body !== body
24325                 ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
24326                 : node;
24327         }
24328         // @api
24329         function createModuleBlock(statements) {
24330             var node = createBaseNode(261 /* ModuleBlock */);
24331             node.statements = createNodeArray(statements);
24332             node.transformFlags |= propagateChildrenFlags(node.statements);
24333             return node;
24334         }
24335         // @api
24336         function updateModuleBlock(node, statements) {
24337             return node.statements !== statements
24338                 ? update(createModuleBlock(statements), node)
24339                 : node;
24340         }
24341         // @api
24342         function createCaseBlock(clauses) {
24343             var node = createBaseNode(262 /* CaseBlock */);
24344             node.clauses = createNodeArray(clauses);
24345             node.transformFlags |= propagateChildrenFlags(node.clauses);
24346             return node;
24347         }
24348         // @api
24349         function updateCaseBlock(node, clauses) {
24350             return node.clauses !== clauses
24351                 ? update(createCaseBlock(clauses), node)
24352                 : node;
24353         }
24354         // @api
24355         function createNamespaceExportDeclaration(name) {
24356             var node = createBaseNamedDeclaration(263 /* NamespaceExportDeclaration */, 
24357             /*decorators*/ undefined, 
24358             /*modifiers*/ undefined, name);
24359             node.transformFlags = 1 /* ContainsTypeScript */;
24360             return node;
24361         }
24362         // @api
24363         function updateNamespaceExportDeclaration(node, name) {
24364             return node.name !== name
24365                 ? update(createNamespaceExportDeclaration(name), node)
24366                 : node;
24367         }
24368         // @api
24369         function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) {
24370             var node = createBaseNamedDeclaration(264 /* ImportEqualsDeclaration */, decorators, modifiers, name);
24371             node.isTypeOnly = isTypeOnly;
24372             node.moduleReference = moduleReference;
24373             node.transformFlags |= propagateChildFlags(node.moduleReference);
24374             if (!ts.isExternalModuleReference(node.moduleReference))
24375                 node.transformFlags |= 1 /* ContainsTypeScript */;
24376             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
24377             return node;
24378         }
24379         // @api
24380         function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) {
24381             return node.decorators !== decorators
24382                 || node.modifiers !== modifiers
24383                 || node.isTypeOnly !== isTypeOnly
24384                 || node.name !== name
24385                 || node.moduleReference !== moduleReference
24386                 ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node)
24387                 : node;
24388         }
24389         // @api
24390         function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) {
24391             var node = createBaseDeclaration(265 /* ImportDeclaration */, decorators, modifiers);
24392             node.importClause = importClause;
24393             node.moduleSpecifier = moduleSpecifier;
24394             node.assertClause = assertClause;
24395             node.transformFlags |=
24396                 propagateChildFlags(node.importClause) |
24397                     propagateChildFlags(node.moduleSpecifier);
24398             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24399             return node;
24400         }
24401         // @api
24402         function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) {
24403             return node.decorators !== decorators
24404                 || node.modifiers !== modifiers
24405                 || node.importClause !== importClause
24406                 || node.moduleSpecifier !== moduleSpecifier
24407                 || node.assertClause !== assertClause
24408                 ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node)
24409                 : node;
24410         }
24411         // @api
24412         function createImportClause(isTypeOnly, name, namedBindings) {
24413             var node = createBaseNode(266 /* ImportClause */);
24414             node.isTypeOnly = isTypeOnly;
24415             node.name = name;
24416             node.namedBindings = namedBindings;
24417             node.transformFlags |=
24418                 propagateChildFlags(node.name) |
24419                     propagateChildFlags(node.namedBindings);
24420             if (isTypeOnly) {
24421                 node.transformFlags |= 1 /* ContainsTypeScript */;
24422             }
24423             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24424             return node;
24425         }
24426         // @api
24427         function updateImportClause(node, isTypeOnly, name, namedBindings) {
24428             return node.isTypeOnly !== isTypeOnly
24429                 || node.name !== name
24430                 || node.namedBindings !== namedBindings
24431                 ? update(createImportClause(isTypeOnly, name, namedBindings), node)
24432                 : node;
24433         }
24434         // @api
24435         function createAssertClause(elements, multiLine) {
24436             var node = createBaseNode(292 /* AssertClause */);
24437             node.elements = elements;
24438             node.multiLine = multiLine;
24439             node.transformFlags |= 4 /* ContainsESNext */;
24440             return node;
24441         }
24442         // @api
24443         function updateAssertClause(node, elements, multiLine) {
24444             return node.elements !== elements
24445                 || node.multiLine !== multiLine
24446                 ? update(createAssertClause(elements, multiLine), node)
24447                 : node;
24448         }
24449         // @api
24450         function createAssertEntry(name, value) {
24451             var node = createBaseNode(293 /* AssertEntry */);
24452             node.name = name;
24453             node.value = value;
24454             node.transformFlags |= 4 /* ContainsESNext */;
24455             return node;
24456         }
24457         // @api
24458         function updateAssertEntry(node, name, value) {
24459             return node.name !== name
24460                 || node.value !== value
24461                 ? update(createAssertEntry(name, value), node)
24462                 : node;
24463         }
24464         // @api
24465         function createNamespaceImport(name) {
24466             var node = createBaseNode(267 /* NamespaceImport */);
24467             node.name = name;
24468             node.transformFlags |= propagateChildFlags(node.name);
24469             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24470             return node;
24471         }
24472         // @api
24473         function updateNamespaceImport(node, name) {
24474             return node.name !== name
24475                 ? update(createNamespaceImport(name), node)
24476                 : node;
24477         }
24478         // @api
24479         function createNamespaceExport(name) {
24480             var node = createBaseNode(273 /* NamespaceExport */);
24481             node.name = name;
24482             node.transformFlags |=
24483                 propagateChildFlags(node.name) |
24484                     4 /* ContainsESNext */;
24485             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24486             return node;
24487         }
24488         // @api
24489         function updateNamespaceExport(node, name) {
24490             return node.name !== name
24491                 ? update(createNamespaceExport(name), node)
24492                 : node;
24493         }
24494         // @api
24495         function createNamedImports(elements) {
24496             var node = createBaseNode(268 /* NamedImports */);
24497             node.elements = createNodeArray(elements);
24498             node.transformFlags |= propagateChildrenFlags(node.elements);
24499             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24500             return node;
24501         }
24502         // @api
24503         function updateNamedImports(node, elements) {
24504             return node.elements !== elements
24505                 ? update(createNamedImports(elements), node)
24506                 : node;
24507         }
24508         // @api
24509         function createImportSpecifier(isTypeOnly, propertyName, name) {
24510             var node = createBaseNode(269 /* ImportSpecifier */);
24511             node.isTypeOnly = isTypeOnly;
24512             node.propertyName = propertyName;
24513             node.name = name;
24514             node.transformFlags |=
24515                 propagateChildFlags(node.propertyName) |
24516                     propagateChildFlags(node.name);
24517             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24518             return node;
24519         }
24520         // @api
24521         function updateImportSpecifier(node, isTypeOnly, propertyName, name) {
24522             return node.isTypeOnly !== isTypeOnly
24523                 || node.propertyName !== propertyName
24524                 || node.name !== name
24525                 ? update(createImportSpecifier(isTypeOnly, propertyName, name), node)
24526                 : node;
24527         }
24528         // @api
24529         function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
24530             var node = createBaseDeclaration(270 /* ExportAssignment */, decorators, modifiers);
24531             node.isExportEquals = isExportEquals;
24532             node.expression = isExportEquals
24533                 ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* EqualsToken */, /*leftSide*/ undefined, expression)
24534                 : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
24535             node.transformFlags |= propagateChildFlags(node.expression);
24536             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24537             return node;
24538         }
24539         // @api
24540         function updateExportAssignment(node, decorators, modifiers, expression) {
24541             return node.decorators !== decorators
24542                 || node.modifiers !== modifiers
24543                 || node.expression !== expression
24544                 ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
24545                 : node;
24546         }
24547         // @api
24548         function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) {
24549             var node = createBaseDeclaration(271 /* ExportDeclaration */, decorators, modifiers);
24550             node.isTypeOnly = isTypeOnly;
24551             node.exportClause = exportClause;
24552             node.moduleSpecifier = moduleSpecifier;
24553             node.assertClause = assertClause;
24554             node.transformFlags |=
24555                 propagateChildFlags(node.exportClause) |
24556                     propagateChildFlags(node.moduleSpecifier);
24557             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24558             return node;
24559         }
24560         // @api
24561         function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) {
24562             return node.decorators !== decorators
24563                 || node.modifiers !== modifiers
24564                 || node.isTypeOnly !== isTypeOnly
24565                 || node.exportClause !== exportClause
24566                 || node.moduleSpecifier !== moduleSpecifier
24567                 || node.assertClause !== assertClause
24568                 ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node)
24569                 : node;
24570         }
24571         // @api
24572         function createNamedExports(elements) {
24573             var node = createBaseNode(272 /* NamedExports */);
24574             node.elements = createNodeArray(elements);
24575             node.transformFlags |= propagateChildrenFlags(node.elements);
24576             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24577             return node;
24578         }
24579         // @api
24580         function updateNamedExports(node, elements) {
24581             return node.elements !== elements
24582                 ? update(createNamedExports(elements), node)
24583                 : node;
24584         }
24585         // @api
24586         function createExportSpecifier(isTypeOnly, propertyName, name) {
24587             var node = createBaseNode(274 /* ExportSpecifier */);
24588             node.isTypeOnly = isTypeOnly;
24589             node.propertyName = asName(propertyName);
24590             node.name = asName(name);
24591             node.transformFlags |=
24592                 propagateChildFlags(node.propertyName) |
24593                     propagateChildFlags(node.name);
24594             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24595             return node;
24596         }
24597         // @api
24598         function updateExportSpecifier(node, isTypeOnly, propertyName, name) {
24599             return node.isTypeOnly !== isTypeOnly
24600                 || node.propertyName !== propertyName
24601                 || node.name !== name
24602                 ? update(createExportSpecifier(isTypeOnly, propertyName, name), node)
24603                 : node;
24604         }
24605         // @api
24606         function createMissingDeclaration() {
24607             var node = createBaseDeclaration(275 /* MissingDeclaration */, 
24608             /*decorators*/ undefined, 
24609             /*modifiers*/ undefined);
24610             return node;
24611         }
24612         //
24613         // Module references
24614         //
24615         // @api
24616         function createExternalModuleReference(expression) {
24617             var node = createBaseNode(276 /* ExternalModuleReference */);
24618             node.expression = expression;
24619             node.transformFlags |= propagateChildFlags(node.expression);
24620             node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
24621             return node;
24622         }
24623         // @api
24624         function updateExternalModuleReference(node, expression) {
24625             return node.expression !== expression
24626                 ? update(createExternalModuleReference(expression), node)
24627                 : node;
24628         }
24629         //
24630         // JSDoc
24631         //
24632         // @api
24633         // createJSDocAllType
24634         // createJSDocUnknownType
24635         function createJSDocPrimaryTypeWorker(kind) {
24636             return createBaseNode(kind);
24637         }
24638         // @api
24639         // createJSDocNonNullableType
24640         // createJSDocNullableType
24641         // createJSDocOptionalType
24642         // createJSDocVariadicType
24643         // createJSDocNamepathType
24644         function createJSDocUnaryTypeWorker(kind, type) {
24645             var node = createBaseNode(kind);
24646             node.type = type;
24647             return node;
24648         }
24649         // @api
24650         // updateJSDocNonNullableType
24651         // updateJSDocNullableType
24652         // updateJSDocOptionalType
24653         // updateJSDocVariadicType
24654         // updateJSDocNamepathType
24655         function updateJSDocUnaryTypeWorker(kind, node, type) {
24656             return node.type !== type
24657                 ? update(createJSDocUnaryTypeWorker(kind, type), node)
24658                 : node;
24659         }
24660         // @api
24661         function createJSDocFunctionType(parameters, type) {
24662             var node = createBaseSignatureDeclaration(315 /* JSDocFunctionType */, 
24663             /*decorators*/ undefined, 
24664             /*modifiers*/ undefined, 
24665             /*name*/ undefined, 
24666             /*typeParameters*/ undefined, parameters, type);
24667             return node;
24668         }
24669         // @api
24670         function updateJSDocFunctionType(node, parameters, type) {
24671             return node.parameters !== parameters
24672                 || node.type !== type
24673                 ? update(createJSDocFunctionType(parameters, type), node)
24674                 : node;
24675         }
24676         // @api
24677         function createJSDocTypeLiteral(propertyTags, isArrayType) {
24678             if (isArrayType === void 0) { isArrayType = false; }
24679             var node = createBaseNode(320 /* JSDocTypeLiteral */);
24680             node.jsDocPropertyTags = asNodeArray(propertyTags);
24681             node.isArrayType = isArrayType;
24682             return node;
24683         }
24684         // @api
24685         function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
24686             return node.jsDocPropertyTags !== propertyTags
24687                 || node.isArrayType !== isArrayType
24688                 ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
24689                 : node;
24690         }
24691         // @api
24692         function createJSDocTypeExpression(type) {
24693             var node = createBaseNode(307 /* JSDocTypeExpression */);
24694             node.type = type;
24695             return node;
24696         }
24697         // @api
24698         function updateJSDocTypeExpression(node, type) {
24699             return node.type !== type
24700                 ? update(createJSDocTypeExpression(type), node)
24701                 : node;
24702         }
24703         // @api
24704         function createJSDocSignature(typeParameters, parameters, type) {
24705             var node = createBaseNode(321 /* JSDocSignature */);
24706             node.typeParameters = asNodeArray(typeParameters);
24707             node.parameters = createNodeArray(parameters);
24708             node.type = type;
24709             return node;
24710         }
24711         // @api
24712         function updateJSDocSignature(node, typeParameters, parameters, type) {
24713             return node.typeParameters !== typeParameters
24714                 || node.parameters !== parameters
24715                 || node.type !== type
24716                 ? update(createJSDocSignature(typeParameters, parameters, type), node)
24717                 : node;
24718         }
24719         function getDefaultTagName(node) {
24720             var defaultTagName = getDefaultTagNameForKind(node.kind);
24721             return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
24722                 ? node.tagName
24723                 : createIdentifier(defaultTagName);
24724         }
24725         // @api
24726         function createBaseJSDocTag(kind, tagName, comment) {
24727             var node = createBaseNode(kind);
24728             node.tagName = tagName;
24729             node.comment = comment;
24730             return node;
24731         }
24732         // @api
24733         function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
24734             var node = createBaseJSDocTag(342 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
24735             node.constraint = constraint;
24736             node.typeParameters = createNodeArray(typeParameters);
24737             return node;
24738         }
24739         // @api
24740         function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
24741             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24742             return node.tagName !== tagName
24743                 || node.constraint !== constraint
24744                 || node.typeParameters !== typeParameters
24745                 || node.comment !== comment
24746                 ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
24747                 : node;
24748         }
24749         // @api
24750         function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
24751             var node = createBaseJSDocTag(343 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
24752             node.typeExpression = typeExpression;
24753             node.fullName = fullName;
24754             node.name = ts.getJSDocTypeAliasName(fullName);
24755             return node;
24756         }
24757         // @api
24758         function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
24759             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24760             return node.tagName !== tagName
24761                 || node.typeExpression !== typeExpression
24762                 || node.fullName !== fullName
24763                 || node.comment !== comment
24764                 ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
24765                 : node;
24766         }
24767         // @api
24768         function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
24769             var node = createBaseJSDocTag(338 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
24770             node.typeExpression = typeExpression;
24771             node.name = name;
24772             node.isNameFirst = !!isNameFirst;
24773             node.isBracketed = isBracketed;
24774             return node;
24775         }
24776         // @api
24777         function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
24778             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24779             return node.tagName !== tagName
24780                 || node.name !== name
24781                 || node.isBracketed !== isBracketed
24782                 || node.typeExpression !== typeExpression
24783                 || node.isNameFirst !== isNameFirst
24784                 || node.comment !== comment
24785                 ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
24786                 : node;
24787         }
24788         // @api
24789         function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
24790             var node = createBaseJSDocTag(345 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
24791             node.typeExpression = typeExpression;
24792             node.name = name;
24793             node.isNameFirst = !!isNameFirst;
24794             node.isBracketed = isBracketed;
24795             return node;
24796         }
24797         // @api
24798         function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
24799             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24800             return node.tagName !== tagName
24801                 || node.name !== name
24802                 || node.isBracketed !== isBracketed
24803                 || node.typeExpression !== typeExpression
24804                 || node.isNameFirst !== isNameFirst
24805                 || node.comment !== comment
24806                 ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
24807                 : node;
24808         }
24809         // @api
24810         function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
24811             var node = createBaseJSDocTag(336 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
24812             node.typeExpression = typeExpression;
24813             node.fullName = fullName;
24814             node.name = ts.getJSDocTypeAliasName(fullName);
24815             return node;
24816         }
24817         // @api
24818         function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
24819             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24820             return node.tagName !== tagName
24821                 || node.typeExpression !== typeExpression
24822                 || node.fullName !== fullName
24823                 || node.comment !== comment
24824                 ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
24825                 : node;
24826         }
24827         // @api
24828         function createJSDocAugmentsTag(tagName, className, comment) {
24829             var node = createBaseJSDocTag(326 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
24830             node.class = className;
24831             return node;
24832         }
24833         // @api
24834         function updateJSDocAugmentsTag(node, tagName, className, comment) {
24835             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24836             return node.tagName !== tagName
24837                 || node.class !== className
24838                 || node.comment !== comment
24839                 ? update(createJSDocAugmentsTag(tagName, className, comment), node)
24840                 : node;
24841         }
24842         // @api
24843         function createJSDocImplementsTag(tagName, className, comment) {
24844             var node = createBaseJSDocTag(327 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
24845             node.class = className;
24846             return node;
24847         }
24848         // @api
24849         function createJSDocSeeTag(tagName, name, comment) {
24850             var node = createBaseJSDocTag(344 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment);
24851             node.name = name;
24852             return node;
24853         }
24854         // @api
24855         function updateJSDocSeeTag(node, tagName, name, comment) {
24856             return node.tagName !== tagName
24857                 || node.name !== name
24858                 || node.comment !== comment
24859                 ? update(createJSDocSeeTag(tagName, name, comment), node)
24860                 : node;
24861         }
24862         // @api
24863         function createJSDocNameReference(name) {
24864             var node = createBaseNode(308 /* JSDocNameReference */);
24865             node.name = name;
24866             return node;
24867         }
24868         // @api
24869         function updateJSDocNameReference(node, name) {
24870             return node.name !== name
24871                 ? update(createJSDocNameReference(name), node)
24872                 : node;
24873         }
24874         // @api
24875         function createJSDocMemberName(left, right) {
24876             var node = createBaseNode(309 /* JSDocMemberName */);
24877             node.left = left;
24878             node.right = right;
24879             node.transformFlags |=
24880                 propagateChildFlags(node.left) |
24881                     propagateChildFlags(node.right);
24882             return node;
24883         }
24884         // @api
24885         function updateJSDocMemberName(node, left, right) {
24886             return node.left !== left
24887                 || node.right !== right
24888                 ? update(createJSDocMemberName(left, right), node)
24889                 : node;
24890         }
24891         // @api
24892         function createJSDocLink(name, text) {
24893             var node = createBaseNode(322 /* JSDocLink */);
24894             node.name = name;
24895             node.text = text;
24896             return node;
24897         }
24898         // @api
24899         function updateJSDocLink(node, name, text) {
24900             return node.name !== name
24901                 ? update(createJSDocLink(name, text), node)
24902                 : node;
24903         }
24904         // @api
24905         function createJSDocLinkCode(name, text) {
24906             var node = createBaseNode(323 /* JSDocLinkCode */);
24907             node.name = name;
24908             node.text = text;
24909             return node;
24910         }
24911         // @api
24912         function updateJSDocLinkCode(node, name, text) {
24913             return node.name !== name
24914                 ? update(createJSDocLinkCode(name, text), node)
24915                 : node;
24916         }
24917         // @api
24918         function createJSDocLinkPlain(name, text) {
24919             var node = createBaseNode(324 /* JSDocLinkPlain */);
24920             node.name = name;
24921             node.text = text;
24922             return node;
24923         }
24924         // @api
24925         function updateJSDocLinkPlain(node, name, text) {
24926             return node.name !== name
24927                 ? update(createJSDocLinkPlain(name, text), node)
24928                 : node;
24929         }
24930         // @api
24931         function updateJSDocImplementsTag(node, tagName, className, comment) {
24932             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24933             return node.tagName !== tagName
24934                 || node.class !== className
24935                 || node.comment !== comment
24936                 ? update(createJSDocImplementsTag(tagName, className, comment), node)
24937                 : node;
24938         }
24939         // @api
24940         // createJSDocAuthorTag
24941         // createJSDocClassTag
24942         // createJSDocPublicTag
24943         // createJSDocPrivateTag
24944         // createJSDocProtectedTag
24945         // createJSDocReadonlyTag
24946         // createJSDocDeprecatedTag
24947         function createJSDocSimpleTagWorker(kind, tagName, comment) {
24948             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
24949             return node;
24950         }
24951         // @api
24952         // updateJSDocAuthorTag
24953         // updateJSDocClassTag
24954         // updateJSDocPublicTag
24955         // updateJSDocPrivateTag
24956         // updateJSDocProtectedTag
24957         // updateJSDocReadonlyTag
24958         // updateJSDocDeprecatedTag
24959         function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
24960             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24961             return node.tagName !== tagName
24962                 || node.comment !== comment
24963                 ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
24964                 node;
24965         }
24966         // @api
24967         // createJSDocTypeTag
24968         // createJSDocReturnTag
24969         // createJSDocThisTag
24970         // createJSDocEnumTag
24971         function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
24972             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
24973             node.typeExpression = typeExpression;
24974             return node;
24975         }
24976         // @api
24977         // updateJSDocTypeTag
24978         // updateJSDocReturnTag
24979         // updateJSDocThisTag
24980         // updateJSDocEnumTag
24981         function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
24982             if (tagName === void 0) { tagName = getDefaultTagName(node); }
24983             return node.tagName !== tagName
24984                 || node.typeExpression !== typeExpression
24985                 || node.comment !== comment
24986                 ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
24987                 : node;
24988         }
24989         // @api
24990         function createJSDocUnknownTag(tagName, comment) {
24991             var node = createBaseJSDocTag(325 /* JSDocTag */, tagName, comment);
24992             return node;
24993         }
24994         // @api
24995         function updateJSDocUnknownTag(node, tagName, comment) {
24996             return node.tagName !== tagName
24997                 || node.comment !== comment
24998                 ? update(createJSDocUnknownTag(tagName, comment), node)
24999                 : node;
25000         }
25001         // @api
25002         function createJSDocText(text) {
25003             var node = createBaseNode(319 /* JSDocText */);
25004             node.text = text;
25005             return node;
25006         }
25007         // @api
25008         function updateJSDocText(node, text) {
25009             return node.text !== text
25010                 ? update(createJSDocText(text), node)
25011                 : node;
25012         }
25013         // @api
25014         function createJSDocComment(comment, tags) {
25015             var node = createBaseNode(318 /* JSDocComment */);
25016             node.comment = comment;
25017             node.tags = asNodeArray(tags);
25018             return node;
25019         }
25020         // @api
25021         function updateJSDocComment(node, comment, tags) {
25022             return node.comment !== comment
25023                 || node.tags !== tags
25024                 ? update(createJSDocComment(comment, tags), node)
25025                 : node;
25026         }
25027         //
25028         // JSX
25029         //
25030         // @api
25031         function createJsxElement(openingElement, children, closingElement) {
25032             var node = createBaseNode(277 /* JsxElement */);
25033             node.openingElement = openingElement;
25034             node.children = createNodeArray(children);
25035             node.closingElement = closingElement;
25036             node.transformFlags |=
25037                 propagateChildFlags(node.openingElement) |
25038                     propagateChildrenFlags(node.children) |
25039                     propagateChildFlags(node.closingElement) |
25040                     2 /* ContainsJsx */;
25041             return node;
25042         }
25043         // @api
25044         function updateJsxElement(node, openingElement, children, closingElement) {
25045             return node.openingElement !== openingElement
25046                 || node.children !== children
25047                 || node.closingElement !== closingElement
25048                 ? update(createJsxElement(openingElement, children, closingElement), node)
25049                 : node;
25050         }
25051         // @api
25052         function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
25053             var node = createBaseNode(278 /* JsxSelfClosingElement */);
25054             node.tagName = tagName;
25055             node.typeArguments = asNodeArray(typeArguments);
25056             node.attributes = attributes;
25057             node.transformFlags |=
25058                 propagateChildFlags(node.tagName) |
25059                     propagateChildrenFlags(node.typeArguments) |
25060                     propagateChildFlags(node.attributes) |
25061                     2 /* ContainsJsx */;
25062             if (node.typeArguments) {
25063                 node.transformFlags |= 1 /* ContainsTypeScript */;
25064             }
25065             return node;
25066         }
25067         // @api
25068         function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
25069             return node.tagName !== tagName
25070                 || node.typeArguments !== typeArguments
25071                 || node.attributes !== attributes
25072                 ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
25073                 : node;
25074         }
25075         // @api
25076         function createJsxOpeningElement(tagName, typeArguments, attributes) {
25077             var node = createBaseNode(279 /* JsxOpeningElement */);
25078             node.tagName = tagName;
25079             node.typeArguments = asNodeArray(typeArguments);
25080             node.attributes = attributes;
25081             node.transformFlags |=
25082                 propagateChildFlags(node.tagName) |
25083                     propagateChildrenFlags(node.typeArguments) |
25084                     propagateChildFlags(node.attributes) |
25085                     2 /* ContainsJsx */;
25086             if (typeArguments) {
25087                 node.transformFlags |= 1 /* ContainsTypeScript */;
25088             }
25089             return node;
25090         }
25091         // @api
25092         function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
25093             return node.tagName !== tagName
25094                 || node.typeArguments !== typeArguments
25095                 || node.attributes !== attributes
25096                 ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
25097                 : node;
25098         }
25099         // @api
25100         function createJsxClosingElement(tagName) {
25101             var node = createBaseNode(280 /* JsxClosingElement */);
25102             node.tagName = tagName;
25103             node.transformFlags |=
25104                 propagateChildFlags(node.tagName) |
25105                     2 /* ContainsJsx */;
25106             return node;
25107         }
25108         // @api
25109         function updateJsxClosingElement(node, tagName) {
25110             return node.tagName !== tagName
25111                 ? update(createJsxClosingElement(tagName), node)
25112                 : node;
25113         }
25114         // @api
25115         function createJsxFragment(openingFragment, children, closingFragment) {
25116             var node = createBaseNode(281 /* JsxFragment */);
25117             node.openingFragment = openingFragment;
25118             node.children = createNodeArray(children);
25119             node.closingFragment = closingFragment;
25120             node.transformFlags |=
25121                 propagateChildFlags(node.openingFragment) |
25122                     propagateChildrenFlags(node.children) |
25123                     propagateChildFlags(node.closingFragment) |
25124                     2 /* ContainsJsx */;
25125             return node;
25126         }
25127         // @api
25128         function updateJsxFragment(node, openingFragment, children, closingFragment) {
25129             return node.openingFragment !== openingFragment
25130                 || node.children !== children
25131                 || node.closingFragment !== closingFragment
25132                 ? update(createJsxFragment(openingFragment, children, closingFragment), node)
25133                 : node;
25134         }
25135         // @api
25136         function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
25137             var node = createBaseNode(11 /* JsxText */);
25138             node.text = text;
25139             node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
25140             node.transformFlags |= 2 /* ContainsJsx */;
25141             return node;
25142         }
25143         // @api
25144         function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
25145             return node.text !== text
25146                 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
25147                 ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
25148                 : node;
25149         }
25150         // @api
25151         function createJsxOpeningFragment() {
25152             var node = createBaseNode(282 /* JsxOpeningFragment */);
25153             node.transformFlags |= 2 /* ContainsJsx */;
25154             return node;
25155         }
25156         // @api
25157         function createJsxJsxClosingFragment() {
25158             var node = createBaseNode(283 /* JsxClosingFragment */);
25159             node.transformFlags |= 2 /* ContainsJsx */;
25160             return node;
25161         }
25162         // @api
25163         function createJsxAttribute(name, initializer) {
25164             var node = createBaseNode(284 /* JsxAttribute */);
25165             node.name = name;
25166             node.initializer = initializer;
25167             node.transformFlags |=
25168                 propagateChildFlags(node.name) |
25169                     propagateChildFlags(node.initializer) |
25170                     2 /* ContainsJsx */;
25171             return node;
25172         }
25173         // @api
25174         function updateJsxAttribute(node, name, initializer) {
25175             return node.name !== name
25176                 || node.initializer !== initializer
25177                 ? update(createJsxAttribute(name, initializer), node)
25178                 : node;
25179         }
25180         // @api
25181         function createJsxAttributes(properties) {
25182             var node = createBaseNode(285 /* JsxAttributes */);
25183             node.properties = createNodeArray(properties);
25184             node.transformFlags |=
25185                 propagateChildrenFlags(node.properties) |
25186                     2 /* ContainsJsx */;
25187             return node;
25188         }
25189         // @api
25190         function updateJsxAttributes(node, properties) {
25191             return node.properties !== properties
25192                 ? update(createJsxAttributes(properties), node)
25193                 : node;
25194         }
25195         // @api
25196         function createJsxSpreadAttribute(expression) {
25197             var node = createBaseNode(286 /* JsxSpreadAttribute */);
25198             node.expression = expression;
25199             node.transformFlags |=
25200                 propagateChildFlags(node.expression) |
25201                     2 /* ContainsJsx */;
25202             return node;
25203         }
25204         // @api
25205         function updateJsxSpreadAttribute(node, expression) {
25206             return node.expression !== expression
25207                 ? update(createJsxSpreadAttribute(expression), node)
25208                 : node;
25209         }
25210         // @api
25211         function createJsxExpression(dotDotDotToken, expression) {
25212             var node = createBaseNode(287 /* JsxExpression */);
25213             node.dotDotDotToken = dotDotDotToken;
25214             node.expression = expression;
25215             node.transformFlags |=
25216                 propagateChildFlags(node.dotDotDotToken) |
25217                     propagateChildFlags(node.expression) |
25218                     2 /* ContainsJsx */;
25219             return node;
25220         }
25221         // @api
25222         function updateJsxExpression(node, expression) {
25223             return node.expression !== expression
25224                 ? update(createJsxExpression(node.dotDotDotToken, expression), node)
25225                 : node;
25226         }
25227         //
25228         // Clauses
25229         //
25230         // @api
25231         function createCaseClause(expression, statements) {
25232             var node = createBaseNode(288 /* CaseClause */);
25233             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
25234             node.statements = createNodeArray(statements);
25235             node.transformFlags |=
25236                 propagateChildFlags(node.expression) |
25237                     propagateChildrenFlags(node.statements);
25238             return node;
25239         }
25240         // @api
25241         function updateCaseClause(node, expression, statements) {
25242             return node.expression !== expression
25243                 || node.statements !== statements
25244                 ? update(createCaseClause(expression, statements), node)
25245                 : node;
25246         }
25247         // @api
25248         function createDefaultClause(statements) {
25249             var node = createBaseNode(289 /* DefaultClause */);
25250             node.statements = createNodeArray(statements);
25251             node.transformFlags = propagateChildrenFlags(node.statements);
25252             return node;
25253         }
25254         // @api
25255         function updateDefaultClause(node, statements) {
25256             return node.statements !== statements
25257                 ? update(createDefaultClause(statements), node)
25258                 : node;
25259         }
25260         // @api
25261         function createHeritageClause(token, types) {
25262             var node = createBaseNode(290 /* HeritageClause */);
25263             node.token = token;
25264             node.types = createNodeArray(types);
25265             node.transformFlags |= propagateChildrenFlags(node.types);
25266             switch (token) {
25267                 case 94 /* ExtendsKeyword */:
25268                     node.transformFlags |= 512 /* ContainsES2015 */;
25269                     break;
25270                 case 117 /* ImplementsKeyword */:
25271                     node.transformFlags |= 1 /* ContainsTypeScript */;
25272                     break;
25273                 default:
25274                     return ts.Debug.assertNever(token);
25275             }
25276             return node;
25277         }
25278         // @api
25279         function updateHeritageClause(node, types) {
25280             return node.types !== types
25281                 ? update(createHeritageClause(node.token, types), node)
25282                 : node;
25283         }
25284         // @api
25285         function createCatchClause(variableDeclaration, block) {
25286             var node = createBaseNode(291 /* CatchClause */);
25287             if (typeof variableDeclaration === "string" || variableDeclaration && !ts.isVariableDeclaration(variableDeclaration)) {
25288                 variableDeclaration = createVariableDeclaration(variableDeclaration, 
25289                 /*exclamationToken*/ undefined, 
25290                 /*type*/ undefined, 
25291                 /*initializer*/ undefined);
25292             }
25293             node.variableDeclaration = variableDeclaration;
25294             node.block = block;
25295             node.transformFlags |=
25296                 propagateChildFlags(node.variableDeclaration) |
25297                     propagateChildFlags(node.block);
25298             if (!variableDeclaration)
25299                 node.transformFlags |= 32 /* ContainsES2019 */;
25300             return node;
25301         }
25302         // @api
25303         function updateCatchClause(node, variableDeclaration, block) {
25304             return node.variableDeclaration !== variableDeclaration
25305                 || node.block !== block
25306                 ? update(createCatchClause(variableDeclaration, block), node)
25307                 : node;
25308         }
25309         //
25310         // Property assignments
25311         //
25312         // @api
25313         function createPropertyAssignment(name, initializer) {
25314             var node = createBaseNamedDeclaration(294 /* PropertyAssignment */, 
25315             /*decorators*/ undefined, 
25316             /*modifiers*/ undefined, name);
25317             node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
25318             node.transformFlags |=
25319                 propagateChildFlags(node.name) |
25320                     propagateChildFlags(node.initializer);
25321             return node;
25322         }
25323         function finishUpdatePropertyAssignment(updated, original) {
25324             // copy children used only for error reporting
25325             if (original.decorators)
25326                 updated.decorators = original.decorators;
25327             if (original.modifiers)
25328                 updated.modifiers = original.modifiers;
25329             if (original.questionToken)
25330                 updated.questionToken = original.questionToken;
25331             if (original.exclamationToken)
25332                 updated.exclamationToken = original.exclamationToken;
25333             return update(updated, original);
25334         }
25335         // @api
25336         function updatePropertyAssignment(node, name, initializer) {
25337             return node.name !== name
25338                 || node.initializer !== initializer
25339                 ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
25340                 : node;
25341         }
25342         // @api
25343         function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
25344             var node = createBaseNamedDeclaration(295 /* ShorthandPropertyAssignment */, 
25345             /*decorators*/ undefined, 
25346             /*modifiers*/ undefined, name);
25347             node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
25348             node.transformFlags |=
25349                 propagateChildFlags(node.objectAssignmentInitializer) |
25350                     512 /* ContainsES2015 */;
25351             return node;
25352         }
25353         function finishUpdateShorthandPropertyAssignment(updated, original) {
25354             // copy children used only for error reporting
25355             if (original.decorators)
25356                 updated.decorators = original.decorators;
25357             if (original.modifiers)
25358                 updated.modifiers = original.modifiers;
25359             if (original.equalsToken)
25360                 updated.equalsToken = original.equalsToken;
25361             if (original.questionToken)
25362                 updated.questionToken = original.questionToken;
25363             if (original.exclamationToken)
25364                 updated.exclamationToken = original.exclamationToken;
25365             return update(updated, original);
25366         }
25367         // @api
25368         function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
25369             return node.name !== name
25370                 || node.objectAssignmentInitializer !== objectAssignmentInitializer
25371                 ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
25372                 : node;
25373         }
25374         // @api
25375         function createSpreadAssignment(expression) {
25376             var node = createBaseNode(296 /* SpreadAssignment */);
25377             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
25378             node.transformFlags |=
25379                 propagateChildFlags(node.expression) |
25380                     64 /* ContainsES2018 */ |
25381                     32768 /* ContainsObjectRestOrSpread */;
25382             return node;
25383         }
25384         // @api
25385         function updateSpreadAssignment(node, expression) {
25386             return node.expression !== expression
25387                 ? update(createSpreadAssignment(expression), node)
25388                 : node;
25389         }
25390         //
25391         // Enum
25392         //
25393         // @api
25394         function createEnumMember(name, initializer) {
25395             var node = createBaseNode(297 /* EnumMember */);
25396             node.name = asName(name);
25397             node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
25398             node.transformFlags |=
25399                 propagateChildFlags(node.name) |
25400                     propagateChildFlags(node.initializer) |
25401                     1 /* ContainsTypeScript */;
25402             return node;
25403         }
25404         // @api
25405         function updateEnumMember(node, name, initializer) {
25406             return node.name !== name
25407                 || node.initializer !== initializer
25408                 ? update(createEnumMember(name, initializer), node)
25409                 : node;
25410         }
25411         //
25412         // Top-level nodes
25413         //
25414         // @api
25415         function createSourceFile(statements, endOfFileToken, flags) {
25416             var node = baseFactory.createBaseSourceFileNode(303 /* SourceFile */);
25417             node.statements = createNodeArray(statements);
25418             node.endOfFileToken = endOfFileToken;
25419             node.flags |= flags;
25420             node.fileName = "";
25421             node.text = "";
25422             node.languageVersion = 0;
25423             node.languageVariant = 0;
25424             node.scriptKind = 0;
25425             node.isDeclarationFile = false;
25426             node.hasNoDefaultLib = false;
25427             node.transformFlags |=
25428                 propagateChildrenFlags(node.statements) |
25429                     propagateChildFlags(node.endOfFileToken);
25430             return node;
25431         }
25432         function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
25433             var node = baseFactory.createBaseSourceFileNode(303 /* SourceFile */);
25434             for (var p in source) {
25435                 if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
25436                     continue;
25437                 node[p] = source[p];
25438             }
25439             node.flags |= source.flags;
25440             node.statements = createNodeArray(statements);
25441             node.endOfFileToken = source.endOfFileToken;
25442             node.isDeclarationFile = isDeclarationFile;
25443             node.referencedFiles = referencedFiles;
25444             node.typeReferenceDirectives = typeReferences;
25445             node.hasNoDefaultLib = hasNoDefaultLib;
25446             node.libReferenceDirectives = libReferences;
25447             node.transformFlags =
25448                 propagateChildrenFlags(node.statements) |
25449                     propagateChildFlags(node.endOfFileToken);
25450             node.impliedNodeFormat = source.impliedNodeFormat;
25451             return node;
25452         }
25453         // @api
25454         function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
25455             if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
25456             if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
25457             if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
25458             if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
25459             if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
25460             return node.statements !== statements
25461                 || node.isDeclarationFile !== isDeclarationFile
25462                 || node.referencedFiles !== referencedFiles
25463                 || node.typeReferenceDirectives !== typeReferenceDirectives
25464                 || node.hasNoDefaultLib !== hasNoDefaultLib
25465                 || node.libReferenceDirectives !== libReferenceDirectives
25466                 ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
25467                 : node;
25468         }
25469         // @api
25470         function createBundle(sourceFiles, prepends) {
25471             if (prepends === void 0) { prepends = ts.emptyArray; }
25472             var node = createBaseNode(304 /* Bundle */);
25473             node.prepends = prepends;
25474             node.sourceFiles = sourceFiles;
25475             return node;
25476         }
25477         // @api
25478         function updateBundle(node, sourceFiles, prepends) {
25479             if (prepends === void 0) { prepends = ts.emptyArray; }
25480             return node.sourceFiles !== sourceFiles
25481                 || node.prepends !== prepends
25482                 ? update(createBundle(sourceFiles, prepends), node)
25483                 : node;
25484         }
25485         // @api
25486         function createUnparsedSource(prologues, syntheticReferences, texts) {
25487             var node = createBaseNode(305 /* UnparsedSource */);
25488             node.prologues = prologues;
25489             node.syntheticReferences = syntheticReferences;
25490             node.texts = texts;
25491             node.fileName = "";
25492             node.text = "";
25493             node.referencedFiles = ts.emptyArray;
25494             node.libReferenceDirectives = ts.emptyArray;
25495             node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
25496             return node;
25497         }
25498         function createBaseUnparsedNode(kind, data) {
25499             var node = createBaseNode(kind);
25500             node.data = data;
25501             return node;
25502         }
25503         // @api
25504         function createUnparsedPrologue(data) {
25505             return createBaseUnparsedNode(298 /* UnparsedPrologue */, data);
25506         }
25507         // @api
25508         function createUnparsedPrepend(data, texts) {
25509             var node = createBaseUnparsedNode(299 /* UnparsedPrepend */, data);
25510             node.texts = texts;
25511             return node;
25512         }
25513         // @api
25514         function createUnparsedTextLike(data, internal) {
25515             return createBaseUnparsedNode(internal ? 301 /* UnparsedInternalText */ : 300 /* UnparsedText */, data);
25516         }
25517         // @api
25518         function createUnparsedSyntheticReference(section) {
25519             var node = createBaseNode(302 /* UnparsedSyntheticReference */);
25520             node.data = section.data;
25521             node.section = section;
25522             return node;
25523         }
25524         // @api
25525         function createInputFiles() {
25526             var node = createBaseNode(306 /* InputFiles */);
25527             node.javascriptText = "";
25528             node.declarationText = "";
25529             return node;
25530         }
25531         //
25532         // Synthetic Nodes (used by checker)
25533         //
25534         // @api
25535         function createSyntheticExpression(type, isSpread, tupleNameSource) {
25536             if (isSpread === void 0) { isSpread = false; }
25537             var node = createBaseNode(231 /* SyntheticExpression */);
25538             node.type = type;
25539             node.isSpread = isSpread;
25540             node.tupleNameSource = tupleNameSource;
25541             return node;
25542         }
25543         // @api
25544         function createSyntaxList(children) {
25545             var node = createBaseNode(346 /* SyntaxList */);
25546             node._children = children;
25547             return node;
25548         }
25549         //
25550         // Transformation nodes
25551         //
25552         /**
25553          * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
25554          * order to preserve comments.
25555          *
25556          * @param original The original statement.
25557          */
25558         // @api
25559         function createNotEmittedStatement(original) {
25560             var node = createBaseNode(347 /* NotEmittedStatement */);
25561             node.original = original;
25562             ts.setTextRange(node, original);
25563             return node;
25564         }
25565         /**
25566          * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
25567          * order to preserve comments or sourcemap positions.
25568          *
25569          * @param expression The inner expression to emit.
25570          * @param original The original outer expression.
25571          */
25572         // @api
25573         function createPartiallyEmittedExpression(expression, original) {
25574             var node = createBaseNode(348 /* PartiallyEmittedExpression */);
25575             node.expression = expression;
25576             node.original = original;
25577             node.transformFlags |=
25578                 propagateChildFlags(node.expression) |
25579                     1 /* ContainsTypeScript */;
25580             ts.setTextRange(node, original);
25581             return node;
25582         }
25583         // @api
25584         function updatePartiallyEmittedExpression(node, expression) {
25585             return node.expression !== expression
25586                 ? update(createPartiallyEmittedExpression(expression, node.original), node)
25587                 : node;
25588         }
25589         function flattenCommaElements(node) {
25590             if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
25591                 if (ts.isCommaListExpression(node)) {
25592                     return node.elements;
25593                 }
25594                 if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
25595                     return [node.left, node.right];
25596                 }
25597             }
25598             return node;
25599         }
25600         // @api
25601         function createCommaListExpression(elements) {
25602             var node = createBaseNode(349 /* CommaListExpression */);
25603             node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
25604             node.transformFlags |= propagateChildrenFlags(node.elements);
25605             return node;
25606         }
25607         // @api
25608         function updateCommaListExpression(node, elements) {
25609             return node.elements !== elements
25610                 ? update(createCommaListExpression(elements), node)
25611                 : node;
25612         }
25613         /**
25614          * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
25615          * order to properly emit exports.
25616          */
25617         // @api
25618         function createEndOfDeclarationMarker(original) {
25619             var node = createBaseNode(351 /* EndOfDeclarationMarker */);
25620             node.emitNode = {};
25621             node.original = original;
25622             return node;
25623         }
25624         /**
25625          * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
25626          * order to properly emit exports.
25627          */
25628         // @api
25629         function createMergeDeclarationMarker(original) {
25630             var node = createBaseNode(350 /* MergeDeclarationMarker */);
25631             node.emitNode = {};
25632             node.original = original;
25633             return node;
25634         }
25635         // @api
25636         function createSyntheticReferenceExpression(expression, thisArg) {
25637             var node = createBaseNode(352 /* SyntheticReferenceExpression */);
25638             node.expression = expression;
25639             node.thisArg = thisArg;
25640             node.transformFlags |=
25641                 propagateChildFlags(node.expression) |
25642                     propagateChildFlags(node.thisArg);
25643             return node;
25644         }
25645         // @api
25646         function updateSyntheticReferenceExpression(node, expression, thisArg) {
25647             return node.expression !== expression
25648                 || node.thisArg !== thisArg
25649                 ? update(createSyntheticReferenceExpression(expression, thisArg), node)
25650                 : node;
25651         }
25652         function cloneNode(node) {
25653             // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
25654             // the original node. We also need to exclude specific properties and only include own-
25655             // properties (to skip members already defined on the shared prototype).
25656             if (node === undefined) {
25657                 return node;
25658             }
25659             var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(303 /* SourceFile */) :
25660                 ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(79 /* Identifier */) :
25661                     ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(80 /* PrivateIdentifier */) :
25662                         !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
25663                             baseFactory.createBaseNode(node.kind);
25664             clone.flags |= (node.flags & ~8 /* Synthesized */);
25665             clone.transformFlags = node.transformFlags;
25666             setOriginalNode(clone, node);
25667             for (var key in node) {
25668                 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
25669                     continue;
25670                 }
25671                 clone[key] = node[key];
25672             }
25673             return clone;
25674         }
25675         function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
25676             return createCallExpression(createFunctionExpression(
25677             /*modifiers*/ undefined, 
25678             /*asteriskToken*/ undefined, 
25679             /*name*/ undefined, 
25680             /*typeParameters*/ undefined, 
25681             /*parameters*/ param ? [param] : [], 
25682             /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
25683             /*typeArguments*/ undefined, 
25684             /*argumentsArray*/ paramValue ? [paramValue] : []);
25685         }
25686         function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
25687             return createCallExpression(createArrowFunction(
25688             /*modifiers*/ undefined, 
25689             /*typeParameters*/ undefined, 
25690             /*parameters*/ param ? [param] : [], 
25691             /*type*/ undefined, 
25692             /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
25693             /*typeArguments*/ undefined, 
25694             /*argumentsArray*/ paramValue ? [paramValue] : []);
25695         }
25696         function createVoidZero() {
25697             return createVoidExpression(createNumericLiteral("0"));
25698         }
25699         function createExportDefault(expression) {
25700             return createExportAssignment(
25701             /*decorators*/ undefined, 
25702             /*modifiers*/ undefined, 
25703             /*isExportEquals*/ false, expression);
25704         }
25705         function createExternalModuleExport(exportName) {
25706             return createExportDeclaration(
25707             /*decorators*/ undefined, 
25708             /*modifiers*/ undefined, 
25709             /*isTypeOnly*/ false, createNamedExports([
25710                 createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName)
25711             ]));
25712         }
25713         //
25714         // Utilities
25715         //
25716         function createTypeCheck(value, tag) {
25717             return tag === "undefined"
25718                 ? factory.createStrictEquality(value, createVoidZero())
25719                 : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
25720         }
25721         function createMethodCall(object, methodName, argumentsList) {
25722             // Preserve the optionality of `object`.
25723             if (ts.isCallChain(object)) {
25724                 return createCallChain(createPropertyAccessChain(object, /*questionDotToken*/ undefined, methodName), 
25725                 /*questionDotToken*/ undefined, 
25726                 /*typeArguments*/ undefined, argumentsList);
25727             }
25728             return createCallExpression(createPropertyAccessExpression(object, methodName), 
25729             /*typeArguments*/ undefined, argumentsList);
25730         }
25731         function createFunctionBindCall(target, thisArg, argumentsList) {
25732             return createMethodCall(target, "bind", __spreadArray([thisArg], argumentsList, true));
25733         }
25734         function createFunctionCallCall(target, thisArg, argumentsList) {
25735             return createMethodCall(target, "call", __spreadArray([thisArg], argumentsList, true));
25736         }
25737         function createFunctionApplyCall(target, thisArg, argumentsExpression) {
25738             return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
25739         }
25740         function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
25741             return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
25742         }
25743         function createArraySliceCall(array, start) {
25744             return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
25745         }
25746         function createArrayConcatCall(array, argumentsList) {
25747             return createMethodCall(array, "concat", argumentsList);
25748         }
25749         function createObjectDefinePropertyCall(target, propertyName, attributes) {
25750             return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
25751         }
25752         function createReflectGetCall(target, propertyKey, receiver) {
25753             return createGlobalMethodCall("Reflect", "get", receiver ? [target, propertyKey, receiver] : [target, propertyKey]);
25754         }
25755         function createReflectSetCall(target, propertyKey, value, receiver) {
25756             return createGlobalMethodCall("Reflect", "set", receiver ? [target, propertyKey, value, receiver] : [target, propertyKey, value]);
25757         }
25758         function tryAddPropertyAssignment(properties, propertyName, expression) {
25759             if (expression) {
25760                 properties.push(createPropertyAssignment(propertyName, expression));
25761                 return true;
25762             }
25763             return false;
25764         }
25765         function createPropertyDescriptor(attributes, singleLine) {
25766             var properties = [];
25767             tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
25768             tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
25769             var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
25770             isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
25771             var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
25772             isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
25773             ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
25774             return createObjectLiteralExpression(properties, !singleLine);
25775         }
25776         function updateOuterExpression(outerExpression, expression) {
25777             switch (outerExpression.kind) {
25778                 case 211 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
25779                 case 210 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
25780                 case 228 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
25781                 case 229 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
25782                 case 348 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
25783             }
25784         }
25785         /**
25786          * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
25787          *
25788          * A parenthesized expression can be ignored when all of the following are true:
25789          *
25790          * - It's `pos` and `end` are not -1
25791          * - It does not have a custom source map range
25792          * - It does not have a custom comment range
25793          * - It does not have synthetic leading or trailing comments
25794          *
25795          * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
25796          * the expression to maintain precedence, a new parenthesized expression should be created automatically when
25797          * the containing expression is created/updated.
25798          */
25799         function isIgnorableParen(node) {
25800             return ts.isParenthesizedExpression(node)
25801                 && ts.nodeIsSynthesized(node)
25802                 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
25803                 && ts.nodeIsSynthesized(ts.getCommentRange(node))
25804                 && !ts.some(ts.getSyntheticLeadingComments(node))
25805                 && !ts.some(ts.getSyntheticTrailingComments(node));
25806         }
25807         function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
25808             if (kinds === void 0) { kinds = 15 /* All */; }
25809             if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
25810                 return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
25811             }
25812             return innerExpression;
25813         }
25814         function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
25815             if (!outermostLabeledStatement) {
25816                 return node;
25817             }
25818             var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
25819                 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
25820                 : node);
25821             if (afterRestoreLabelCallback) {
25822                 afterRestoreLabelCallback(outermostLabeledStatement);
25823             }
25824             return updated;
25825         }
25826         function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
25827             var target = ts.skipParentheses(node);
25828             switch (target.kind) {
25829                 case 79 /* Identifier */:
25830                     return cacheIdentifiers;
25831                 case 108 /* ThisKeyword */:
25832                 case 8 /* NumericLiteral */:
25833                 case 9 /* BigIntLiteral */:
25834                 case 10 /* StringLiteral */:
25835                     return false;
25836                 case 203 /* ArrayLiteralExpression */:
25837                     var elements = target.elements;
25838                     if (elements.length === 0) {
25839                         return false;
25840                     }
25841                     return true;
25842                 case 204 /* ObjectLiteralExpression */:
25843                     return target.properties.length > 0;
25844                 default:
25845                     return true;
25846             }
25847         }
25848         function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
25849             if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
25850             var callee = ts.skipOuterExpressions(expression, 15 /* All */);
25851             var thisArg;
25852             var target;
25853             if (ts.isSuperProperty(callee)) {
25854                 thisArg = createThis();
25855                 target = callee;
25856             }
25857             else if (ts.isSuperKeyword(callee)) {
25858                 thisArg = createThis();
25859                 target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
25860                     ? ts.setTextRange(createIdentifier("_super"), callee)
25861                     : callee;
25862             }
25863             else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
25864                 thisArg = createVoidZero();
25865                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
25866             }
25867             else if (ts.isPropertyAccessExpression(callee)) {
25868                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
25869                     // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
25870                     thisArg = createTempVariable(recordTempVariable);
25871                     target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
25872                     ts.setTextRange(target, callee);
25873                 }
25874                 else {
25875                     thisArg = callee.expression;
25876                     target = callee;
25877                 }
25878             }
25879             else if (ts.isElementAccessExpression(callee)) {
25880                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
25881                     // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
25882                     thisArg = createTempVariable(recordTempVariable);
25883                     target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
25884                     ts.setTextRange(target, callee);
25885                 }
25886                 else {
25887                     thisArg = callee.expression;
25888                     target = callee;
25889                 }
25890             }
25891             else {
25892                 // for `a()` target is `a` and thisArg is `void 0`
25893                 thisArg = createVoidZero();
25894                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
25895             }
25896             return { target: target, thisArg: thisArg };
25897         }
25898         function createAssignmentTargetWrapper(paramName, expression) {
25899             return createPropertyAccessExpression(
25900             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
25901             createParenthesizedExpression(createObjectLiteralExpression([
25902                 createSetAccessorDeclaration(
25903                 /*decorators*/ undefined, 
25904                 /*modifiers*/ undefined, "value", [createParameterDeclaration(
25905                     /*decorators*/ undefined, 
25906                     /*modifiers*/ undefined, 
25907                     /*dotDotDotToken*/ undefined, paramName, 
25908                     /*questionToken*/ undefined, 
25909                     /*type*/ undefined, 
25910                     /*initializer*/ undefined)], createBlock([
25911                     createExpressionStatement(expression)
25912                 ]))
25913             ])), "value");
25914         }
25915         function inlineExpressions(expressions) {
25916             // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
25917             // stack size exceeded" errors.
25918             return expressions.length > 10
25919                 ? createCommaListExpression(expressions)
25920                 : ts.reduceLeft(expressions, factory.createComma);
25921         }
25922         function getName(node, allowComments, allowSourceMaps, emitFlags) {
25923             if (emitFlags === void 0) { emitFlags = 0; }
25924             var nodeName = ts.getNameOfDeclaration(node);
25925             if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
25926                 // TODO(rbuckton): Does this need to be parented?
25927                 var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
25928                 emitFlags |= ts.getEmitFlags(nodeName);
25929                 if (!allowSourceMaps)
25930                     emitFlags |= 48 /* NoSourceMap */;
25931                 if (!allowComments)
25932                     emitFlags |= 1536 /* NoComments */;
25933                 if (emitFlags)
25934                     ts.setEmitFlags(name, emitFlags);
25935                 return name;
25936             }
25937             return getGeneratedNameForNode(node);
25938         }
25939         /**
25940          * Gets the internal name of a declaration. This is primarily used for declarations that can be
25941          * referred to by name in the body of an ES5 class function body. An internal name will *never*
25942          * be prefixed with an module or namespace export modifier like "exports." when emitted as an
25943          * expression. An internal name will also *never* be renamed due to a collision with a block
25944          * scoped variable.
25945          *
25946          * @param node The declaration.
25947          * @param allowComments A value indicating whether comments may be emitted for the name.
25948          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
25949          */
25950         function getInternalName(node, allowComments, allowSourceMaps) {
25951             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
25952         }
25953         /**
25954          * Gets the local name of a declaration. This is primarily used for declarations that can be
25955          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
25956          * local name will *never* be prefixed with an module or namespace export modifier like
25957          * "exports." when emitted as an expression.
25958          *
25959          * @param node The declaration.
25960          * @param allowComments A value indicating whether comments may be emitted for the name.
25961          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
25962          */
25963         function getLocalName(node, allowComments, allowSourceMaps) {
25964             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
25965         }
25966         /**
25967          * Gets the export name of a declaration. This is primarily used for declarations that can be
25968          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
25969          * export name will *always* be prefixed with an module or namespace export modifier like
25970          * `"exports."` when emitted as an expression if the name points to an exported symbol.
25971          *
25972          * @param node The declaration.
25973          * @param allowComments A value indicating whether comments may be emitted for the name.
25974          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
25975          */
25976         function getExportName(node, allowComments, allowSourceMaps) {
25977             return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
25978         }
25979         /**
25980          * Gets the name of a declaration for use in declarations.
25981          *
25982          * @param node The declaration.
25983          * @param allowComments A value indicating whether comments may be emitted for the name.
25984          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
25985          */
25986         function getDeclarationName(node, allowComments, allowSourceMaps) {
25987             return getName(node, allowComments, allowSourceMaps);
25988         }
25989         /**
25990          * Gets a namespace-qualified name for use in expressions.
25991          *
25992          * @param ns The namespace identifier.
25993          * @param name The name.
25994          * @param allowComments A value indicating whether comments may be emitted for the name.
25995          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
25996          */
25997         function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
25998             var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
25999             ts.setTextRange(qualifiedName, name);
26000             var emitFlags = 0;
26001             if (!allowSourceMaps)
26002                 emitFlags |= 48 /* NoSourceMap */;
26003             if (!allowComments)
26004                 emitFlags |= 1536 /* NoComments */;
26005             if (emitFlags)
26006                 ts.setEmitFlags(qualifiedName, emitFlags);
26007             return qualifiedName;
26008         }
26009         /**
26010          * Gets the exported name of a declaration for use in expressions.
26011          *
26012          * An exported name will *always* be prefixed with an module or namespace export modifier like
26013          * "exports." if the name points to an exported symbol.
26014          *
26015          * @param ns The namespace identifier.
26016          * @param node The declaration.
26017          * @param allowComments A value indicating whether comments may be emitted for the name.
26018          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
26019          */
26020         function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
26021             if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
26022                 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
26023             }
26024             return getExportName(node, allowComments, allowSourceMaps);
26025         }
26026         /**
26027          * Copies any necessary standard and custom prologue-directives into target array.
26028          * @param source origin statements array
26029          * @param target result statements array
26030          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
26031          * @param visitor Optional callback used to visit any custom prologue directives.
26032          */
26033         function copyPrologue(source, target, ensureUseStrict, visitor) {
26034             var offset = copyStandardPrologue(source, target, ensureUseStrict);
26035             return copyCustomPrologue(source, target, offset, visitor);
26036         }
26037         function isUseStrictPrologue(node) {
26038             return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
26039         }
26040         function createUseStrictPrologue() {
26041             return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
26042         }
26043         /**
26044          * Copies only the standard (string-expression) prologue-directives into the target statement-array.
26045          * @param source origin statements array
26046          * @param target result statements array
26047          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
26048          */
26049         function copyStandardPrologue(source, target, ensureUseStrict) {
26050             ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
26051             var foundUseStrict = false;
26052             var statementOffset = 0;
26053             var numStatements = source.length;
26054             while (statementOffset < numStatements) {
26055                 var statement = source[statementOffset];
26056                 if (ts.isPrologueDirective(statement)) {
26057                     if (isUseStrictPrologue(statement)) {
26058                         foundUseStrict = true;
26059                     }
26060                     target.push(statement);
26061                 }
26062                 else {
26063                     break;
26064                 }
26065                 statementOffset++;
26066             }
26067             if (ensureUseStrict && !foundUseStrict) {
26068                 target.push(createUseStrictPrologue());
26069             }
26070             return statementOffset;
26071         }
26072         function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
26073             if (filter === void 0) { filter = ts.returnTrue; }
26074             var numStatements = source.length;
26075             while (statementOffset !== undefined && statementOffset < numStatements) {
26076                 var statement = source[statementOffset];
26077                 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
26078                     ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
26079                 }
26080                 else {
26081                     break;
26082                 }
26083                 statementOffset++;
26084             }
26085             return statementOffset;
26086         }
26087         /**
26088          * Ensures "use strict" directive is added
26089          *
26090          * @param statements An array of statements
26091          */
26092         function ensureUseStrict(statements) {
26093             var foundUseStrict = ts.findUseStrictPrologue(statements);
26094             if (!foundUseStrict) {
26095                 return ts.setTextRange(createNodeArray(__spreadArray([createUseStrictPrologue()], statements, true)), statements);
26096             }
26097             return statements;
26098         }
26099         /**
26100          * Lifts a NodeArray containing only Statement nodes to a block.
26101          *
26102          * @param nodes The NodeArray.
26103          */
26104         function liftToBlock(nodes) {
26105             ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
26106             return ts.singleOrUndefined(nodes) || createBlock(nodes);
26107         }
26108         function findSpanEnd(array, test, start) {
26109             var i = start;
26110             while (i < array.length && test(array[i])) {
26111                 i++;
26112             }
26113             return i;
26114         }
26115         function mergeLexicalEnvironment(statements, declarations) {
26116             if (!ts.some(declarations)) {
26117                 return statements;
26118             }
26119             // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
26120             //
26121             // Given:
26122             //
26123             // | Left                               | Right                               |
26124             // |------------------------------------|-------------------------------------|
26125             // | [standard prologues (left)]        | [standard prologues (right)]        |
26126             // | [hoisted functions (left)]         | [hoisted functions (right)]         |
26127             // | [hoisted variables (left)]         | [hoisted variables (right)]         |
26128             // | [lexical init statements (left)]   | [lexical init statements (right)]   |
26129             // | [other statements (left)]          |                                     |
26130             //
26131             // The resulting statement list will be:
26132             //
26133             // | Result                              |
26134             // |-------------------------------------|
26135             // | [standard prologues (right)]        |
26136             // | [standard prologues (left)]         |
26137             // | [hoisted functions (right)]         |
26138             // | [hoisted functions (left)]          |
26139             // | [hoisted variables (right)]         |
26140             // | [hoisted variables (left)]          |
26141             // | [lexical init statements (right)]   |
26142             // | [lexical init statements (left)]    |
26143             // | [other statements (left)]           |
26144             //
26145             // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
26146             // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
26147             // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
26148             var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
26149             var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
26150             var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
26151             // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
26152             var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
26153             var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
26154             var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
26155             var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
26156             ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
26157             // splice prologues from the right into the left. We do this in reverse order
26158             // so that we don't need to recompute the index on the left when we insert items.
26159             var left = ts.isNodeArray(statements) ? statements.slice() : statements;
26160             // splice other custom prologues from right into left
26161             if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
26162                 left.splice.apply(left, __spreadArray([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd), false));
26163             }
26164             // splice hoisted variables from right into left
26165             if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
26166                 left.splice.apply(left, __spreadArray([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd), false));
26167             }
26168             // splice hoisted functions from right into left
26169             if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
26170                 left.splice.apply(left, __spreadArray([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd), false));
26171             }
26172             // splice standard prologues from right into left (that are not already in left)
26173             if (rightStandardPrologueEnd > 0) {
26174                 if (leftStandardPrologueEnd === 0) {
26175                     left.splice.apply(left, __spreadArray([0, 0], declarations.slice(0, rightStandardPrologueEnd), false));
26176                 }
26177                 else {
26178                     var leftPrologues = new ts.Map();
26179                     for (var i = 0; i < leftStandardPrologueEnd; i++) {
26180                         var leftPrologue = statements[i];
26181                         leftPrologues.set(leftPrologue.expression.text, true);
26182                     }
26183                     for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
26184                         var rightPrologue = declarations[i];
26185                         if (!leftPrologues.has(rightPrologue.expression.text)) {
26186                             left.unshift(rightPrologue);
26187                         }
26188                     }
26189                 }
26190             }
26191             if (ts.isNodeArray(statements)) {
26192                 return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
26193             }
26194             return statements;
26195         }
26196         function updateModifiers(node, modifiers) {
26197             var _a;
26198             if (typeof modifiers === "number") {
26199                 modifiers = createModifiersFromModifierFlags(modifiers);
26200             }
26201             return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
26202                 ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
26203                     ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
26204                         ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
26205                             ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
26206                                 ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
26207                                     ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
26208                                         ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
26209                                             ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
26210                                                 ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
26211                                                     ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
26212                                                         ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
26213                                                             ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
26214                                                                 ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
26215                                                                     ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
26216                                                                         ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
26217                                                                             ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
26218                                                                                 ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
26219                                                                                     ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
26220                                                                                         ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) :
26221                                                                                             ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier, node.assertClause) :
26222                                                                                                 ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
26223                                                                                                     ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) :
26224                                                                                                         ts.Debug.assertNever(node);
26225         }
26226         function asNodeArray(array) {
26227             return array ? createNodeArray(array) : undefined;
26228         }
26229         function asName(name) {
26230             return typeof name === "string" ? createIdentifier(name) :
26231                 name;
26232         }
26233         function asExpression(value) {
26234             return typeof value === "string" ? createStringLiteral(value) :
26235                 typeof value === "number" ? createNumericLiteral(value) :
26236                     typeof value === "boolean" ? value ? createTrue() : createFalse() :
26237                         value;
26238         }
26239         function asToken(value) {
26240             return typeof value === "number" ? createToken(value) : value;
26241         }
26242         function asEmbeddedStatement(statement) {
26243             return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
26244         }
26245     }
26246     ts.createNodeFactory = createNodeFactory;
26247     function updateWithoutOriginal(updated, original) {
26248         if (updated !== original) {
26249             ts.setTextRange(updated, original);
26250         }
26251         return updated;
26252     }
26253     function updateWithOriginal(updated, original) {
26254         if (updated !== original) {
26255             setOriginalNode(updated, original);
26256             ts.setTextRange(updated, original);
26257         }
26258         return updated;
26259     }
26260     function getDefaultTagNameForKind(kind) {
26261         switch (kind) {
26262             case 341 /* JSDocTypeTag */: return "type";
26263             case 339 /* JSDocReturnTag */: return "returns";
26264             case 340 /* JSDocThisTag */: return "this";
26265             case 337 /* JSDocEnumTag */: return "enum";
26266             case 328 /* JSDocAuthorTag */: return "author";
26267             case 330 /* JSDocClassTag */: return "class";
26268             case 331 /* JSDocPublicTag */: return "public";
26269             case 332 /* JSDocPrivateTag */: return "private";
26270             case 333 /* JSDocProtectedTag */: return "protected";
26271             case 334 /* JSDocReadonlyTag */: return "readonly";
26272             case 335 /* JSDocOverrideTag */: return "override";
26273             case 342 /* JSDocTemplateTag */: return "template";
26274             case 343 /* JSDocTypedefTag */: return "typedef";
26275             case 338 /* JSDocParameterTag */: return "param";
26276             case 345 /* JSDocPropertyTag */: return "prop";
26277             case 336 /* JSDocCallbackTag */: return "callback";
26278             case 326 /* JSDocAugmentsTag */: return "augments";
26279             case 327 /* JSDocImplementsTag */: return "implements";
26280             default:
26281                 return ts.Debug.fail("Unsupported kind: ".concat(ts.Debug.formatSyntaxKind(kind)));
26282         }
26283     }
26284     var rawTextScanner;
26285     var invalidValueSentinel = {};
26286     function getCookedText(kind, rawText) {
26287         if (!rawTextScanner) {
26288             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
26289         }
26290         switch (kind) {
26291             case 14 /* NoSubstitutionTemplateLiteral */:
26292                 rawTextScanner.setText("`" + rawText + "`");
26293                 break;
26294             case 15 /* TemplateHead */:
26295                 // tslint:disable-next-line no-invalid-template-strings
26296                 rawTextScanner.setText("`" + rawText + "${");
26297                 break;
26298             case 16 /* TemplateMiddle */:
26299                 // tslint:disable-next-line no-invalid-template-strings
26300                 rawTextScanner.setText("}" + rawText + "${");
26301                 break;
26302             case 17 /* TemplateTail */:
26303                 rawTextScanner.setText("}" + rawText + "`");
26304                 break;
26305         }
26306         var token = rawTextScanner.scan();
26307         if (token === 19 /* CloseBraceToken */) {
26308             token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
26309         }
26310         if (rawTextScanner.isUnterminated()) {
26311             rawTextScanner.setText(undefined);
26312             return invalidValueSentinel;
26313         }
26314         var tokenValue;
26315         switch (token) {
26316             case 14 /* NoSubstitutionTemplateLiteral */:
26317             case 15 /* TemplateHead */:
26318             case 16 /* TemplateMiddle */:
26319             case 17 /* TemplateTail */:
26320                 tokenValue = rawTextScanner.getTokenValue();
26321                 break;
26322         }
26323         if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
26324             rawTextScanner.setText(undefined);
26325             return invalidValueSentinel;
26326         }
26327         rawTextScanner.setText(undefined);
26328         return tokenValue;
26329     }
26330     function propagateIdentifierNameFlags(node) {
26331         // An IdentifierName is allowed to be `await`
26332         return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */;
26333     }
26334     function propagatePropertyNameFlagsOfChild(node, transformFlags) {
26335         return transformFlags | (node.transformFlags & 33562624 /* PropertyNamePropagatingFlags */);
26336     }
26337     function propagateChildFlags(child) {
26338         if (!child)
26339             return 0 /* None */;
26340         var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
26341         return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
26342     }
26343     function propagateChildrenFlags(children) {
26344         return children ? children.transformFlags : 0 /* None */;
26345     }
26346     function aggregateChildrenFlags(children) {
26347         var subtreeFlags = 0 /* None */;
26348         for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
26349             var child = children_2[_i];
26350             subtreeFlags |= propagateChildFlags(child);
26351         }
26352         children.transformFlags = subtreeFlags;
26353     }
26354     /**
26355      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
26356      */
26357     /* @internal */
26358     function getTransformFlagsSubtreeExclusions(kind) {
26359         if (kind >= 176 /* FirstTypeNode */ && kind <= 199 /* LastTypeNode */) {
26360             return -2 /* TypeExcludes */;
26361         }
26362         switch (kind) {
26363             case 207 /* CallExpression */:
26364             case 208 /* NewExpression */:
26365             case 203 /* ArrayLiteralExpression */:
26366                 return 536887296 /* ArrayLiteralOrCallOrNewExcludes */;
26367             case 260 /* ModuleDeclaration */:
26368                 return 589443072 /* ModuleExcludes */;
26369             case 163 /* Parameter */:
26370                 return 536870912 /* ParameterExcludes */;
26371             case 213 /* ArrowFunction */:
26372                 return 557748224 /* ArrowFunctionExcludes */;
26373             case 212 /* FunctionExpression */:
26374             case 255 /* FunctionDeclaration */:
26375                 return 591310848 /* FunctionExcludes */;
26376             case 254 /* VariableDeclarationList */:
26377                 return 537165824 /* VariableDeclarationListExcludes */;
26378             case 256 /* ClassDeclaration */:
26379             case 225 /* ClassExpression */:
26380                 return 536940544 /* ClassExcludes */;
26381             case 170 /* Constructor */:
26382                 return 591306752 /* ConstructorExcludes */;
26383             case 166 /* PropertyDeclaration */:
26384                 return 570433536 /* PropertyExcludes */;
26385             case 168 /* MethodDeclaration */:
26386             case 171 /* GetAccessor */:
26387             case 172 /* SetAccessor */:
26388                 return 574529536 /* MethodOrAccessorExcludes */;
26389             case 130 /* AnyKeyword */:
26390             case 146 /* NumberKeyword */:
26391             case 157 /* BigIntKeyword */:
26392             case 143 /* NeverKeyword */:
26393             case 149 /* StringKeyword */:
26394             case 147 /* ObjectKeyword */:
26395             case 133 /* BooleanKeyword */:
26396             case 150 /* SymbolKeyword */:
26397             case 114 /* VoidKeyword */:
26398             case 162 /* TypeParameter */:
26399             case 165 /* PropertySignature */:
26400             case 167 /* MethodSignature */:
26401             case 173 /* CallSignature */:
26402             case 174 /* ConstructSignature */:
26403             case 175 /* IndexSignature */:
26404             case 257 /* InterfaceDeclaration */:
26405             case 258 /* TypeAliasDeclaration */:
26406                 return -2 /* TypeExcludes */;
26407             case 204 /* ObjectLiteralExpression */:
26408                 return 536973312 /* ObjectLiteralExcludes */;
26409             case 291 /* CatchClause */:
26410                 return 536903680 /* CatchClauseExcludes */;
26411             case 200 /* ObjectBindingPattern */:
26412             case 201 /* ArrayBindingPattern */:
26413                 return 536887296 /* BindingPatternExcludes */;
26414             case 210 /* TypeAssertionExpression */:
26415             case 228 /* AsExpression */:
26416             case 348 /* PartiallyEmittedExpression */:
26417             case 211 /* ParenthesizedExpression */:
26418             case 106 /* SuperKeyword */:
26419                 return 536870912 /* OuterExpressionExcludes */;
26420             case 205 /* PropertyAccessExpression */:
26421             case 206 /* ElementAccessExpression */:
26422                 return 536870912 /* PropertyAccessExcludes */;
26423             default:
26424                 return 536870912 /* NodeExcludes */;
26425         }
26426     }
26427     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
26428     var baseFactory = ts.createBaseNodeFactory();
26429     function makeSynthetic(node) {
26430         node.flags |= 8 /* Synthesized */;
26431         return node;
26432     }
26433     var syntheticFactory = {
26434         createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
26435         createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
26436         createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
26437         createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
26438         createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
26439     };
26440     ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
26441     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
26442         var stripInternal;
26443         var bundleFileInfo;
26444         var fileName;
26445         var text;
26446         var length;
26447         var sourceMapPath;
26448         var sourceMapText;
26449         var getText;
26450         var getSourceMapText;
26451         var oldFileOfCurrentEmit;
26452         if (!ts.isString(textOrInputFiles)) {
26453             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
26454             fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
26455             sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
26456             getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
26457             getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
26458             length = function () { return getText().length; };
26459             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
26460                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
26461                 stripInternal = mapTextOrStripInternal;
26462                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
26463                 oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
26464             }
26465         }
26466         else {
26467             fileName = "";
26468             text = textOrInputFiles;
26469             length = textOrInputFiles.length;
26470             sourceMapPath = mapPathOrType;
26471             sourceMapText = mapTextOrStripInternal;
26472         }
26473         var node = oldFileOfCurrentEmit ?
26474             parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
26475             parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
26476         node.fileName = fileName;
26477         node.sourceMapPath = sourceMapPath;
26478         node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
26479         if (getText && getSourceMapText) {
26480             Object.defineProperty(node, "text", { get: getText });
26481             Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
26482         }
26483         else {
26484             ts.Debug.assert(!oldFileOfCurrentEmit);
26485             node.text = text !== null && text !== void 0 ? text : "";
26486             node.sourceMapText = sourceMapText;
26487         }
26488         return node;
26489     }
26490     ts.createUnparsedSourceFile = createUnparsedSourceFile;
26491     function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
26492         var prologues;
26493         var helpers;
26494         var referencedFiles;
26495         var typeReferenceDirectives;
26496         var libReferenceDirectives;
26497         var prependChildren;
26498         var texts;
26499         var hasNoDefaultLib;
26500         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
26501             var section = _a[_i];
26502             switch (section.kind) {
26503                 case "prologue" /* Prologue */:
26504                     prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
26505                     break;
26506                 case "emitHelpers" /* EmitHelpers */:
26507                     helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
26508                     break;
26509                 case "no-default-lib" /* NoDefaultLib */:
26510                     hasNoDefaultLib = true;
26511                     break;
26512                 case "reference" /* Reference */:
26513                     referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
26514                     break;
26515                 case "type" /* Type */:
26516                     typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
26517                     break;
26518                 case "lib" /* Lib */:
26519                     libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
26520                     break;
26521                 case "prepend" /* Prepend */:
26522                     var prependTexts = void 0;
26523                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
26524                         var text = _c[_b];
26525                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
26526                             prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
26527                         }
26528                     }
26529                     prependChildren = ts.addRange(prependChildren, prependTexts);
26530                     texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
26531                     break;
26532                 case "internal" /* Internal */:
26533                     if (stripInternal) {
26534                         if (!texts)
26535                             texts = [];
26536                         break;
26537                     }
26538                 // falls through
26539                 case "text" /* Text */:
26540                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
26541                     break;
26542                 default:
26543                     ts.Debug.assertNever(section);
26544             }
26545         }
26546         if (!texts) {
26547             var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
26548             ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
26549             texts = [textNode];
26550         }
26551         var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
26552         ts.setEachParent(prologues, node);
26553         ts.setEachParent(texts, node);
26554         ts.setEachParent(prependChildren, node);
26555         node.hasNoDefaultLib = hasNoDefaultLib;
26556         node.helpers = helpers;
26557         node.referencedFiles = referencedFiles || ts.emptyArray;
26558         node.typeReferenceDirectives = typeReferenceDirectives;
26559         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
26560         return node;
26561     }
26562     function parseOldFileOfCurrentEmit(bundleFileInfo) {
26563         var texts;
26564         var syntheticReferences;
26565         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
26566             var section = _a[_i];
26567             switch (section.kind) {
26568                 case "internal" /* Internal */:
26569                 case "text" /* Text */:
26570                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
26571                     break;
26572                 case "no-default-lib" /* NoDefaultLib */:
26573                 case "reference" /* Reference */:
26574                 case "type" /* Type */:
26575                 case "lib" /* Lib */:
26576                     syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
26577                     break;
26578                 // Ignore
26579                 case "prologue" /* Prologue */:
26580                 case "emitHelpers" /* EmitHelpers */:
26581                 case "prepend" /* Prepend */:
26582                     break;
26583                 default:
26584                     ts.Debug.assertNever(section);
26585             }
26586         }
26587         var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
26588         ts.setEachParent(syntheticReferences, node);
26589         ts.setEachParent(texts, node);
26590         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
26591         return node;
26592     }
26593     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
26594         var node = ts.parseNodeFactory.createInputFiles();
26595         if (!ts.isString(javascriptTextOrReadFileText)) {
26596             var cache_1 = new ts.Map();
26597             var textGetter_1 = function (path) {
26598                 if (path === undefined)
26599                     return undefined;
26600                 var value = cache_1.get(path);
26601                 if (value === undefined) {
26602                     value = javascriptTextOrReadFileText(path);
26603                     cache_1.set(path, value !== undefined ? value : false);
26604                 }
26605                 return value !== false ? value : undefined;
26606             };
26607             var definedTextGetter_1 = function (path) {
26608                 var result = textGetter_1(path);
26609                 return result !== undefined ? result : "/* Input file ".concat(path, " was missing */\r\n");
26610             };
26611             var buildInfo_1;
26612             var getAndCacheBuildInfo_1 = function (getText) {
26613                 if (buildInfo_1 === undefined) {
26614                     var result = getText();
26615                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
26616                 }
26617                 return buildInfo_1 || undefined;
26618             };
26619             node.javascriptPath = declarationTextOrJavascriptPath;
26620             node.javascriptMapPath = javascriptMapPath;
26621             node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
26622             node.declarationMapPath = declarationMapPath;
26623             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
26624             Object.defineProperties(node, {
26625                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
26626                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
26627                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
26628                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
26629                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
26630             });
26631         }
26632         else {
26633             node.javascriptText = javascriptTextOrReadFileText;
26634             node.javascriptMapPath = javascriptMapPath;
26635             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
26636             node.declarationText = declarationTextOrJavascriptPath;
26637             node.declarationMapPath = declarationMapPath;
26638             node.declarationMapText = declarationMapTextOrBuildInfoPath;
26639             node.javascriptPath = javascriptPath;
26640             node.declarationPath = declarationPath;
26641             node.buildInfoPath = buildInfoPath;
26642             node.buildInfo = buildInfo;
26643             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
26644         }
26645         return node;
26646     }
26647     ts.createInputFiles = createInputFiles;
26648     // tslint:disable-next-line variable-name
26649     var SourceMapSource;
26650     /**
26651      * Create an external source map source file reference
26652      */
26653     function createSourceMapSource(fileName, text, skipTrivia) {
26654         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
26655     }
26656     ts.createSourceMapSource = createSourceMapSource;
26657     // Utilities
26658     function setOriginalNode(node, original) {
26659         node.original = original;
26660         if (original) {
26661             var emitNode = original.emitNode;
26662             if (emitNode)
26663                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
26664         }
26665         return node;
26666     }
26667     ts.setOriginalNode = setOriginalNode;
26668     function mergeEmitNode(sourceEmitNode, destEmitNode) {
26669         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;
26670         if (!destEmitNode)
26671             destEmitNode = {};
26672         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
26673         if (leadingComments)
26674             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
26675         if (trailingComments)
26676             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
26677         if (flags)
26678             destEmitNode.flags = flags & ~268435456 /* Immutable */;
26679         if (commentRange)
26680             destEmitNode.commentRange = commentRange;
26681         if (sourceMapRange)
26682             destEmitNode.sourceMapRange = sourceMapRange;
26683         if (tokenSourceMapRanges)
26684             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
26685         if (constantValue !== undefined)
26686             destEmitNode.constantValue = constantValue;
26687         if (helpers) {
26688             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
26689                 var helper = helpers_1[_i];
26690                 destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
26691             }
26692         }
26693         if (startsOnNewLine !== undefined)
26694             destEmitNode.startsOnNewLine = startsOnNewLine;
26695         return destEmitNode;
26696     }
26697     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
26698         if (!destRanges)
26699             destRanges = [];
26700         for (var key in sourceRanges) {
26701             destRanges[key] = sourceRanges[key];
26702         }
26703         return destRanges;
26704     }
26705 })(ts || (ts = {}));
26706 var ts;
26707 (function (ts) {
26708     /**
26709      * Associates a node with the current transformation, initializing
26710      * various transient transformation properties.
26711      * @internal
26712      */
26713     function getOrCreateEmitNode(node) {
26714         var _a;
26715         if (!node.emitNode) {
26716             if (ts.isParseTreeNode(node)) {
26717                 // To avoid holding onto transformation artifacts, we keep track of any
26718                 // parse tree node we are annotating. This allows us to clean them up after
26719                 // all transformations have completed.
26720                 if (node.kind === 303 /* SourceFile */) {
26721                     return node.emitNode = { annotatedNodes: [node] };
26722                 }
26723                 var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
26724                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
26725             }
26726             node.emitNode = {};
26727         }
26728         else {
26729             ts.Debug.assert(!(node.emitNode.flags & 268435456 /* Immutable */), "Invalid attempt to mutate an immutable node.");
26730         }
26731         return node.emitNode;
26732     }
26733     ts.getOrCreateEmitNode = getOrCreateEmitNode;
26734     /**
26735      * Clears any `EmitNode` entries from parse-tree nodes.
26736      * @param sourceFile A source file.
26737      */
26738     function disposeEmitNodes(sourceFile) {
26739         var _a, _b;
26740         // During transformation we may need to annotate a parse tree node with transient
26741         // transformation properties. As parse tree nodes live longer than transformation
26742         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
26743         // from these nodes to ensure we do not hold onto entire subtrees just for position
26744         // information. We also need to reset these nodes to a pre-transformation state
26745         // for incremental parsing scenarios so that we do not impact later emit.
26746         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;
26747         if (annotatedNodes) {
26748             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
26749                 var node = annotatedNodes_1[_i];
26750                 node.emitNode = undefined;
26751             }
26752         }
26753     }
26754     ts.disposeEmitNodes = disposeEmitNodes;
26755     /**
26756      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
26757      * @internal
26758      */
26759     function removeAllComments(node) {
26760         var emitNode = getOrCreateEmitNode(node);
26761         emitNode.flags |= 1536 /* NoComments */;
26762         emitNode.leadingComments = undefined;
26763         emitNode.trailingComments = undefined;
26764         return node;
26765     }
26766     ts.removeAllComments = removeAllComments;
26767     /**
26768      * Sets flags that control emit behavior of a node.
26769      */
26770     function setEmitFlags(node, emitFlags) {
26771         getOrCreateEmitNode(node).flags = emitFlags;
26772         return node;
26773     }
26774     ts.setEmitFlags = setEmitFlags;
26775     /**
26776      * Sets flags that control emit behavior of a node.
26777      */
26778     /* @internal */
26779     function addEmitFlags(node, emitFlags) {
26780         var emitNode = getOrCreateEmitNode(node);
26781         emitNode.flags = emitNode.flags | emitFlags;
26782         return node;
26783     }
26784     ts.addEmitFlags = addEmitFlags;
26785     /**
26786      * Gets a custom text range to use when emitting source maps.
26787      */
26788     function getSourceMapRange(node) {
26789         var _a, _b;
26790         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
26791     }
26792     ts.getSourceMapRange = getSourceMapRange;
26793     /**
26794      * Sets a custom text range to use when emitting source maps.
26795      */
26796     function setSourceMapRange(node, range) {
26797         getOrCreateEmitNode(node).sourceMapRange = range;
26798         return node;
26799     }
26800     ts.setSourceMapRange = setSourceMapRange;
26801     /**
26802      * Gets the TextRange to use for source maps for a token of a node.
26803      */
26804     function getTokenSourceMapRange(node, token) {
26805         var _a, _b;
26806         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
26807     }
26808     ts.getTokenSourceMapRange = getTokenSourceMapRange;
26809     /**
26810      * Sets the TextRange to use for source maps for a token of a node.
26811      */
26812     function setTokenSourceMapRange(node, token, range) {
26813         var _a;
26814         var emitNode = getOrCreateEmitNode(node);
26815         var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
26816         tokenSourceMapRanges[token] = range;
26817         return node;
26818     }
26819     ts.setTokenSourceMapRange = setTokenSourceMapRange;
26820     /**
26821      * Gets a custom text range to use when emitting comments.
26822      */
26823     /*@internal*/
26824     function getStartsOnNewLine(node) {
26825         var _a;
26826         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
26827     }
26828     ts.getStartsOnNewLine = getStartsOnNewLine;
26829     /**
26830      * Sets a custom text range to use when emitting comments.
26831      */
26832     /*@internal*/
26833     function setStartsOnNewLine(node, newLine) {
26834         getOrCreateEmitNode(node).startsOnNewLine = newLine;
26835         return node;
26836     }
26837     ts.setStartsOnNewLine = setStartsOnNewLine;
26838     /**
26839      * Gets a custom text range to use when emitting comments.
26840      */
26841     function getCommentRange(node) {
26842         var _a, _b;
26843         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
26844     }
26845     ts.getCommentRange = getCommentRange;
26846     /**
26847      * Sets a custom text range to use when emitting comments.
26848      */
26849     function setCommentRange(node, range) {
26850         getOrCreateEmitNode(node).commentRange = range;
26851         return node;
26852     }
26853     ts.setCommentRange = setCommentRange;
26854     function getSyntheticLeadingComments(node) {
26855         var _a;
26856         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
26857     }
26858     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
26859     function setSyntheticLeadingComments(node, comments) {
26860         getOrCreateEmitNode(node).leadingComments = comments;
26861         return node;
26862     }
26863     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
26864     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
26865         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
26866     }
26867     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
26868     function getSyntheticTrailingComments(node) {
26869         var _a;
26870         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
26871     }
26872     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
26873     function setSyntheticTrailingComments(node, comments) {
26874         getOrCreateEmitNode(node).trailingComments = comments;
26875         return node;
26876     }
26877     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
26878     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
26879         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
26880     }
26881     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
26882     function moveSyntheticComments(node, original) {
26883         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
26884         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
26885         var emit = getOrCreateEmitNode(original);
26886         emit.leadingComments = undefined;
26887         emit.trailingComments = undefined;
26888         return node;
26889     }
26890     ts.moveSyntheticComments = moveSyntheticComments;
26891     /**
26892      * Gets the constant value to emit for an expression representing an enum.
26893      */
26894     function getConstantValue(node) {
26895         var _a;
26896         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
26897     }
26898     ts.getConstantValue = getConstantValue;
26899     /**
26900      * Sets the constant value to emit for an expression.
26901      */
26902     function setConstantValue(node, value) {
26903         var emitNode = getOrCreateEmitNode(node);
26904         emitNode.constantValue = value;
26905         return node;
26906     }
26907     ts.setConstantValue = setConstantValue;
26908     /**
26909      * Adds an EmitHelper to a node.
26910      */
26911     function addEmitHelper(node, helper) {
26912         var emitNode = getOrCreateEmitNode(node);
26913         emitNode.helpers = ts.append(emitNode.helpers, helper);
26914         return node;
26915     }
26916     ts.addEmitHelper = addEmitHelper;
26917     /**
26918      * Add EmitHelpers to a node.
26919      */
26920     function addEmitHelpers(node, helpers) {
26921         if (ts.some(helpers)) {
26922             var emitNode = getOrCreateEmitNode(node);
26923             for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
26924                 var helper = helpers_2[_i];
26925                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
26926             }
26927         }
26928         return node;
26929     }
26930     ts.addEmitHelpers = addEmitHelpers;
26931     /**
26932      * Removes an EmitHelper from a node.
26933      */
26934     function removeEmitHelper(node, helper) {
26935         var _a;
26936         var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
26937         if (helpers) {
26938             return ts.orderedRemoveItem(helpers, helper);
26939         }
26940         return false;
26941     }
26942     ts.removeEmitHelper = removeEmitHelper;
26943     /**
26944      * Gets the EmitHelpers of a node.
26945      */
26946     function getEmitHelpers(node) {
26947         var _a;
26948         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
26949     }
26950     ts.getEmitHelpers = getEmitHelpers;
26951     /**
26952      * Moves matching emit helpers from a source node to a target node.
26953      */
26954     function moveEmitHelpers(source, target, predicate) {
26955         var sourceEmitNode = source.emitNode;
26956         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
26957         if (!ts.some(sourceEmitHelpers))
26958             return;
26959         var targetEmitNode = getOrCreateEmitNode(target);
26960         var helpersRemoved = 0;
26961         for (var i = 0; i < sourceEmitHelpers.length; i++) {
26962             var helper = sourceEmitHelpers[i];
26963             if (predicate(helper)) {
26964                 helpersRemoved++;
26965                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
26966             }
26967             else if (helpersRemoved > 0) {
26968                 sourceEmitHelpers[i - helpersRemoved] = helper;
26969             }
26970         }
26971         if (helpersRemoved > 0) {
26972             sourceEmitHelpers.length -= helpersRemoved;
26973         }
26974     }
26975     ts.moveEmitHelpers = moveEmitHelpers;
26976     /**
26977      * Gets the SnippetElement of a node.
26978      */
26979     /* @internal */
26980     function getSnippetElement(node) {
26981         var _a;
26982         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement;
26983     }
26984     ts.getSnippetElement = getSnippetElement;
26985     /**
26986      * Sets the SnippetElement of a node.
26987      */
26988     /* @internal */
26989     function setSnippetElement(node, snippet) {
26990         var emitNode = getOrCreateEmitNode(node);
26991         emitNode.snippetElement = snippet;
26992         return node;
26993     }
26994     ts.setSnippetElement = setSnippetElement;
26995     /* @internal */
26996     function ignoreSourceNewlines(node) {
26997         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
26998         return node;
26999     }
27000     ts.ignoreSourceNewlines = ignoreSourceNewlines;
27001 })(ts || (ts = {}));
27002 /* @internal */
27003 var ts;
27004 (function (ts) {
27005     function createEmitHelperFactory(context) {
27006         var factory = context.factory;
27007         var immutableTrue = ts.memoize(function () { return ts.setEmitFlags(factory.createTrue(), 268435456 /* Immutable */); });
27008         var immutableFalse = ts.memoize(function () { return ts.setEmitFlags(factory.createFalse(), 268435456 /* Immutable */); });
27009         return {
27010             getUnscopedHelperName: getUnscopedHelperName,
27011             // TypeScript Helpers
27012             createDecorateHelper: createDecorateHelper,
27013             createMetadataHelper: createMetadataHelper,
27014             createParamHelper: createParamHelper,
27015             // ES2018 Helpers
27016             createAssignHelper: createAssignHelper,
27017             createAwaitHelper: createAwaitHelper,
27018             createAsyncGeneratorHelper: createAsyncGeneratorHelper,
27019             createAsyncDelegatorHelper: createAsyncDelegatorHelper,
27020             createAsyncValuesHelper: createAsyncValuesHelper,
27021             // ES2018 Destructuring Helpers
27022             createRestHelper: createRestHelper,
27023             // ES2017 Helpers
27024             createAwaiterHelper: createAwaiterHelper,
27025             // ES2015 Helpers
27026             createExtendsHelper: createExtendsHelper,
27027             createTemplateObjectHelper: createTemplateObjectHelper,
27028             createSpreadArrayHelper: createSpreadArrayHelper,
27029             // ES2015 Destructuring Helpers
27030             createValuesHelper: createValuesHelper,
27031             createReadHelper: createReadHelper,
27032             // ES2015 Generator Helpers
27033             createGeneratorHelper: createGeneratorHelper,
27034             // ES Module Helpers
27035             createCreateBindingHelper: createCreateBindingHelper,
27036             createImportStarHelper: createImportStarHelper,
27037             createImportStarCallbackHelper: createImportStarCallbackHelper,
27038             createImportDefaultHelper: createImportDefaultHelper,
27039             createExportStarHelper: createExportStarHelper,
27040             // Class Fields Helpers
27041             createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
27042             createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
27043             createClassPrivateFieldInHelper: createClassPrivateFieldInHelper
27044         };
27045         /**
27046          * Gets an identifier for the name of an *unscoped* emit helper.
27047          */
27048         function getUnscopedHelperName(name) {
27049             return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
27050         }
27051         // TypeScript Helpers
27052         function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
27053             context.requestEmitHelper(ts.decorateHelper);
27054             var argumentsArray = [];
27055             argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
27056             argumentsArray.push(target);
27057             if (memberName) {
27058                 argumentsArray.push(memberName);
27059                 if (descriptor) {
27060                     argumentsArray.push(descriptor);
27061                 }
27062             }
27063             return factory.createCallExpression(getUnscopedHelperName("__decorate"), 
27064             /*typeArguments*/ undefined, argumentsArray);
27065         }
27066         function createMetadataHelper(metadataKey, metadataValue) {
27067             context.requestEmitHelper(ts.metadataHelper);
27068             return factory.createCallExpression(getUnscopedHelperName("__metadata"), 
27069             /*typeArguments*/ undefined, [
27070                 factory.createStringLiteral(metadataKey),
27071                 metadataValue
27072             ]);
27073         }
27074         function createParamHelper(expression, parameterOffset, location) {
27075             context.requestEmitHelper(ts.paramHelper);
27076             return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"), 
27077             /*typeArguments*/ undefined, [
27078                 factory.createNumericLiteral(parameterOffset + ""),
27079                 expression
27080             ]), location);
27081         }
27082         // ES2018 Helpers
27083         function createAssignHelper(attributesSegments) {
27084             if (ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
27085                 return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), 
27086                 /*typeArguments*/ undefined, attributesSegments);
27087             }
27088             context.requestEmitHelper(ts.assignHelper);
27089             return factory.createCallExpression(getUnscopedHelperName("__assign"), 
27090             /*typeArguments*/ undefined, attributesSegments);
27091         }
27092         function createAwaitHelper(expression) {
27093             context.requestEmitHelper(ts.awaitHelper);
27094             return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
27095         }
27096         function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
27097             context.requestEmitHelper(ts.awaitHelper);
27098             context.requestEmitHelper(ts.asyncGeneratorHelper);
27099             // Mark this node as originally an async function
27100             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
27101             return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"), 
27102             /*typeArguments*/ undefined, [
27103                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
27104                 factory.createIdentifier("arguments"),
27105                 generatorFunc
27106             ]);
27107         }
27108         function createAsyncDelegatorHelper(expression) {
27109             context.requestEmitHelper(ts.awaitHelper);
27110             context.requestEmitHelper(ts.asyncDelegator);
27111             return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"), 
27112             /*typeArguments*/ undefined, [expression]);
27113         }
27114         function createAsyncValuesHelper(expression) {
27115             context.requestEmitHelper(ts.asyncValues);
27116             return factory.createCallExpression(getUnscopedHelperName("__asyncValues"), 
27117             /*typeArguments*/ undefined, [expression]);
27118         }
27119         // ES2018 Destructuring Helpers
27120         /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
27121          * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
27122          */
27123         function createRestHelper(value, elements, computedTempVariables, location) {
27124             context.requestEmitHelper(ts.restHelper);
27125             var propertyNames = [];
27126             var computedTempVariableOffset = 0;
27127             for (var i = 0; i < elements.length - 1; i++) {
27128                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
27129                 if (propertyName) {
27130                     if (ts.isComputedPropertyName(propertyName)) {
27131                         ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
27132                         var temp = computedTempVariables[computedTempVariableOffset];
27133                         computedTempVariableOffset++;
27134                         // typeof _tmp === "symbol" ? _tmp : _tmp + ""
27135                         propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"), 
27136                         /*questionToken*/ undefined, temp, 
27137                         /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
27138                     }
27139                     else {
27140                         propertyNames.push(factory.createStringLiteralFromNode(propertyName));
27141                     }
27142                 }
27143             }
27144             return factory.createCallExpression(getUnscopedHelperName("__rest"), 
27145             /*typeArguments*/ undefined, [
27146                 value,
27147                 ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
27148             ]);
27149         }
27150         // ES2017 Helpers
27151         function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
27152             context.requestEmitHelper(ts.awaiterHelper);
27153             var generatorFunc = factory.createFunctionExpression(
27154             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), 
27155             /*name*/ undefined, 
27156             /*typeParameters*/ undefined, 
27157             /*parameters*/ [], 
27158             /*type*/ undefined, body);
27159             // Mark this node as originally an async function
27160             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
27161             return factory.createCallExpression(getUnscopedHelperName("__awaiter"), 
27162             /*typeArguments*/ undefined, [
27163                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
27164                 hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
27165                 promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
27166                 generatorFunc
27167             ]);
27168         }
27169         // ES2015 Helpers
27170         function createExtendsHelper(name) {
27171             context.requestEmitHelper(ts.extendsHelper);
27172             return factory.createCallExpression(getUnscopedHelperName("__extends"), 
27173             /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
27174         }
27175         function createTemplateObjectHelper(cooked, raw) {
27176             context.requestEmitHelper(ts.templateObjectHelper);
27177             return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"), 
27178             /*typeArguments*/ undefined, [cooked, raw]);
27179         }
27180         function createSpreadArrayHelper(to, from, packFrom) {
27181             context.requestEmitHelper(ts.spreadArrayHelper);
27182             return factory.createCallExpression(getUnscopedHelperName("__spreadArray"), 
27183             /*typeArguments*/ undefined, [to, from, packFrom ? immutableTrue() : immutableFalse()]);
27184         }
27185         // ES2015 Destructuring Helpers
27186         function createValuesHelper(expression) {
27187             context.requestEmitHelper(ts.valuesHelper);
27188             return factory.createCallExpression(getUnscopedHelperName("__values"), 
27189             /*typeArguments*/ undefined, [expression]);
27190         }
27191         function createReadHelper(iteratorRecord, count) {
27192             context.requestEmitHelper(ts.readHelper);
27193             return factory.createCallExpression(getUnscopedHelperName("__read"), 
27194             /*typeArguments*/ undefined, count !== undefined
27195                 ? [iteratorRecord, factory.createNumericLiteral(count + "")]
27196                 : [iteratorRecord]);
27197         }
27198         // ES2015 Generator Helpers
27199         function createGeneratorHelper(body) {
27200             context.requestEmitHelper(ts.generatorHelper);
27201             return factory.createCallExpression(getUnscopedHelperName("__generator"), 
27202             /*typeArguments*/ undefined, [factory.createThis(), body]);
27203         }
27204         // ES Module Helpers
27205         function createCreateBindingHelper(module, inputName, outputName) {
27206             context.requestEmitHelper(ts.createBindingHelper);
27207             return factory.createCallExpression(getUnscopedHelperName("__createBinding"), 
27208             /*typeArguments*/ undefined, __spreadArray([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : []), true));
27209         }
27210         function createImportStarHelper(expression) {
27211             context.requestEmitHelper(ts.importStarHelper);
27212             return factory.createCallExpression(getUnscopedHelperName("__importStar"), 
27213             /*typeArguments*/ undefined, [expression]);
27214         }
27215         function createImportStarCallbackHelper() {
27216             context.requestEmitHelper(ts.importStarHelper);
27217             return getUnscopedHelperName("__importStar");
27218         }
27219         function createImportDefaultHelper(expression) {
27220             context.requestEmitHelper(ts.importDefaultHelper);
27221             return factory.createCallExpression(getUnscopedHelperName("__importDefault"), 
27222             /*typeArguments*/ undefined, [expression]);
27223         }
27224         function createExportStarHelper(moduleExpression, exportsExpression) {
27225             if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
27226             context.requestEmitHelper(ts.exportStarHelper);
27227             context.requestEmitHelper(ts.createBindingHelper);
27228             return factory.createCallExpression(getUnscopedHelperName("__exportStar"), 
27229             /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
27230         }
27231         // Class Fields Helpers
27232         function createClassPrivateFieldGetHelper(receiver, state, kind, f) {
27233             context.requestEmitHelper(ts.classPrivateFieldGetHelper);
27234             var args;
27235             if (!f) {
27236                 args = [receiver, state, factory.createStringLiteral(kind)];
27237             }
27238             else {
27239                 args = [receiver, state, factory.createStringLiteral(kind), f];
27240             }
27241             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args);
27242         }
27243         function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) {
27244             context.requestEmitHelper(ts.classPrivateFieldSetHelper);
27245             var args;
27246             if (!f) {
27247                 args = [receiver, state, value, factory.createStringLiteral(kind)];
27248             }
27249             else {
27250                 args = [receiver, state, value, factory.createStringLiteral(kind), f];
27251             }
27252             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args);
27253         }
27254         function createClassPrivateFieldInHelper(state, receiver) {
27255             context.requestEmitHelper(ts.classPrivateFieldInHelper);
27256             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ undefined, [state, receiver]);
27257         }
27258     }
27259     ts.createEmitHelperFactory = createEmitHelperFactory;
27260     /* @internal */
27261     function compareEmitHelpers(x, y) {
27262         if (x === y)
27263             return 0 /* EqualTo */;
27264         if (x.priority === y.priority)
27265             return 0 /* EqualTo */;
27266         if (x.priority === undefined)
27267             return 1 /* GreaterThan */;
27268         if (y.priority === undefined)
27269             return -1 /* LessThan */;
27270         return ts.compareValues(x.priority, y.priority);
27271     }
27272     ts.compareEmitHelpers = compareEmitHelpers;
27273     /**
27274      * @param input Template string input strings
27275      * @param args Names which need to be made file-level unique
27276      */
27277     function helperString(input) {
27278         var args = [];
27279         for (var _i = 1; _i < arguments.length; _i++) {
27280             args[_i - 1] = arguments[_i];
27281         }
27282         return function (uniqueName) {
27283             var result = "";
27284             for (var i = 0; i < args.length; i++) {
27285                 result += input[i];
27286                 result += uniqueName(args[i]);
27287             }
27288             result += input[input.length - 1];
27289             return result;
27290         };
27291     }
27292     ts.helperString = helperString;
27293     // TypeScript Helpers
27294     ts.decorateHelper = {
27295         name: "typescript:decorate",
27296         importName: "__decorate",
27297         scoped: false,
27298         priority: 2,
27299         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            };"
27300     };
27301     ts.metadataHelper = {
27302         name: "typescript:metadata",
27303         importName: "__metadata",
27304         scoped: false,
27305         priority: 3,
27306         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            };"
27307     };
27308     ts.paramHelper = {
27309         name: "typescript:param",
27310         importName: "__param",
27311         scoped: false,
27312         priority: 4,
27313         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
27314     };
27315     // ES2018 Helpers
27316     ts.assignHelper = {
27317         name: "typescript:assign",
27318         importName: "__assign",
27319         scoped: false,
27320         priority: 1,
27321         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            };"
27322     };
27323     ts.awaitHelper = {
27324         name: "typescript:await",
27325         importName: "__await",
27326         scoped: false,
27327         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
27328     };
27329     ts.asyncGeneratorHelper = {
27330         name: "typescript:asyncGenerator",
27331         importName: "__asyncGenerator",
27332         scoped: false,
27333         dependencies: [ts.awaitHelper],
27334         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            };"
27335     };
27336     ts.asyncDelegator = {
27337         name: "typescript:asyncDelegator",
27338         importName: "__asyncDelegator",
27339         scoped: false,
27340         dependencies: [ts.awaitHelper],
27341         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            };"
27342     };
27343     ts.asyncValues = {
27344         name: "typescript:asyncValues",
27345         importName: "__asyncValues",
27346         scoped: false,
27347         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            };"
27348     };
27349     // ES2018 Destructuring Helpers
27350     ts.restHelper = {
27351         name: "typescript:rest",
27352         importName: "__rest",
27353         scoped: false,
27354         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            };"
27355     };
27356     // ES2017 Helpers
27357     ts.awaiterHelper = {
27358         name: "typescript:awaiter",
27359         importName: "__awaiter",
27360         scoped: false,
27361         priority: 5,
27362         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            };"
27363     };
27364     // ES2015 Helpers
27365     ts.extendsHelper = {
27366         name: "typescript:extends",
27367         importName: "__extends",
27368         scoped: false,
27369         priority: 0,
27370         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                    if (typeof b !== \"function\" && b !== null)\n                        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n                    extendStatics(d, b);\n                    function __() { this.constructor = d; }\n                    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n                };\n            })();"
27371     };
27372     ts.templateObjectHelper = {
27373         name: "typescript:makeTemplateObject",
27374         importName: "__makeTemplateObject",
27375         scoped: false,
27376         priority: 0,
27377         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            };"
27378     };
27379     ts.readHelper = {
27380         name: "typescript:read",
27381         importName: "__read",
27382         scoped: false,
27383         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            };"
27384     };
27385     ts.spreadArrayHelper = {
27386         name: "typescript:spreadArray",
27387         importName: "__spreadArray",
27388         scoped: false,
27389         text: "\n            var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n                if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n                    if (ar || !(i in from)) {\n                        if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n                        ar[i] = from[i];\n                    }\n                }\n                return to.concat(ar || Array.prototype.slice.call(from));\n            };"
27390     };
27391     // ES2015 Destructuring Helpers
27392     ts.valuesHelper = {
27393         name: "typescript:values",
27394         importName: "__values",
27395         scoped: false,
27396         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            };"
27397     };
27398     // ES2015 Generator Helpers
27399     // The __generator helper is used by down-level transformations to emulate the runtime
27400     // semantics of an ES2015 generator function. When called, this helper returns an
27401     // object that implements the Iterator protocol, in that it has `next`, `return`, and
27402     // `throw` methods that step through the generator when invoked.
27403     //
27404     // parameters:
27405     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
27406     //  @param body     A function that acts as the transformed generator body.
27407     //
27408     // variables:
27409     //  _       Persistent state for the generator that is shared between the helper and the
27410     //          generator body. The state object has the following members:
27411     //            sent() - A method that returns or throws the current completion value.
27412     //            label  - The next point at which to resume evaluation of the generator body.
27413     //            trys   - A stack of protected regions (try/catch/finally blocks).
27414     //            ops    - A stack of pending instructions when inside of a finally block.
27415     //  f       A value indicating whether the generator is executing.
27416     //  y       An iterator to delegate for a yield*.
27417     //  t       A temporary variable that holds one of the following values (note that these
27418     //          cases do not overlap):
27419     //          - The completion value when resuming from a `yield` or `yield*`.
27420     //          - The error value for a catch block.
27421     //          - The current protected region (array of try/catch/finally/end labels).
27422     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
27423     //            of a `yield*`.
27424     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
27425     //
27426     // functions:
27427     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
27428     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
27429     //              completed.
27430     //
27431     // The __generator helper understands a limited set of instructions:
27432     //  0: next(value?)     - Start or resume the generator with the specified value.
27433     //  1: throw(error)     - Resume the generator with an exception. If the generator is
27434     //                        suspended inside of one or more protected regions, evaluates
27435     //                        any intervening finally blocks between the current label and
27436     //                        the nearest catch block or function boundary. If uncaught, the
27437     //                        exception is thrown to the caller.
27438     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
27439     //                        suspended inside of one or more protected regions, evaluates any
27440     //                        intervening finally blocks.
27441     //  3: break(label)     - Jump to the specified label. If the label is outside of the
27442     //                        current protected region, evaluates any intervening finally
27443     //                        blocks.
27444     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
27445     //                        resumed, the generator will continue at the next label.
27446     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
27447     //                        delegation completes, the generator will continue at the next
27448     //                        label.
27449     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
27450     //                        the current label is inside of one or more protected regions,
27451     //                        evaluates any intervening finally blocks between the current
27452     //                        label and the nearest catch block or function boundary. If
27453     //                        uncaught, the exception is thrown to the caller.
27454     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
27455     //                        entering a finally block.
27456     //
27457     // For examples of how these are used, see the comments in ./transformers/generators.ts
27458     ts.generatorHelper = {
27459         name: "typescript:generator",
27460         importName: "__generator",
27461         scoped: false,
27462         priority: 6,
27463         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            };"
27464     };
27465     // ES Module Helpers
27466     ts.createBindingHelper = {
27467         name: "typescript:commonjscreatebinding",
27468         importName: "__createBinding",
27469         scoped: false,
27470         priority: 1,
27471         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            }));"
27472     };
27473     ts.setModuleDefaultHelper = {
27474         name: "typescript:commonjscreatevalue",
27475         importName: "__setModuleDefault",
27476         scoped: false,
27477         priority: 1,
27478         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            });"
27479     };
27480     // emit helper for `import * as Name from "foo"`
27481     ts.importStarHelper = {
27482         name: "typescript:commonjsimportstar",
27483         importName: "__importStar",
27484         scoped: false,
27485         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
27486         priority: 2,
27487         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            };"
27488     };
27489     // emit helper for `import Name from "foo"`
27490     ts.importDefaultHelper = {
27491         name: "typescript:commonjsimportdefault",
27492         importName: "__importDefault",
27493         scoped: false,
27494         text: "\n            var __importDefault = (this && this.__importDefault) || function (mod) {\n                return (mod && mod.__esModule) ? mod : { \"default\": mod };\n            };"
27495     };
27496     ts.exportStarHelper = {
27497         name: "typescript:export-star",
27498         importName: "__exportStar",
27499         scoped: false,
27500         dependencies: [ts.createBindingHelper],
27501         priority: 2,
27502         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            };"
27503     };
27504     /**
27505      * Parameters:
27506      *  @param receiver â€” The object from which the private member will be read.
27507      *  @param state â€” One of the following:
27508      *      - A WeakMap used to read a private instance field.
27509      *      - A WeakSet used as an instance brand for private instance methods and accessors.
27510      *      - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors.
27511      *  @param kind â€” (optional pre TS 4.3, required for TS 4.3+) One of the following values:
27512      *      - undefined â€” Indicates a private instance field (pre TS 4.3).
27513      *      - "f" â€” Indicates a private field (instance or static).
27514      *      - "m" â€” Indicates a private method (instance or static).
27515      *      - "a" â€” Indicates a private accessor (instance or static).
27516      *  @param f â€” (optional pre TS 4.3) Depends on the arguments for state and kind:
27517      *      - If kind is "m", this should be the function corresponding to the static or instance method.
27518      *      - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined.
27519      *      - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated.
27520      * Usage:
27521      * This helper will only ever be used by the compiler in the following ways:
27522      *
27523      * Reading from a private instance field (pre TS 4.3):
27524      *      __classPrivateFieldGet(<any>, <WeakMap>)
27525      *
27526      * Reading from a private instance field (TS 4.3+):
27527      *      __classPrivateFieldGet(<any>, <WeakMap>, "f")
27528      *
27529      * Reading from a private instance get accessor (when defined, TS 4.3+):
27530      *      __classPrivateFieldGet(<any>, <WeakSet>, "a", <function>)
27531      *
27532      * Reading from a private instance get accessor (when not defined, TS 4.3+):
27533      *      __classPrivateFieldGet(<any>, <WeakSet>, "a", void 0)
27534      *      NOTE: This always results in a runtime error.
27535      *
27536      * Reading from a private instance method (TS 4.3+):
27537      *      __classPrivateFieldGet(<any>, <WeakSet>, "m", <function>)
27538      *
27539      * Reading from a private static field (TS 4.3+):
27540      *      __classPrivateFieldGet(<any>, <constructor>, "f", <{ value: any }>)
27541      *
27542      * Reading from a private static get accessor (when defined, TS 4.3+):
27543      *      __classPrivateFieldGet(<any>, <constructor>, "a", <function>)
27544      *
27545      * Reading from a private static get accessor (when not defined, TS 4.3+):
27546      *      __classPrivateFieldGet(<any>, <constructor>, "a", void 0)
27547      *      NOTE: This always results in a runtime error.
27548      *
27549      * Reading from a private static method (TS 4.3+):
27550      *      __classPrivateFieldGet(<any>, <constructor>, "m", <function>)
27551      */
27552     ts.classPrivateFieldGetHelper = {
27553         name: "typescript:classPrivateFieldGet",
27554         importName: "__classPrivateFieldGet",
27555         scoped: false,
27556         text: "\n            var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n                if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n                if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n                return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n            };"
27557     };
27558     /**
27559      * Parameters:
27560      *  @param receiver â€” The object on which the private member will be set.
27561      *  @param state â€” One of the following:
27562      *      - A WeakMap used to store a private instance field.
27563      *      - A WeakSet used as an instance brand for private instance methods and accessors.
27564      *      - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors.
27565      *  @param value â€” The value to set.
27566      *  @param kind â€” (optional pre TS 4.3, required for TS 4.3+) One of the following values:
27567      *       - undefined â€” Indicates a private instance field (pre TS 4.3).
27568      *       - "f" â€” Indicates a private field (instance or static).
27569      *       - "m" â€” Indicates a private method (instance or static).
27570      *       - "a" â€” Indicates a private accessor (instance or static).
27571      *   @param f â€” (optional pre TS 4.3) Depends on the arguments for state and kind:
27572      *       - If kind is "m", this should be the function corresponding to the static or instance method.
27573      *       - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined.
27574      *       - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated.
27575      * Usage:
27576      * This helper will only ever be used by the compiler in the following ways:
27577      *
27578      * Writing to a private instance field (pre TS 4.3):
27579      *      __classPrivateFieldSet(<any>, <WeakMap>, <any>)
27580      *
27581      * Writing to a private instance field (TS 4.3+):
27582      *      __classPrivateFieldSet(<any>, <WeakMap>, <any>, "f")
27583      *
27584      * Writing to a private instance set accessor (when defined, TS 4.3+):
27585      *      __classPrivateFieldSet(<any>, <WeakSet>, <any>, "a", <function>)
27586      *
27587      * Writing to a private instance set accessor (when not defined, TS 4.3+):
27588      *      __classPrivateFieldSet(<any>, <WeakSet>, <any>, "a", void 0)
27589      *      NOTE: This always results in a runtime error.
27590      *
27591      * Writing to a private instance method (TS 4.3+):
27592      *      __classPrivateFieldSet(<any>, <WeakSet>, <any>, "m", <function>)
27593      *      NOTE: This always results in a runtime error.
27594      *
27595      * Writing to a private static field (TS 4.3+):
27596      *      __classPrivateFieldSet(<any>, <constructor>, <any>, "f", <{ value: any }>)
27597      *
27598      * Writing to a private static set accessor (when defined, TS 4.3+):
27599      *      __classPrivateFieldSet(<any>, <constructor>, <any>, "a", <function>)
27600      *
27601      * Writing to a private static set accessor (when not defined, TS 4.3+):
27602      *      __classPrivateFieldSet(<any>, <constructor>, <any>, "a", void 0)
27603      *      NOTE: This always results in a runtime error.
27604      *
27605      * Writing to a private static method (TS 4.3+):
27606      *      __classPrivateFieldSet(<any>, <constructor>, <any>, "m", <function>)
27607      *      NOTE: This always results in a runtime error.
27608      */
27609     ts.classPrivateFieldSetHelper = {
27610         name: "typescript:classPrivateFieldSet",
27611         importName: "__classPrivateFieldSet",
27612         scoped: false,
27613         text: "\n            var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n                if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n                if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n                if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n                return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n            };"
27614     };
27615     /**
27616      * Parameters:
27617      *  @param state â€” One of the following:
27618      *      - A WeakMap when the member is a private instance field.
27619      *      - A WeakSet when the member is a private instance method or accessor.
27620      *      - A function value that should be the undecorated class constructor when the member is a private static field, method, or accessor.
27621      *  @param receiver â€” The object being checked if it has the private member.
27622      *
27623      * Usage:
27624      * This helper is used to transform `#field in expression` to
27625      *      `__classPrivateFieldIn(<weakMap/weakSet/constructor>, expression)`
27626      */
27627     ts.classPrivateFieldInHelper = {
27628         name: "typescript:classPrivateFieldIn",
27629         importName: "__classPrivateFieldIn",
27630         scoped: false,
27631         text: "\n            var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) {\n                if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n                return typeof state === \"function\" ? receiver === state : state.has(receiver);\n            };"
27632     };
27633     var allUnscopedEmitHelpers;
27634     function getAllUnscopedEmitHelpers() {
27635         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
27636             ts.decorateHelper,
27637             ts.metadataHelper,
27638             ts.paramHelper,
27639             ts.assignHelper,
27640             ts.awaitHelper,
27641             ts.asyncGeneratorHelper,
27642             ts.asyncDelegator,
27643             ts.asyncValues,
27644             ts.restHelper,
27645             ts.awaiterHelper,
27646             ts.extendsHelper,
27647             ts.templateObjectHelper,
27648             ts.spreadArrayHelper,
27649             ts.valuesHelper,
27650             ts.readHelper,
27651             ts.generatorHelper,
27652             ts.importStarHelper,
27653             ts.importDefaultHelper,
27654             ts.exportStarHelper,
27655             ts.classPrivateFieldGetHelper,
27656             ts.classPrivateFieldSetHelper,
27657             ts.classPrivateFieldInHelper,
27658             ts.createBindingHelper,
27659             ts.setModuleDefaultHelper
27660         ], function (helper) { return helper.name; }));
27661     }
27662     ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
27663     ts.asyncSuperHelper = {
27664         name: "typescript:async-super",
27665         scoped: true,
27666         text: helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
27667     };
27668     ts.advancedAsyncSuperHelper = {
27669         name: "typescript:advanced-async-super",
27670         scoped: true,
27671         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")
27672     };
27673     function isCallToHelper(firstSegment, helperName) {
27674         return ts.isCallExpression(firstSegment)
27675             && ts.isIdentifier(firstSegment.expression)
27676             && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) !== 0
27677             && firstSegment.expression.escapedText === helperName;
27678     }
27679     ts.isCallToHelper = isCallToHelper;
27680 })(ts || (ts = {}));
27681 var ts;
27682 (function (ts) {
27683     // Literals
27684     function isNumericLiteral(node) {
27685         return node.kind === 8 /* NumericLiteral */;
27686     }
27687     ts.isNumericLiteral = isNumericLiteral;
27688     function isBigIntLiteral(node) {
27689         return node.kind === 9 /* BigIntLiteral */;
27690     }
27691     ts.isBigIntLiteral = isBigIntLiteral;
27692     function isStringLiteral(node) {
27693         return node.kind === 10 /* StringLiteral */;
27694     }
27695     ts.isStringLiteral = isStringLiteral;
27696     function isJsxText(node) {
27697         return node.kind === 11 /* JsxText */;
27698     }
27699     ts.isJsxText = isJsxText;
27700     function isRegularExpressionLiteral(node) {
27701         return node.kind === 13 /* RegularExpressionLiteral */;
27702     }
27703     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
27704     function isNoSubstitutionTemplateLiteral(node) {
27705         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
27706     }
27707     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
27708     // Pseudo-literals
27709     function isTemplateHead(node) {
27710         return node.kind === 15 /* TemplateHead */;
27711     }
27712     ts.isTemplateHead = isTemplateHead;
27713     function isTemplateMiddle(node) {
27714         return node.kind === 16 /* TemplateMiddle */;
27715     }
27716     ts.isTemplateMiddle = isTemplateMiddle;
27717     function isTemplateTail(node) {
27718         return node.kind === 17 /* TemplateTail */;
27719     }
27720     ts.isTemplateTail = isTemplateTail;
27721     // Punctuation
27722     function isDotDotDotToken(node) {
27723         return node.kind === 25 /* DotDotDotToken */;
27724     }
27725     ts.isDotDotDotToken = isDotDotDotToken;
27726     /*@internal*/
27727     function isCommaToken(node) {
27728         return node.kind === 27 /* CommaToken */;
27729     }
27730     ts.isCommaToken = isCommaToken;
27731     function isPlusToken(node) {
27732         return node.kind === 39 /* PlusToken */;
27733     }
27734     ts.isPlusToken = isPlusToken;
27735     function isMinusToken(node) {
27736         return node.kind === 40 /* MinusToken */;
27737     }
27738     ts.isMinusToken = isMinusToken;
27739     function isAsteriskToken(node) {
27740         return node.kind === 41 /* AsteriskToken */;
27741     }
27742     ts.isAsteriskToken = isAsteriskToken;
27743     /*@internal*/
27744     function isExclamationToken(node) {
27745         return node.kind === 53 /* ExclamationToken */;
27746     }
27747     ts.isExclamationToken = isExclamationToken;
27748     /*@internal*/
27749     function isQuestionToken(node) {
27750         return node.kind === 57 /* QuestionToken */;
27751     }
27752     ts.isQuestionToken = isQuestionToken;
27753     /*@internal*/
27754     function isColonToken(node) {
27755         return node.kind === 58 /* ColonToken */;
27756     }
27757     ts.isColonToken = isColonToken;
27758     /*@internal*/
27759     function isQuestionDotToken(node) {
27760         return node.kind === 28 /* QuestionDotToken */;
27761     }
27762     ts.isQuestionDotToken = isQuestionDotToken;
27763     /*@internal*/
27764     function isEqualsGreaterThanToken(node) {
27765         return node.kind === 38 /* EqualsGreaterThanToken */;
27766     }
27767     ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken;
27768     // Identifiers
27769     function isIdentifier(node) {
27770         return node.kind === 79 /* Identifier */;
27771     }
27772     ts.isIdentifier = isIdentifier;
27773     function isPrivateIdentifier(node) {
27774         return node.kind === 80 /* PrivateIdentifier */;
27775     }
27776     ts.isPrivateIdentifier = isPrivateIdentifier;
27777     // Reserved Words
27778     /* @internal */
27779     function isExportModifier(node) {
27780         return node.kind === 93 /* ExportKeyword */;
27781     }
27782     ts.isExportModifier = isExportModifier;
27783     /* @internal */
27784     function isAsyncModifier(node) {
27785         return node.kind === 131 /* AsyncKeyword */;
27786     }
27787     ts.isAsyncModifier = isAsyncModifier;
27788     /* @internal */
27789     function isAssertsKeyword(node) {
27790         return node.kind === 128 /* AssertsKeyword */;
27791     }
27792     ts.isAssertsKeyword = isAssertsKeyword;
27793     /* @internal */
27794     function isAwaitKeyword(node) {
27795         return node.kind === 132 /* AwaitKeyword */;
27796     }
27797     ts.isAwaitKeyword = isAwaitKeyword;
27798     /* @internal */
27799     function isReadonlyKeyword(node) {
27800         return node.kind === 144 /* ReadonlyKeyword */;
27801     }
27802     ts.isReadonlyKeyword = isReadonlyKeyword;
27803     /* @internal */
27804     function isStaticModifier(node) {
27805         return node.kind === 124 /* StaticKeyword */;
27806     }
27807     ts.isStaticModifier = isStaticModifier;
27808     /* @internal */
27809     function isAbstractModifier(node) {
27810         return node.kind === 126 /* AbstractKeyword */;
27811     }
27812     ts.isAbstractModifier = isAbstractModifier;
27813     /*@internal*/
27814     function isSuperKeyword(node) {
27815         return node.kind === 106 /* SuperKeyword */;
27816     }
27817     ts.isSuperKeyword = isSuperKeyword;
27818     /*@internal*/
27819     function isImportKeyword(node) {
27820         return node.kind === 100 /* ImportKeyword */;
27821     }
27822     ts.isImportKeyword = isImportKeyword;
27823     // Names
27824     function isQualifiedName(node) {
27825         return node.kind === 160 /* QualifiedName */;
27826     }
27827     ts.isQualifiedName = isQualifiedName;
27828     function isComputedPropertyName(node) {
27829         return node.kind === 161 /* ComputedPropertyName */;
27830     }
27831     ts.isComputedPropertyName = isComputedPropertyName;
27832     // Signature elements
27833     function isTypeParameterDeclaration(node) {
27834         return node.kind === 162 /* TypeParameter */;
27835     }
27836     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
27837     // TODO(rbuckton): Rename to 'isParameterDeclaration'
27838     function isParameter(node) {
27839         return node.kind === 163 /* Parameter */;
27840     }
27841     ts.isParameter = isParameter;
27842     function isDecorator(node) {
27843         return node.kind === 164 /* Decorator */;
27844     }
27845     ts.isDecorator = isDecorator;
27846     // TypeMember
27847     function isPropertySignature(node) {
27848         return node.kind === 165 /* PropertySignature */;
27849     }
27850     ts.isPropertySignature = isPropertySignature;
27851     function isPropertyDeclaration(node) {
27852         return node.kind === 166 /* PropertyDeclaration */;
27853     }
27854     ts.isPropertyDeclaration = isPropertyDeclaration;
27855     function isMethodSignature(node) {
27856         return node.kind === 167 /* MethodSignature */;
27857     }
27858     ts.isMethodSignature = isMethodSignature;
27859     function isMethodDeclaration(node) {
27860         return node.kind === 168 /* MethodDeclaration */;
27861     }
27862     ts.isMethodDeclaration = isMethodDeclaration;
27863     function isClassStaticBlockDeclaration(node) {
27864         return node.kind === 169 /* ClassStaticBlockDeclaration */;
27865     }
27866     ts.isClassStaticBlockDeclaration = isClassStaticBlockDeclaration;
27867     function isConstructorDeclaration(node) {
27868         return node.kind === 170 /* Constructor */;
27869     }
27870     ts.isConstructorDeclaration = isConstructorDeclaration;
27871     function isGetAccessorDeclaration(node) {
27872         return node.kind === 171 /* GetAccessor */;
27873     }
27874     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
27875     function isSetAccessorDeclaration(node) {
27876         return node.kind === 172 /* SetAccessor */;
27877     }
27878     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
27879     function isCallSignatureDeclaration(node) {
27880         return node.kind === 173 /* CallSignature */;
27881     }
27882     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
27883     function isConstructSignatureDeclaration(node) {
27884         return node.kind === 174 /* ConstructSignature */;
27885     }
27886     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
27887     function isIndexSignatureDeclaration(node) {
27888         return node.kind === 175 /* IndexSignature */;
27889     }
27890     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
27891     // Type
27892     function isTypePredicateNode(node) {
27893         return node.kind === 176 /* TypePredicate */;
27894     }
27895     ts.isTypePredicateNode = isTypePredicateNode;
27896     function isTypeReferenceNode(node) {
27897         return node.kind === 177 /* TypeReference */;
27898     }
27899     ts.isTypeReferenceNode = isTypeReferenceNode;
27900     function isFunctionTypeNode(node) {
27901         return node.kind === 178 /* FunctionType */;
27902     }
27903     ts.isFunctionTypeNode = isFunctionTypeNode;
27904     function isConstructorTypeNode(node) {
27905         return node.kind === 179 /* ConstructorType */;
27906     }
27907     ts.isConstructorTypeNode = isConstructorTypeNode;
27908     function isTypeQueryNode(node) {
27909         return node.kind === 180 /* TypeQuery */;
27910     }
27911     ts.isTypeQueryNode = isTypeQueryNode;
27912     function isTypeLiteralNode(node) {
27913         return node.kind === 181 /* TypeLiteral */;
27914     }
27915     ts.isTypeLiteralNode = isTypeLiteralNode;
27916     function isArrayTypeNode(node) {
27917         return node.kind === 182 /* ArrayType */;
27918     }
27919     ts.isArrayTypeNode = isArrayTypeNode;
27920     function isTupleTypeNode(node) {
27921         return node.kind === 183 /* TupleType */;
27922     }
27923     ts.isTupleTypeNode = isTupleTypeNode;
27924     function isNamedTupleMember(node) {
27925         return node.kind === 196 /* NamedTupleMember */;
27926     }
27927     ts.isNamedTupleMember = isNamedTupleMember;
27928     function isOptionalTypeNode(node) {
27929         return node.kind === 184 /* OptionalType */;
27930     }
27931     ts.isOptionalTypeNode = isOptionalTypeNode;
27932     function isRestTypeNode(node) {
27933         return node.kind === 185 /* RestType */;
27934     }
27935     ts.isRestTypeNode = isRestTypeNode;
27936     function isUnionTypeNode(node) {
27937         return node.kind === 186 /* UnionType */;
27938     }
27939     ts.isUnionTypeNode = isUnionTypeNode;
27940     function isIntersectionTypeNode(node) {
27941         return node.kind === 187 /* IntersectionType */;
27942     }
27943     ts.isIntersectionTypeNode = isIntersectionTypeNode;
27944     function isConditionalTypeNode(node) {
27945         return node.kind === 188 /* ConditionalType */;
27946     }
27947     ts.isConditionalTypeNode = isConditionalTypeNode;
27948     function isInferTypeNode(node) {
27949         return node.kind === 189 /* InferType */;
27950     }
27951     ts.isInferTypeNode = isInferTypeNode;
27952     function isParenthesizedTypeNode(node) {
27953         return node.kind === 190 /* ParenthesizedType */;
27954     }
27955     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
27956     function isThisTypeNode(node) {
27957         return node.kind === 191 /* ThisType */;
27958     }
27959     ts.isThisTypeNode = isThisTypeNode;
27960     function isTypeOperatorNode(node) {
27961         return node.kind === 192 /* TypeOperator */;
27962     }
27963     ts.isTypeOperatorNode = isTypeOperatorNode;
27964     function isIndexedAccessTypeNode(node) {
27965         return node.kind === 193 /* IndexedAccessType */;
27966     }
27967     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
27968     function isMappedTypeNode(node) {
27969         return node.kind === 194 /* MappedType */;
27970     }
27971     ts.isMappedTypeNode = isMappedTypeNode;
27972     function isLiteralTypeNode(node) {
27973         return node.kind === 195 /* LiteralType */;
27974     }
27975     ts.isLiteralTypeNode = isLiteralTypeNode;
27976     function isImportTypeNode(node) {
27977         return node.kind === 199 /* ImportType */;
27978     }
27979     ts.isImportTypeNode = isImportTypeNode;
27980     function isTemplateLiteralTypeSpan(node) {
27981         return node.kind === 198 /* TemplateLiteralTypeSpan */;
27982     }
27983     ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
27984     function isTemplateLiteralTypeNode(node) {
27985         return node.kind === 197 /* TemplateLiteralType */;
27986     }
27987     ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
27988     // Binding patterns
27989     function isObjectBindingPattern(node) {
27990         return node.kind === 200 /* ObjectBindingPattern */;
27991     }
27992     ts.isObjectBindingPattern = isObjectBindingPattern;
27993     function isArrayBindingPattern(node) {
27994         return node.kind === 201 /* ArrayBindingPattern */;
27995     }
27996     ts.isArrayBindingPattern = isArrayBindingPattern;
27997     function isBindingElement(node) {
27998         return node.kind === 202 /* BindingElement */;
27999     }
28000     ts.isBindingElement = isBindingElement;
28001     // Expression
28002     function isArrayLiteralExpression(node) {
28003         return node.kind === 203 /* ArrayLiteralExpression */;
28004     }
28005     ts.isArrayLiteralExpression = isArrayLiteralExpression;
28006     function isObjectLiteralExpression(node) {
28007         return node.kind === 204 /* ObjectLiteralExpression */;
28008     }
28009     ts.isObjectLiteralExpression = isObjectLiteralExpression;
28010     function isPropertyAccessExpression(node) {
28011         return node.kind === 205 /* PropertyAccessExpression */;
28012     }
28013     ts.isPropertyAccessExpression = isPropertyAccessExpression;
28014     function isElementAccessExpression(node) {
28015         return node.kind === 206 /* ElementAccessExpression */;
28016     }
28017     ts.isElementAccessExpression = isElementAccessExpression;
28018     function isCallExpression(node) {
28019         return node.kind === 207 /* CallExpression */;
28020     }
28021     ts.isCallExpression = isCallExpression;
28022     function isNewExpression(node) {
28023         return node.kind === 208 /* NewExpression */;
28024     }
28025     ts.isNewExpression = isNewExpression;
28026     function isTaggedTemplateExpression(node) {
28027         return node.kind === 209 /* TaggedTemplateExpression */;
28028     }
28029     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
28030     function isTypeAssertionExpression(node) {
28031         return node.kind === 210 /* TypeAssertionExpression */;
28032     }
28033     ts.isTypeAssertionExpression = isTypeAssertionExpression;
28034     function isParenthesizedExpression(node) {
28035         return node.kind === 211 /* ParenthesizedExpression */;
28036     }
28037     ts.isParenthesizedExpression = isParenthesizedExpression;
28038     function isFunctionExpression(node) {
28039         return node.kind === 212 /* FunctionExpression */;
28040     }
28041     ts.isFunctionExpression = isFunctionExpression;
28042     function isArrowFunction(node) {
28043         return node.kind === 213 /* ArrowFunction */;
28044     }
28045     ts.isArrowFunction = isArrowFunction;
28046     function isDeleteExpression(node) {
28047         return node.kind === 214 /* DeleteExpression */;
28048     }
28049     ts.isDeleteExpression = isDeleteExpression;
28050     function isTypeOfExpression(node) {
28051         return node.kind === 215 /* TypeOfExpression */;
28052     }
28053     ts.isTypeOfExpression = isTypeOfExpression;
28054     function isVoidExpression(node) {
28055         return node.kind === 216 /* VoidExpression */;
28056     }
28057     ts.isVoidExpression = isVoidExpression;
28058     function isAwaitExpression(node) {
28059         return node.kind === 217 /* AwaitExpression */;
28060     }
28061     ts.isAwaitExpression = isAwaitExpression;
28062     function isPrefixUnaryExpression(node) {
28063         return node.kind === 218 /* PrefixUnaryExpression */;
28064     }
28065     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
28066     function isPostfixUnaryExpression(node) {
28067         return node.kind === 219 /* PostfixUnaryExpression */;
28068     }
28069     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
28070     function isBinaryExpression(node) {
28071         return node.kind === 220 /* BinaryExpression */;
28072     }
28073     ts.isBinaryExpression = isBinaryExpression;
28074     function isConditionalExpression(node) {
28075         return node.kind === 221 /* ConditionalExpression */;
28076     }
28077     ts.isConditionalExpression = isConditionalExpression;
28078     function isTemplateExpression(node) {
28079         return node.kind === 222 /* TemplateExpression */;
28080     }
28081     ts.isTemplateExpression = isTemplateExpression;
28082     function isYieldExpression(node) {
28083         return node.kind === 223 /* YieldExpression */;
28084     }
28085     ts.isYieldExpression = isYieldExpression;
28086     function isSpreadElement(node) {
28087         return node.kind === 224 /* SpreadElement */;
28088     }
28089     ts.isSpreadElement = isSpreadElement;
28090     function isClassExpression(node) {
28091         return node.kind === 225 /* ClassExpression */;
28092     }
28093     ts.isClassExpression = isClassExpression;
28094     function isOmittedExpression(node) {
28095         return node.kind === 226 /* OmittedExpression */;
28096     }
28097     ts.isOmittedExpression = isOmittedExpression;
28098     function isExpressionWithTypeArguments(node) {
28099         return node.kind === 227 /* ExpressionWithTypeArguments */;
28100     }
28101     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
28102     function isAsExpression(node) {
28103         return node.kind === 228 /* AsExpression */;
28104     }
28105     ts.isAsExpression = isAsExpression;
28106     function isNonNullExpression(node) {
28107         return node.kind === 229 /* NonNullExpression */;
28108     }
28109     ts.isNonNullExpression = isNonNullExpression;
28110     function isMetaProperty(node) {
28111         return node.kind === 230 /* MetaProperty */;
28112     }
28113     ts.isMetaProperty = isMetaProperty;
28114     function isSyntheticExpression(node) {
28115         return node.kind === 231 /* SyntheticExpression */;
28116     }
28117     ts.isSyntheticExpression = isSyntheticExpression;
28118     function isPartiallyEmittedExpression(node) {
28119         return node.kind === 348 /* PartiallyEmittedExpression */;
28120     }
28121     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
28122     function isCommaListExpression(node) {
28123         return node.kind === 349 /* CommaListExpression */;
28124     }
28125     ts.isCommaListExpression = isCommaListExpression;
28126     // Misc
28127     function isTemplateSpan(node) {
28128         return node.kind === 232 /* TemplateSpan */;
28129     }
28130     ts.isTemplateSpan = isTemplateSpan;
28131     function isSemicolonClassElement(node) {
28132         return node.kind === 233 /* SemicolonClassElement */;
28133     }
28134     ts.isSemicolonClassElement = isSemicolonClassElement;
28135     // Elements
28136     function isBlock(node) {
28137         return node.kind === 234 /* Block */;
28138     }
28139     ts.isBlock = isBlock;
28140     function isVariableStatement(node) {
28141         return node.kind === 236 /* VariableStatement */;
28142     }
28143     ts.isVariableStatement = isVariableStatement;
28144     function isEmptyStatement(node) {
28145         return node.kind === 235 /* EmptyStatement */;
28146     }
28147     ts.isEmptyStatement = isEmptyStatement;
28148     function isExpressionStatement(node) {
28149         return node.kind === 237 /* ExpressionStatement */;
28150     }
28151     ts.isExpressionStatement = isExpressionStatement;
28152     function isIfStatement(node) {
28153         return node.kind === 238 /* IfStatement */;
28154     }
28155     ts.isIfStatement = isIfStatement;
28156     function isDoStatement(node) {
28157         return node.kind === 239 /* DoStatement */;
28158     }
28159     ts.isDoStatement = isDoStatement;
28160     function isWhileStatement(node) {
28161         return node.kind === 240 /* WhileStatement */;
28162     }
28163     ts.isWhileStatement = isWhileStatement;
28164     function isForStatement(node) {
28165         return node.kind === 241 /* ForStatement */;
28166     }
28167     ts.isForStatement = isForStatement;
28168     function isForInStatement(node) {
28169         return node.kind === 242 /* ForInStatement */;
28170     }
28171     ts.isForInStatement = isForInStatement;
28172     function isForOfStatement(node) {
28173         return node.kind === 243 /* ForOfStatement */;
28174     }
28175     ts.isForOfStatement = isForOfStatement;
28176     function isContinueStatement(node) {
28177         return node.kind === 244 /* ContinueStatement */;
28178     }
28179     ts.isContinueStatement = isContinueStatement;
28180     function isBreakStatement(node) {
28181         return node.kind === 245 /* BreakStatement */;
28182     }
28183     ts.isBreakStatement = isBreakStatement;
28184     function isReturnStatement(node) {
28185         return node.kind === 246 /* ReturnStatement */;
28186     }
28187     ts.isReturnStatement = isReturnStatement;
28188     function isWithStatement(node) {
28189         return node.kind === 247 /* WithStatement */;
28190     }
28191     ts.isWithStatement = isWithStatement;
28192     function isSwitchStatement(node) {
28193         return node.kind === 248 /* SwitchStatement */;
28194     }
28195     ts.isSwitchStatement = isSwitchStatement;
28196     function isLabeledStatement(node) {
28197         return node.kind === 249 /* LabeledStatement */;
28198     }
28199     ts.isLabeledStatement = isLabeledStatement;
28200     function isThrowStatement(node) {
28201         return node.kind === 250 /* ThrowStatement */;
28202     }
28203     ts.isThrowStatement = isThrowStatement;
28204     function isTryStatement(node) {
28205         return node.kind === 251 /* TryStatement */;
28206     }
28207     ts.isTryStatement = isTryStatement;
28208     function isDebuggerStatement(node) {
28209         return node.kind === 252 /* DebuggerStatement */;
28210     }
28211     ts.isDebuggerStatement = isDebuggerStatement;
28212     function isVariableDeclaration(node) {
28213         return node.kind === 253 /* VariableDeclaration */;
28214     }
28215     ts.isVariableDeclaration = isVariableDeclaration;
28216     function isVariableDeclarationList(node) {
28217         return node.kind === 254 /* VariableDeclarationList */;
28218     }
28219     ts.isVariableDeclarationList = isVariableDeclarationList;
28220     function isFunctionDeclaration(node) {
28221         return node.kind === 255 /* FunctionDeclaration */;
28222     }
28223     ts.isFunctionDeclaration = isFunctionDeclaration;
28224     function isClassDeclaration(node) {
28225         return node.kind === 256 /* ClassDeclaration */;
28226     }
28227     ts.isClassDeclaration = isClassDeclaration;
28228     function isInterfaceDeclaration(node) {
28229         return node.kind === 257 /* InterfaceDeclaration */;
28230     }
28231     ts.isInterfaceDeclaration = isInterfaceDeclaration;
28232     function isTypeAliasDeclaration(node) {
28233         return node.kind === 258 /* TypeAliasDeclaration */;
28234     }
28235     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
28236     function isEnumDeclaration(node) {
28237         return node.kind === 259 /* EnumDeclaration */;
28238     }
28239     ts.isEnumDeclaration = isEnumDeclaration;
28240     function isModuleDeclaration(node) {
28241         return node.kind === 260 /* ModuleDeclaration */;
28242     }
28243     ts.isModuleDeclaration = isModuleDeclaration;
28244     function isModuleBlock(node) {
28245         return node.kind === 261 /* ModuleBlock */;
28246     }
28247     ts.isModuleBlock = isModuleBlock;
28248     function isCaseBlock(node) {
28249         return node.kind === 262 /* CaseBlock */;
28250     }
28251     ts.isCaseBlock = isCaseBlock;
28252     function isNamespaceExportDeclaration(node) {
28253         return node.kind === 263 /* NamespaceExportDeclaration */;
28254     }
28255     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
28256     function isImportEqualsDeclaration(node) {
28257         return node.kind === 264 /* ImportEqualsDeclaration */;
28258     }
28259     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
28260     function isImportDeclaration(node) {
28261         return node.kind === 265 /* ImportDeclaration */;
28262     }
28263     ts.isImportDeclaration = isImportDeclaration;
28264     function isImportClause(node) {
28265         return node.kind === 266 /* ImportClause */;
28266     }
28267     ts.isImportClause = isImportClause;
28268     function isAssertClause(node) {
28269         return node.kind === 292 /* AssertClause */;
28270     }
28271     ts.isAssertClause = isAssertClause;
28272     function isAssertEntry(node) {
28273         return node.kind === 293 /* AssertEntry */;
28274     }
28275     ts.isAssertEntry = isAssertEntry;
28276     function isNamespaceImport(node) {
28277         return node.kind === 267 /* NamespaceImport */;
28278     }
28279     ts.isNamespaceImport = isNamespaceImport;
28280     function isNamespaceExport(node) {
28281         return node.kind === 273 /* NamespaceExport */;
28282     }
28283     ts.isNamespaceExport = isNamespaceExport;
28284     function isNamedImports(node) {
28285         return node.kind === 268 /* NamedImports */;
28286     }
28287     ts.isNamedImports = isNamedImports;
28288     function isImportSpecifier(node) {
28289         return node.kind === 269 /* ImportSpecifier */;
28290     }
28291     ts.isImportSpecifier = isImportSpecifier;
28292     function isExportAssignment(node) {
28293         return node.kind === 270 /* ExportAssignment */;
28294     }
28295     ts.isExportAssignment = isExportAssignment;
28296     function isExportDeclaration(node) {
28297         return node.kind === 271 /* ExportDeclaration */;
28298     }
28299     ts.isExportDeclaration = isExportDeclaration;
28300     function isNamedExports(node) {
28301         return node.kind === 272 /* NamedExports */;
28302     }
28303     ts.isNamedExports = isNamedExports;
28304     function isExportSpecifier(node) {
28305         return node.kind === 274 /* ExportSpecifier */;
28306     }
28307     ts.isExportSpecifier = isExportSpecifier;
28308     function isMissingDeclaration(node) {
28309         return node.kind === 275 /* MissingDeclaration */;
28310     }
28311     ts.isMissingDeclaration = isMissingDeclaration;
28312     function isNotEmittedStatement(node) {
28313         return node.kind === 347 /* NotEmittedStatement */;
28314     }
28315     ts.isNotEmittedStatement = isNotEmittedStatement;
28316     /* @internal */
28317     function isSyntheticReference(node) {
28318         return node.kind === 352 /* SyntheticReferenceExpression */;
28319     }
28320     ts.isSyntheticReference = isSyntheticReference;
28321     /* @internal */
28322     function isMergeDeclarationMarker(node) {
28323         return node.kind === 350 /* MergeDeclarationMarker */;
28324     }
28325     ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
28326     /* @internal */
28327     function isEndOfDeclarationMarker(node) {
28328         return node.kind === 351 /* EndOfDeclarationMarker */;
28329     }
28330     ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
28331     // Module References
28332     function isExternalModuleReference(node) {
28333         return node.kind === 276 /* ExternalModuleReference */;
28334     }
28335     ts.isExternalModuleReference = isExternalModuleReference;
28336     // JSX
28337     function isJsxElement(node) {
28338         return node.kind === 277 /* JsxElement */;
28339     }
28340     ts.isJsxElement = isJsxElement;
28341     function isJsxSelfClosingElement(node) {
28342         return node.kind === 278 /* JsxSelfClosingElement */;
28343     }
28344     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
28345     function isJsxOpeningElement(node) {
28346         return node.kind === 279 /* JsxOpeningElement */;
28347     }
28348     ts.isJsxOpeningElement = isJsxOpeningElement;
28349     function isJsxClosingElement(node) {
28350         return node.kind === 280 /* JsxClosingElement */;
28351     }
28352     ts.isJsxClosingElement = isJsxClosingElement;
28353     function isJsxFragment(node) {
28354         return node.kind === 281 /* JsxFragment */;
28355     }
28356     ts.isJsxFragment = isJsxFragment;
28357     function isJsxOpeningFragment(node) {
28358         return node.kind === 282 /* JsxOpeningFragment */;
28359     }
28360     ts.isJsxOpeningFragment = isJsxOpeningFragment;
28361     function isJsxClosingFragment(node) {
28362         return node.kind === 283 /* JsxClosingFragment */;
28363     }
28364     ts.isJsxClosingFragment = isJsxClosingFragment;
28365     function isJsxAttribute(node) {
28366         return node.kind === 284 /* JsxAttribute */;
28367     }
28368     ts.isJsxAttribute = isJsxAttribute;
28369     function isJsxAttributes(node) {
28370         return node.kind === 285 /* JsxAttributes */;
28371     }
28372     ts.isJsxAttributes = isJsxAttributes;
28373     function isJsxSpreadAttribute(node) {
28374         return node.kind === 286 /* JsxSpreadAttribute */;
28375     }
28376     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
28377     function isJsxExpression(node) {
28378         return node.kind === 287 /* JsxExpression */;
28379     }
28380     ts.isJsxExpression = isJsxExpression;
28381     // Clauses
28382     function isCaseClause(node) {
28383         return node.kind === 288 /* CaseClause */;
28384     }
28385     ts.isCaseClause = isCaseClause;
28386     function isDefaultClause(node) {
28387         return node.kind === 289 /* DefaultClause */;
28388     }
28389     ts.isDefaultClause = isDefaultClause;
28390     function isHeritageClause(node) {
28391         return node.kind === 290 /* HeritageClause */;
28392     }
28393     ts.isHeritageClause = isHeritageClause;
28394     function isCatchClause(node) {
28395         return node.kind === 291 /* CatchClause */;
28396     }
28397     ts.isCatchClause = isCatchClause;
28398     // Property assignments
28399     function isPropertyAssignment(node) {
28400         return node.kind === 294 /* PropertyAssignment */;
28401     }
28402     ts.isPropertyAssignment = isPropertyAssignment;
28403     function isShorthandPropertyAssignment(node) {
28404         return node.kind === 295 /* ShorthandPropertyAssignment */;
28405     }
28406     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
28407     function isSpreadAssignment(node) {
28408         return node.kind === 296 /* SpreadAssignment */;
28409     }
28410     ts.isSpreadAssignment = isSpreadAssignment;
28411     // Enum
28412     function isEnumMember(node) {
28413         return node.kind === 297 /* EnumMember */;
28414     }
28415     ts.isEnumMember = isEnumMember;
28416     // Unparsed
28417     // TODO(rbuckton): isUnparsedPrologue
28418     function isUnparsedPrepend(node) {
28419         return node.kind === 299 /* UnparsedPrepend */;
28420     }
28421     ts.isUnparsedPrepend = isUnparsedPrepend;
28422     // TODO(rbuckton): isUnparsedText
28423     // TODO(rbuckton): isUnparsedInternalText
28424     // TODO(rbuckton): isUnparsedSyntheticReference
28425     // Top-level nodes
28426     function isSourceFile(node) {
28427         return node.kind === 303 /* SourceFile */;
28428     }
28429     ts.isSourceFile = isSourceFile;
28430     function isBundle(node) {
28431         return node.kind === 304 /* Bundle */;
28432     }
28433     ts.isBundle = isBundle;
28434     function isUnparsedSource(node) {
28435         return node.kind === 305 /* UnparsedSource */;
28436     }
28437     ts.isUnparsedSource = isUnparsedSource;
28438     // TODO(rbuckton): isInputFiles
28439     // JSDoc Elements
28440     function isJSDocTypeExpression(node) {
28441         return node.kind === 307 /* JSDocTypeExpression */;
28442     }
28443     ts.isJSDocTypeExpression = isJSDocTypeExpression;
28444     function isJSDocNameReference(node) {
28445         return node.kind === 308 /* JSDocNameReference */;
28446     }
28447     ts.isJSDocNameReference = isJSDocNameReference;
28448     function isJSDocMemberName(node) {
28449         return node.kind === 309 /* JSDocMemberName */;
28450     }
28451     ts.isJSDocMemberName = isJSDocMemberName;
28452     function isJSDocLink(node) {
28453         return node.kind === 322 /* JSDocLink */;
28454     }
28455     ts.isJSDocLink = isJSDocLink;
28456     function isJSDocLinkCode(node) {
28457         return node.kind === 323 /* JSDocLinkCode */;
28458     }
28459     ts.isJSDocLinkCode = isJSDocLinkCode;
28460     function isJSDocLinkPlain(node) {
28461         return node.kind === 324 /* JSDocLinkPlain */;
28462     }
28463     ts.isJSDocLinkPlain = isJSDocLinkPlain;
28464     function isJSDocAllType(node) {
28465         return node.kind === 310 /* JSDocAllType */;
28466     }
28467     ts.isJSDocAllType = isJSDocAllType;
28468     function isJSDocUnknownType(node) {
28469         return node.kind === 311 /* JSDocUnknownType */;
28470     }
28471     ts.isJSDocUnknownType = isJSDocUnknownType;
28472     function isJSDocNullableType(node) {
28473         return node.kind === 312 /* JSDocNullableType */;
28474     }
28475     ts.isJSDocNullableType = isJSDocNullableType;
28476     function isJSDocNonNullableType(node) {
28477         return node.kind === 313 /* JSDocNonNullableType */;
28478     }
28479     ts.isJSDocNonNullableType = isJSDocNonNullableType;
28480     function isJSDocOptionalType(node) {
28481         return node.kind === 314 /* JSDocOptionalType */;
28482     }
28483     ts.isJSDocOptionalType = isJSDocOptionalType;
28484     function isJSDocFunctionType(node) {
28485         return node.kind === 315 /* JSDocFunctionType */;
28486     }
28487     ts.isJSDocFunctionType = isJSDocFunctionType;
28488     function isJSDocVariadicType(node) {
28489         return node.kind === 316 /* JSDocVariadicType */;
28490     }
28491     ts.isJSDocVariadicType = isJSDocVariadicType;
28492     function isJSDocNamepathType(node) {
28493         return node.kind === 317 /* JSDocNamepathType */;
28494     }
28495     ts.isJSDocNamepathType = isJSDocNamepathType;
28496     function isJSDoc(node) {
28497         return node.kind === 318 /* JSDocComment */;
28498     }
28499     ts.isJSDoc = isJSDoc;
28500     function isJSDocTypeLiteral(node) {
28501         return node.kind === 320 /* JSDocTypeLiteral */;
28502     }
28503     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
28504     function isJSDocSignature(node) {
28505         return node.kind === 321 /* JSDocSignature */;
28506     }
28507     ts.isJSDocSignature = isJSDocSignature;
28508     // JSDoc Tags
28509     function isJSDocAugmentsTag(node) {
28510         return node.kind === 326 /* JSDocAugmentsTag */;
28511     }
28512     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
28513     function isJSDocAuthorTag(node) {
28514         return node.kind === 328 /* JSDocAuthorTag */;
28515     }
28516     ts.isJSDocAuthorTag = isJSDocAuthorTag;
28517     function isJSDocClassTag(node) {
28518         return node.kind === 330 /* JSDocClassTag */;
28519     }
28520     ts.isJSDocClassTag = isJSDocClassTag;
28521     function isJSDocCallbackTag(node) {
28522         return node.kind === 336 /* JSDocCallbackTag */;
28523     }
28524     ts.isJSDocCallbackTag = isJSDocCallbackTag;
28525     function isJSDocPublicTag(node) {
28526         return node.kind === 331 /* JSDocPublicTag */;
28527     }
28528     ts.isJSDocPublicTag = isJSDocPublicTag;
28529     function isJSDocPrivateTag(node) {
28530         return node.kind === 332 /* JSDocPrivateTag */;
28531     }
28532     ts.isJSDocPrivateTag = isJSDocPrivateTag;
28533     function isJSDocProtectedTag(node) {
28534         return node.kind === 333 /* JSDocProtectedTag */;
28535     }
28536     ts.isJSDocProtectedTag = isJSDocProtectedTag;
28537     function isJSDocReadonlyTag(node) {
28538         return node.kind === 334 /* JSDocReadonlyTag */;
28539     }
28540     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
28541     function isJSDocOverrideTag(node) {
28542         return node.kind === 335 /* JSDocOverrideTag */;
28543     }
28544     ts.isJSDocOverrideTag = isJSDocOverrideTag;
28545     function isJSDocDeprecatedTag(node) {
28546         return node.kind === 329 /* JSDocDeprecatedTag */;
28547     }
28548     ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
28549     function isJSDocSeeTag(node) {
28550         return node.kind === 344 /* JSDocSeeTag */;
28551     }
28552     ts.isJSDocSeeTag = isJSDocSeeTag;
28553     function isJSDocEnumTag(node) {
28554         return node.kind === 337 /* JSDocEnumTag */;
28555     }
28556     ts.isJSDocEnumTag = isJSDocEnumTag;
28557     function isJSDocParameterTag(node) {
28558         return node.kind === 338 /* JSDocParameterTag */;
28559     }
28560     ts.isJSDocParameterTag = isJSDocParameterTag;
28561     function isJSDocReturnTag(node) {
28562         return node.kind === 339 /* JSDocReturnTag */;
28563     }
28564     ts.isJSDocReturnTag = isJSDocReturnTag;
28565     function isJSDocThisTag(node) {
28566         return node.kind === 340 /* JSDocThisTag */;
28567     }
28568     ts.isJSDocThisTag = isJSDocThisTag;
28569     function isJSDocTypeTag(node) {
28570         return node.kind === 341 /* JSDocTypeTag */;
28571     }
28572     ts.isJSDocTypeTag = isJSDocTypeTag;
28573     function isJSDocTemplateTag(node) {
28574         return node.kind === 342 /* JSDocTemplateTag */;
28575     }
28576     ts.isJSDocTemplateTag = isJSDocTemplateTag;
28577     function isJSDocTypedefTag(node) {
28578         return node.kind === 343 /* JSDocTypedefTag */;
28579     }
28580     ts.isJSDocTypedefTag = isJSDocTypedefTag;
28581     function isJSDocUnknownTag(node) {
28582         return node.kind === 325 /* JSDocTag */;
28583     }
28584     ts.isJSDocUnknownTag = isJSDocUnknownTag;
28585     function isJSDocPropertyTag(node) {
28586         return node.kind === 345 /* JSDocPropertyTag */;
28587     }
28588     ts.isJSDocPropertyTag = isJSDocPropertyTag;
28589     function isJSDocImplementsTag(node) {
28590         return node.kind === 327 /* JSDocImplementsTag */;
28591     }
28592     ts.isJSDocImplementsTag = isJSDocImplementsTag;
28593     // Synthesized list
28594     /* @internal */
28595     function isSyntaxList(n) {
28596         return n.kind === 346 /* SyntaxList */;
28597     }
28598     ts.isSyntaxList = isSyntaxList;
28599 })(ts || (ts = {}));
28600 /* @internal */
28601 var ts;
28602 (function (ts) {
28603     // Compound nodes
28604     function createEmptyExports(factory) {
28605         return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
28606     }
28607     ts.createEmptyExports = createEmptyExports;
28608     function createMemberAccessForPropertyName(factory, target, memberName, location) {
28609         if (ts.isComputedPropertyName(memberName)) {
28610             return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
28611         }
28612         else {
28613             var expression = ts.setTextRange(ts.isMemberName(memberName)
28614                 ? factory.createPropertyAccessExpression(target, memberName)
28615                 : factory.createElementAccessExpression(target, memberName), memberName);
28616             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
28617             return expression;
28618         }
28619     }
28620     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
28621     function createReactNamespace(reactNamespace, parent) {
28622         // To ensure the emit resolver can properly resolve the namespace, we need to
28623         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
28624         // flag and setting a parent node.
28625         var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
28626         // Set the parent that is in parse tree
28627         // this makes sure that parent chain is intact for checker to traverse complete scope tree
28628         ts.setParent(react, ts.getParseTreeNode(parent));
28629         return react;
28630     }
28631     function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
28632         if (ts.isQualifiedName(jsxFactory)) {
28633             var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
28634             var right = factory.createIdentifier(ts.idText(jsxFactory.right));
28635             right.escapedText = jsxFactory.right.escapedText;
28636             return factory.createPropertyAccessExpression(left, right);
28637         }
28638         else {
28639             return createReactNamespace(ts.idText(jsxFactory), parent);
28640         }
28641     }
28642     function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
28643         return jsxFactoryEntity ?
28644             createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
28645             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
28646     }
28647     ts.createJsxFactoryExpression = createJsxFactoryExpression;
28648     function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
28649         return jsxFragmentFactoryEntity ?
28650             createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
28651             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
28652     }
28653     function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
28654         var argumentsList = [tagName];
28655         if (props) {
28656             argumentsList.push(props);
28657         }
28658         if (children && children.length > 0) {
28659             if (!props) {
28660                 argumentsList.push(factory.createNull());
28661             }
28662             if (children.length > 1) {
28663                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
28664                     var child = children_3[_i];
28665                     startOnNewLine(child);
28666                     argumentsList.push(child);
28667                 }
28668             }
28669             else {
28670                 argumentsList.push(children[0]);
28671             }
28672         }
28673         return ts.setTextRange(factory.createCallExpression(callee, 
28674         /*typeArguments*/ undefined, argumentsList), location);
28675     }
28676     ts.createExpressionForJsxElement = createExpressionForJsxElement;
28677     function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
28678         var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
28679         var argumentsList = [tagName, factory.createNull()];
28680         if (children && children.length > 0) {
28681             if (children.length > 1) {
28682                 for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
28683                     var child = children_4[_i];
28684                     startOnNewLine(child);
28685                     argumentsList.push(child);
28686                 }
28687             }
28688             else {
28689                 argumentsList.push(children[0]);
28690             }
28691         }
28692         return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), 
28693         /*typeArguments*/ undefined, argumentsList), location);
28694     }
28695     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
28696     // Utilities
28697     function createForOfBindingStatement(factory, node, boundValue) {
28698         if (ts.isVariableDeclarationList(node)) {
28699             var firstDeclaration = ts.first(node.declarations);
28700             var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
28701             /*exclamationToken*/ undefined, 
28702             /*type*/ undefined, boundValue);
28703             return ts.setTextRange(factory.createVariableStatement(
28704             /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])), 
28705             /*location*/ node);
28706         }
28707         else {
28708             var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
28709             return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
28710         }
28711     }
28712     ts.createForOfBindingStatement = createForOfBindingStatement;
28713     function insertLeadingStatement(factory, dest, source) {
28714         if (ts.isBlock(dest)) {
28715             return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArray([source], dest.statements, true)), dest.statements));
28716         }
28717         else {
28718             return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
28719         }
28720     }
28721     ts.insertLeadingStatement = insertLeadingStatement;
28722     function createExpressionFromEntityName(factory, node) {
28723         if (ts.isQualifiedName(node)) {
28724             var left = createExpressionFromEntityName(factory, node.left);
28725             // TODO(rbuckton): Does this need to be parented?
28726             var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
28727             return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
28728         }
28729         else {
28730             // TODO(rbuckton): Does this need to be parented?
28731             return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
28732         }
28733     }
28734     ts.createExpressionFromEntityName = createExpressionFromEntityName;
28735     function createExpressionForPropertyName(factory, memberName) {
28736         if (ts.isIdentifier(memberName)) {
28737             return factory.createStringLiteralFromNode(memberName);
28738         }
28739         else if (ts.isComputedPropertyName(memberName)) {
28740             // TODO(rbuckton): Does this need to be parented?
28741             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
28742         }
28743         else {
28744             // TODO(rbuckton): Does this need to be parented?
28745             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
28746         }
28747     }
28748     ts.createExpressionForPropertyName = createExpressionForPropertyName;
28749     function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
28750         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
28751         if (property === firstAccessor) {
28752             return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
28753                 enumerable: factory.createFalse(),
28754                 configurable: true,
28755                 get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, 
28756                 /*asteriskToken*/ undefined, 
28757                 /*name*/ undefined, 
28758                 /*typeParameters*/ undefined, getAccessor.parameters, 
28759                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
28760                 ), getAccessor), getAccessor),
28761                 set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, 
28762                 /*asteriskToken*/ undefined, 
28763                 /*name*/ undefined, 
28764                 /*typeParameters*/ undefined, setAccessor.parameters, 
28765                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
28766                 ), setAccessor), setAccessor)
28767             }, !multiLine)), firstAccessor);
28768         }
28769         return undefined;
28770     }
28771     function createExpressionForPropertyAssignment(factory, property, receiver) {
28772         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
28773     }
28774     function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
28775         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)), 
28776         /*location*/ property), 
28777         /*original*/ property);
28778     }
28779     function createExpressionForMethodDeclaration(factory, method, receiver) {
28780         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, 
28781         /*name*/ undefined, 
28782         /*typeParameters*/ undefined, method.parameters, 
28783         /*type*/ undefined, method.body // TODO: GH#18217
28784         ), 
28785         /*location*/ method), 
28786         /*original*/ method)), 
28787         /*location*/ method), 
28788         /*original*/ method);
28789     }
28790     function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
28791         if (property.name && ts.isPrivateIdentifier(property.name)) {
28792             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
28793         }
28794         switch (property.kind) {
28795             case 171 /* GetAccessor */:
28796             case 172 /* SetAccessor */:
28797                 return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
28798             case 294 /* PropertyAssignment */:
28799                 return createExpressionForPropertyAssignment(factory, property, receiver);
28800             case 295 /* ShorthandPropertyAssignment */:
28801                 return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
28802             case 168 /* MethodDeclaration */:
28803                 return createExpressionForMethodDeclaration(factory, property, receiver);
28804         }
28805     }
28806     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
28807     /**
28808      * Expand the read and increment/decrement operations a pre- or post-increment or pre- or post-decrement expression.
28809      *
28810      * ```ts
28811      * // input
28812      * <expression>++
28813      * // output (if result is not discarded)
28814      * var <temp>;
28815      * (<temp> = <expression>, <resultVariable> = <temp>++, <temp>)
28816      * // output (if result is discarded)
28817      * var <temp>;
28818      * (<temp> = <expression>, <temp>++, <temp>)
28819      *
28820      * // input
28821      * ++<expression>
28822      * // output (if result is not discarded)
28823      * var <temp>;
28824      * (<temp> = <expression>, <resultVariable> = ++<temp>)
28825      * // output (if result is discarded)
28826      * var <temp>;
28827      * (<temp> = <expression>, ++<temp>)
28828      * ```
28829      *
28830      * It is up to the caller to supply a temporary variable for `<resultVariable>` if one is needed.
28831      * The temporary variable `<temp>` is injected so that `++` and `--` work uniformly with `number` and `bigint`.
28832      * The result of the expression is always the final result of incrementing or decrementing the expression, so that it can be used for storage.
28833      *
28834      * @param factory {@link NodeFactory} used to create the expanded representation.
28835      * @param node The original prefix or postfix unary node.
28836      * @param expression The expression to use as the value to increment or decrement
28837      * @param resultVariable A temporary variable in which to store the result. Pass `undefined` if the result is discarded, or if the value of `<temp>` is the expected result.
28838      */
28839     function expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, recordTempVariable, resultVariable) {
28840         var operator = node.operator;
28841         ts.Debug.assert(operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression");
28842         var temp = factory.createTempVariable(recordTempVariable);
28843         expression = factory.createAssignment(temp, expression);
28844         ts.setTextRange(expression, node.operand);
28845         var operation = ts.isPrefixUnaryExpression(node) ?
28846             factory.createPrefixUnaryExpression(operator, temp) :
28847             factory.createPostfixUnaryExpression(temp, operator);
28848         ts.setTextRange(operation, node);
28849         if (resultVariable) {
28850             operation = factory.createAssignment(resultVariable, operation);
28851             ts.setTextRange(operation, node);
28852         }
28853         expression = factory.createComma(expression, operation);
28854         ts.setTextRange(expression, node);
28855         if (ts.isPostfixUnaryExpression(node)) {
28856             expression = factory.createComma(expression, temp);
28857             ts.setTextRange(expression, node);
28858         }
28859         return expression;
28860     }
28861     ts.expandPreOrPostfixIncrementOrDecrementExpression = expandPreOrPostfixIncrementOrDecrementExpression;
28862     /**
28863      * Gets whether an identifier should only be referred to by its internal name.
28864      */
28865     function isInternalName(node) {
28866         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
28867     }
28868     ts.isInternalName = isInternalName;
28869     /**
28870      * Gets whether an identifier should only be referred to by its local name.
28871      */
28872     function isLocalName(node) {
28873         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
28874     }
28875     ts.isLocalName = isLocalName;
28876     /**
28877      * Gets whether an identifier should only be referred to by its export representation if the
28878      * name points to an exported symbol.
28879      */
28880     function isExportName(node) {
28881         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
28882     }
28883     ts.isExportName = isExportName;
28884     function isUseStrictPrologue(node) {
28885         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
28886     }
28887     function findUseStrictPrologue(statements) {
28888         for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
28889             var statement = statements_1[_i];
28890             if (ts.isPrologueDirective(statement)) {
28891                 if (isUseStrictPrologue(statement)) {
28892                     return statement;
28893                 }
28894             }
28895             else {
28896                 break;
28897             }
28898         }
28899         return undefined;
28900     }
28901     ts.findUseStrictPrologue = findUseStrictPrologue;
28902     function startsWithUseStrict(statements) {
28903         var firstStatement = ts.firstOrUndefined(statements);
28904         return firstStatement !== undefined
28905             && ts.isPrologueDirective(firstStatement)
28906             && isUseStrictPrologue(firstStatement);
28907     }
28908     ts.startsWithUseStrict = startsWithUseStrict;
28909     function isCommaSequence(node) {
28910         return node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
28911             node.kind === 349 /* CommaListExpression */;
28912     }
28913     ts.isCommaSequence = isCommaSequence;
28914     function isJSDocTypeAssertion(node) {
28915         return ts.isParenthesizedExpression(node)
28916             && ts.isInJSFile(node)
28917             && !!ts.getJSDocTypeTag(node);
28918     }
28919     ts.isJSDocTypeAssertion = isJSDocTypeAssertion;
28920     function getJSDocTypeAssertionType(node) {
28921         var type = ts.getJSDocType(node);
28922         ts.Debug.assertIsDefined(type);
28923         return type;
28924     }
28925     ts.getJSDocTypeAssertionType = getJSDocTypeAssertionType;
28926     function isOuterExpression(node, kinds) {
28927         if (kinds === void 0) { kinds = 15 /* All */; }
28928         switch (node.kind) {
28929             case 211 /* ParenthesizedExpression */:
28930                 if (kinds & 16 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) {
28931                     return false;
28932                 }
28933                 return (kinds & 1 /* Parentheses */) !== 0;
28934             case 210 /* TypeAssertionExpression */:
28935             case 228 /* AsExpression */:
28936                 return (kinds & 2 /* TypeAssertions */) !== 0;
28937             case 229 /* NonNullExpression */:
28938                 return (kinds & 4 /* NonNullAssertions */) !== 0;
28939             case 348 /* PartiallyEmittedExpression */:
28940                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
28941         }
28942         return false;
28943     }
28944     ts.isOuterExpression = isOuterExpression;
28945     function skipOuterExpressions(node, kinds) {
28946         if (kinds === void 0) { kinds = 15 /* All */; }
28947         while (isOuterExpression(node, kinds)) {
28948             node = node.expression;
28949         }
28950         return node;
28951     }
28952     ts.skipOuterExpressions = skipOuterExpressions;
28953     function skipAssertions(node) {
28954         return skipOuterExpressions(node, 6 /* Assertions */);
28955     }
28956     ts.skipAssertions = skipAssertions;
28957     function startOnNewLine(node) {
28958         return ts.setStartsOnNewLine(node, /*newLine*/ true);
28959     }
28960     ts.startOnNewLine = startOnNewLine;
28961     function getExternalHelpersModuleName(node) {
28962         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
28963         var emitNode = parseNode && parseNode.emitNode;
28964         return emitNode && emitNode.externalHelpersModuleName;
28965     }
28966     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
28967     function hasRecordedExternalHelpers(sourceFile) {
28968         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
28969         var emitNode = parseNode && parseNode.emitNode;
28970         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
28971     }
28972     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
28973     function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
28974         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
28975             var namedBindings = void 0;
28976             var moduleKind = ts.getEmitModuleKind(compilerOptions);
28977             if ((moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) || sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) {
28978                 // use named imports
28979                 var helpers = ts.getEmitHelpers(sourceFile);
28980                 if (helpers) {
28981                     var helperNames = [];
28982                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
28983                         var helper = helpers_3[_i];
28984                         if (!helper.scoped) {
28985                             var importName = helper.importName;
28986                             if (importName) {
28987                                 ts.pushIfUnique(helperNames, importName);
28988                             }
28989                         }
28990                     }
28991                     if (ts.some(helperNames)) {
28992                         helperNames.sort(ts.compareStringsCaseSensitive);
28993                         // Alias the imports if the names are used somewhere in the file.
28994                         // NOTE: We don't need to care about global import collisions as this is a module.
28995                         namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
28996                             ? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name))
28997                             : nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
28998                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
28999                         var emitNode = ts.getOrCreateEmitNode(parseNode);
29000                         emitNode.externalHelpers = true;
29001                     }
29002                 }
29003             }
29004             else {
29005                 // use a namespace import
29006                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
29007                 if (externalHelpersModuleName) {
29008                     namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
29009                 }
29010             }
29011             if (namedBindings) {
29012                 var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
29013                 /*decorators*/ undefined, 
29014                 /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), 
29015                 /*assertClause*/ undefined);
29016                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
29017                 return externalHelpersImportDeclaration;
29018             }
29019         }
29020     }
29021     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
29022     function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
29023         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
29024             var externalHelpersModuleName = getExternalHelpersModuleName(node);
29025             if (externalHelpersModuleName) {
29026                 return externalHelpersModuleName;
29027             }
29028             var moduleKind = ts.getEmitModuleKind(compilerOptions);
29029             var create = (hasExportStarsToExportValues || (ts.getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault))
29030                 && moduleKind !== ts.ModuleKind.System
29031                 && (moduleKind < ts.ModuleKind.ES2015 || node.impliedNodeFormat === ts.ModuleKind.CommonJS);
29032             if (!create) {
29033                 var helpers = ts.getEmitHelpers(node);
29034                 if (helpers) {
29035                     for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
29036                         var helper = helpers_4[_i];
29037                         if (!helper.scoped) {
29038                             create = true;
29039                             break;
29040                         }
29041                     }
29042                 }
29043             }
29044             if (create) {
29045                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
29046                 var emitNode = ts.getOrCreateEmitNode(parseNode);
29047                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
29048             }
29049         }
29050     }
29051     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
29052     /**
29053      * Get the name of that target module from an import or export declaration
29054      */
29055     function getLocalNameForExternalImport(factory, node, sourceFile) {
29056         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
29057         if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
29058             var name = namespaceDeclaration.name;
29059             return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
29060         }
29061         if (node.kind === 265 /* ImportDeclaration */ && node.importClause) {
29062             return factory.getGeneratedNameForNode(node);
29063         }
29064         if (node.kind === 271 /* ExportDeclaration */ && node.moduleSpecifier) {
29065             return factory.getGeneratedNameForNode(node);
29066         }
29067         return undefined;
29068     }
29069     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
29070     /**
29071      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
29072      * The emitted output name can be different from the input if:
29073      *  1. The module has a /// <amd-module name="<new name>" />
29074      *  2. --out or --outFile is used, making the name relative to the rootDir
29075      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
29076      * Otherwise, a new StringLiteral node representing the module name will be returned.
29077      */
29078     function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
29079         var moduleName = ts.getExternalModuleName(importNode);
29080         if (moduleName && ts.isStringLiteral(moduleName)) {
29081             return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
29082                 || tryRenameExternalModule(factory, moduleName, sourceFile)
29083                 || factory.cloneNode(moduleName);
29084         }
29085         return undefined;
29086     }
29087     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
29088     /**
29089      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
29090      * Here we check if alternative name was provided for a given moduleName and return it if possible.
29091      */
29092     function tryRenameExternalModule(factory, moduleName, sourceFile) {
29093         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
29094         return rename ? factory.createStringLiteral(rename) : undefined;
29095     }
29096     /**
29097      * Get the name of a module as should be written in the emitted output.
29098      * The emitted output name can be different from the input if:
29099      *  1. The module has a /// <amd-module name="<new name>" />
29100      *  2. --out or --outFile is used, making the name relative to the rootDir
29101      * Otherwise, a new StringLiteral node representing the module name will be returned.
29102      */
29103     function tryGetModuleNameFromFile(factory, file, host, options) {
29104         if (!file) {
29105             return undefined;
29106         }
29107         if (file.moduleName) {
29108             return factory.createStringLiteral(file.moduleName);
29109         }
29110         if (!file.isDeclarationFile && ts.outFile(options)) {
29111             return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
29112         }
29113         return undefined;
29114     }
29115     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
29116     function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
29117         return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
29118     }
29119     /**
29120      * Gets the initializer of an BindingOrAssignmentElement.
29121      */
29122     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
29123         if (ts.isDeclarationBindingElement(bindingElement)) {
29124             // `1` in `let { a = 1 } = ...`
29125             // `1` in `let { a: b = 1 } = ...`
29126             // `1` in `let { a: {b} = 1 } = ...`
29127             // `1` in `let { a: [b] = 1 } = ...`
29128             // `1` in `let [a = 1] = ...`
29129             // `1` in `let [{a} = 1] = ...`
29130             // `1` in `let [[a] = 1] = ...`
29131             return bindingElement.initializer;
29132         }
29133         if (ts.isPropertyAssignment(bindingElement)) {
29134             // `1` in `({ a: b = 1 } = ...)`
29135             // `1` in `({ a: {b} = 1 } = ...)`
29136             // `1` in `({ a: [b] = 1 } = ...)`
29137             var initializer = bindingElement.initializer;
29138             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
29139                 ? initializer.right
29140                 : undefined;
29141         }
29142         if (ts.isShorthandPropertyAssignment(bindingElement)) {
29143             // `1` in `({ a = 1 } = ...)`
29144             return bindingElement.objectAssignmentInitializer;
29145         }
29146         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
29147             // `1` in `[a = 1] = ...`
29148             // `1` in `[{a} = 1] = ...`
29149             // `1` in `[[a] = 1] = ...`
29150             return bindingElement.right;
29151         }
29152         if (ts.isSpreadElement(bindingElement)) {
29153             // Recovery consistent with existing emit.
29154             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
29155         }
29156     }
29157     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
29158     /**
29159      * Gets the name of an BindingOrAssignmentElement.
29160      */
29161     function getTargetOfBindingOrAssignmentElement(bindingElement) {
29162         if (ts.isDeclarationBindingElement(bindingElement)) {
29163             // `a` in `let { a } = ...`
29164             // `a` in `let { a = 1 } = ...`
29165             // `b` in `let { a: b } = ...`
29166             // `b` in `let { a: b = 1 } = ...`
29167             // `a` in `let { ...a } = ...`
29168             // `{b}` in `let { a: {b} } = ...`
29169             // `{b}` in `let { a: {b} = 1 } = ...`
29170             // `[b]` in `let { a: [b] } = ...`
29171             // `[b]` in `let { a: [b] = 1 } = ...`
29172             // `a` in `let [a] = ...`
29173             // `a` in `let [a = 1] = ...`
29174             // `a` in `let [...a] = ...`
29175             // `{a}` in `let [{a}] = ...`
29176             // `{a}` in `let [{a} = 1] = ...`
29177             // `[a]` in `let [[a]] = ...`
29178             // `[a]` in `let [[a] = 1] = ...`
29179             return bindingElement.name;
29180         }
29181         if (ts.isObjectLiteralElementLike(bindingElement)) {
29182             switch (bindingElement.kind) {
29183                 case 294 /* PropertyAssignment */:
29184                     // `b` in `({ a: b } = ...)`
29185                     // `b` in `({ a: b = 1 } = ...)`
29186                     // `{b}` in `({ a: {b} } = ...)`
29187                     // `{b}` in `({ a: {b} = 1 } = ...)`
29188                     // `[b]` in `({ a: [b] } = ...)`
29189                     // `[b]` in `({ a: [b] = 1 } = ...)`
29190                     // `b.c` in `({ a: b.c } = ...)`
29191                     // `b.c` in `({ a: b.c = 1 } = ...)`
29192                     // `b[0]` in `({ a: b[0] } = ...)`
29193                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
29194                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
29195                 case 295 /* ShorthandPropertyAssignment */:
29196                     // `a` in `({ a } = ...)`
29197                     // `a` in `({ a = 1 } = ...)`
29198                     return bindingElement.name;
29199                 case 296 /* SpreadAssignment */:
29200                     // `a` in `({ ...a } = ...)`
29201                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
29202             }
29203             // no target
29204             return undefined;
29205         }
29206         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
29207             // `a` in `[a = 1] = ...`
29208             // `{a}` in `[{a} = 1] = ...`
29209             // `[a]` in `[[a] = 1] = ...`
29210             // `a.b` in `[a.b = 1] = ...`
29211             // `a[0]` in `[a[0] = 1] = ...`
29212             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
29213         }
29214         if (ts.isSpreadElement(bindingElement)) {
29215             // `a` in `[...a] = ...`
29216             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
29217         }
29218         // `a` in `[a] = ...`
29219         // `{a}` in `[{a}] = ...`
29220         // `[a]` in `[[a]] = ...`
29221         // `a.b` in `[a.b] = ...`
29222         // `a[0]` in `[a[0]] = ...`
29223         return bindingElement;
29224     }
29225     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
29226     /**
29227      * Determines whether an BindingOrAssignmentElement is a rest element.
29228      */
29229     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
29230         switch (bindingElement.kind) {
29231             case 163 /* Parameter */:
29232             case 202 /* BindingElement */:
29233                 // `...` in `let [...a] = ...`
29234                 return bindingElement.dotDotDotToken;
29235             case 224 /* SpreadElement */:
29236             case 296 /* SpreadAssignment */:
29237                 // `...` in `[...a] = ...`
29238                 return bindingElement;
29239         }
29240         return undefined;
29241     }
29242     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
29243     /**
29244      * Gets the property name of a BindingOrAssignmentElement
29245      */
29246     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
29247         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
29248         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
29249         return propertyName;
29250     }
29251     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
29252     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
29253         switch (bindingElement.kind) {
29254             case 202 /* BindingElement */:
29255                 // `a` in `let { a: b } = ...`
29256                 // `[a]` in `let { [a]: b } = ...`
29257                 // `"a"` in `let { "a": b } = ...`
29258                 // `1` in `let { 1: b } = ...`
29259                 if (bindingElement.propertyName) {
29260                     var propertyName = bindingElement.propertyName;
29261                     if (ts.isPrivateIdentifier(propertyName)) {
29262                         return ts.Debug.failBadSyntaxKind(propertyName);
29263                     }
29264                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
29265                         ? propertyName.expression
29266                         : propertyName;
29267                 }
29268                 break;
29269             case 294 /* PropertyAssignment */:
29270                 // `a` in `({ a: b } = ...)`
29271                 // `[a]` in `({ [a]: b } = ...)`
29272                 // `"a"` in `({ "a": b } = ...)`
29273                 // `1` in `({ 1: b } = ...)`
29274                 if (bindingElement.name) {
29275                     var propertyName = bindingElement.name;
29276                     if (ts.isPrivateIdentifier(propertyName)) {
29277                         return ts.Debug.failBadSyntaxKind(propertyName);
29278                     }
29279                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
29280                         ? propertyName.expression
29281                         : propertyName;
29282                 }
29283                 break;
29284             case 296 /* SpreadAssignment */:
29285                 // `a` in `({ ...a } = ...)`
29286                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
29287                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
29288                 }
29289                 return bindingElement.name;
29290         }
29291         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
29292         if (target && ts.isPropertyName(target)) {
29293             return target;
29294         }
29295     }
29296     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
29297     function isStringOrNumericLiteral(node) {
29298         var kind = node.kind;
29299         return kind === 10 /* StringLiteral */
29300             || kind === 8 /* NumericLiteral */;
29301     }
29302     /**
29303      * Gets the elements of a BindingOrAssignmentPattern
29304      */
29305     function getElementsOfBindingOrAssignmentPattern(name) {
29306         switch (name.kind) {
29307             case 200 /* ObjectBindingPattern */:
29308             case 201 /* ArrayBindingPattern */:
29309             case 203 /* ArrayLiteralExpression */:
29310                 // `a` in `{a}`
29311                 // `a` in `[a]`
29312                 return name.elements;
29313             case 204 /* ObjectLiteralExpression */:
29314                 // `a` in `{a}`
29315                 return name.properties;
29316         }
29317     }
29318     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
29319     /* @internal */
29320     function getJSDocTypeAliasName(fullName) {
29321         if (fullName) {
29322             var rightNode = fullName;
29323             while (true) {
29324                 if (ts.isIdentifier(rightNode) || !rightNode.body) {
29325                     return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
29326                 }
29327                 rightNode = rightNode.body;
29328             }
29329         }
29330     }
29331     ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
29332     function canHaveModifiers(node) {
29333         var kind = node.kind;
29334         return kind === 163 /* Parameter */
29335             || kind === 165 /* PropertySignature */
29336             || kind === 166 /* PropertyDeclaration */
29337             || kind === 167 /* MethodSignature */
29338             || kind === 168 /* MethodDeclaration */
29339             || kind === 170 /* Constructor */
29340             || kind === 171 /* GetAccessor */
29341             || kind === 172 /* SetAccessor */
29342             || kind === 175 /* IndexSignature */
29343             || kind === 212 /* FunctionExpression */
29344             || kind === 213 /* ArrowFunction */
29345             || kind === 225 /* ClassExpression */
29346             || kind === 236 /* VariableStatement */
29347             || kind === 255 /* FunctionDeclaration */
29348             || kind === 256 /* ClassDeclaration */
29349             || kind === 257 /* InterfaceDeclaration */
29350             || kind === 258 /* TypeAliasDeclaration */
29351             || kind === 259 /* EnumDeclaration */
29352             || kind === 260 /* ModuleDeclaration */
29353             || kind === 264 /* ImportEqualsDeclaration */
29354             || kind === 265 /* ImportDeclaration */
29355             || kind === 270 /* ExportAssignment */
29356             || kind === 271 /* ExportDeclaration */;
29357     }
29358     ts.canHaveModifiers = canHaveModifiers;
29359     ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
29360     ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken);
29361     ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode);
29362     ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken);
29363     ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken);
29364     ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral);
29365     function isLiteralTypeLikeExpression(node) {
29366         var kind = node.kind;
29367         return kind === 104 /* NullKeyword */
29368             || kind === 110 /* TrueKeyword */
29369             || kind === 95 /* FalseKeyword */
29370             || ts.isLiteralExpression(node)
29371             || ts.isPrefixUnaryExpression(node);
29372     }
29373     ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression;
29374     function isExponentiationOperator(kind) {
29375         return kind === 42 /* AsteriskAsteriskToken */;
29376     }
29377     function isMultiplicativeOperator(kind) {
29378         return kind === 41 /* AsteriskToken */
29379             || kind === 43 /* SlashToken */
29380             || kind === 44 /* PercentToken */;
29381     }
29382     function isMultiplicativeOperatorOrHigher(kind) {
29383         return isExponentiationOperator(kind)
29384             || isMultiplicativeOperator(kind);
29385     }
29386     function isAdditiveOperator(kind) {
29387         return kind === 39 /* PlusToken */
29388             || kind === 40 /* MinusToken */;
29389     }
29390     function isAdditiveOperatorOrHigher(kind) {
29391         return isAdditiveOperator(kind)
29392             || isMultiplicativeOperatorOrHigher(kind);
29393     }
29394     function isShiftOperator(kind) {
29395         return kind === 47 /* LessThanLessThanToken */
29396             || kind === 48 /* GreaterThanGreaterThanToken */
29397             || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */;
29398     }
29399     function isShiftOperatorOrHigher(kind) {
29400         return isShiftOperator(kind)
29401             || isAdditiveOperatorOrHigher(kind);
29402     }
29403     function isRelationalOperator(kind) {
29404         return kind === 29 /* LessThanToken */
29405             || kind === 32 /* LessThanEqualsToken */
29406             || kind === 31 /* GreaterThanToken */
29407             || kind === 33 /* GreaterThanEqualsToken */
29408             || kind === 102 /* InstanceOfKeyword */
29409             || kind === 101 /* InKeyword */;
29410     }
29411     function isRelationalOperatorOrHigher(kind) {
29412         return isRelationalOperator(kind)
29413             || isShiftOperatorOrHigher(kind);
29414     }
29415     function isEqualityOperator(kind) {
29416         return kind === 34 /* EqualsEqualsToken */
29417             || kind === 36 /* EqualsEqualsEqualsToken */
29418             || kind === 35 /* ExclamationEqualsToken */
29419             || kind === 37 /* ExclamationEqualsEqualsToken */;
29420     }
29421     function isEqualityOperatorOrHigher(kind) {
29422         return isEqualityOperator(kind)
29423             || isRelationalOperatorOrHigher(kind);
29424     }
29425     function isBitwiseOperator(kind) {
29426         return kind === 50 /* AmpersandToken */
29427             || kind === 51 /* BarToken */
29428             || kind === 52 /* CaretToken */;
29429     }
29430     function isBitwiseOperatorOrHigher(kind) {
29431         return isBitwiseOperator(kind)
29432             || isEqualityOperatorOrHigher(kind);
29433     }
29434     // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator.
29435     function isLogicalOperator(kind) {
29436         return kind === 55 /* AmpersandAmpersandToken */
29437             || kind === 56 /* BarBarToken */;
29438     }
29439     function isLogicalOperatorOrHigher(kind) {
29440         return isLogicalOperator(kind)
29441             || isBitwiseOperatorOrHigher(kind);
29442     }
29443     function isAssignmentOperatorOrHigher(kind) {
29444         return kind === 60 /* QuestionQuestionToken */
29445             || isLogicalOperatorOrHigher(kind)
29446             || ts.isAssignmentOperator(kind);
29447     }
29448     function isBinaryOperator(kind) {
29449         return isAssignmentOperatorOrHigher(kind)
29450             || kind === 27 /* CommaToken */;
29451     }
29452     function isBinaryOperatorToken(node) {
29453         return isBinaryOperator(node.kind);
29454     }
29455     ts.isBinaryOperatorToken = isBinaryOperatorToken;
29456     var BinaryExpressionState;
29457     (function (BinaryExpressionState) {
29458         /**
29459          * Handles walking into a `BinaryExpression`.
29460          * @param machine State machine handler functions
29461          * @param frame The current frame
29462          * @returns The new frame
29463          */
29464         function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) {
29465             var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined;
29466             ts.Debug.assertEqual(stateStack[stackIndex], enter);
29467             userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState);
29468             stateStack[stackIndex] = nextState(machine, enter);
29469             return stackIndex;
29470         }
29471         BinaryExpressionState.enter = enter;
29472         /**
29473          * Handles walking the `left` side of a `BinaryExpression`.
29474          * @param machine State machine handler functions
29475          * @param frame The current frame
29476          * @returns The new frame
29477          */
29478         function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
29479             ts.Debug.assertEqual(stateStack[stackIndex], left);
29480             ts.Debug.assertIsDefined(machine.onLeft);
29481             stateStack[stackIndex] = nextState(machine, left);
29482             var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]);
29483             if (nextNode) {
29484                 checkCircularity(stackIndex, nodeStack, nextNode);
29485                 return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
29486             }
29487             return stackIndex;
29488         }
29489         BinaryExpressionState.left = left;
29490         /**
29491          * Handles walking the `operatorToken` of a `BinaryExpression`.
29492          * @param machine State machine handler functions
29493          * @param frame The current frame
29494          * @returns The new frame
29495          */
29496         function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
29497             ts.Debug.assertEqual(stateStack[stackIndex], operator);
29498             ts.Debug.assertIsDefined(machine.onOperator);
29499             stateStack[stackIndex] = nextState(machine, operator);
29500             machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]);
29501             return stackIndex;
29502         }
29503         BinaryExpressionState.operator = operator;
29504         /**
29505          * Handles walking the `right` side of a `BinaryExpression`.
29506          * @param machine State machine handler functions
29507          * @param frame The current frame
29508          * @returns The new frame
29509          */
29510         function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) {
29511             ts.Debug.assertEqual(stateStack[stackIndex], right);
29512             ts.Debug.assertIsDefined(machine.onRight);
29513             stateStack[stackIndex] = nextState(machine, right);
29514             var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]);
29515             if (nextNode) {
29516                 checkCircularity(stackIndex, nodeStack, nextNode);
29517                 return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode);
29518             }
29519             return stackIndex;
29520         }
29521         BinaryExpressionState.right = right;
29522         /**
29523          * Handles walking out of a `BinaryExpression`.
29524          * @param machine State machine handler functions
29525          * @param frame The current frame
29526          * @returns The new frame
29527          */
29528         function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) {
29529             ts.Debug.assertEqual(stateStack[stackIndex], exit);
29530             stateStack[stackIndex] = nextState(machine, exit);
29531             var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]);
29532             if (stackIndex > 0) {
29533                 stackIndex--;
29534                 if (machine.foldState) {
29535                     var side = stateStack[stackIndex] === exit ? "right" : "left";
29536                     userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side);
29537                 }
29538             }
29539             else {
29540                 resultHolder.value = result;
29541             }
29542             return stackIndex;
29543         }
29544         BinaryExpressionState.exit = exit;
29545         /**
29546          * Handles a frame that is already done.
29547          * @returns The `done` state.
29548          */
29549         function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) {
29550             ts.Debug.assertEqual(stateStack[stackIndex], done);
29551             return stackIndex;
29552         }
29553         BinaryExpressionState.done = done;
29554         function nextState(machine, currentState) {
29555             switch (currentState) {
29556                 case enter:
29557                     if (machine.onLeft)
29558                         return left;
29559                 // falls through
29560                 case left:
29561                     if (machine.onOperator)
29562                         return operator;
29563                 // falls through
29564                 case operator:
29565                     if (machine.onRight)
29566                         return right;
29567                 // falls through
29568                 case right: return exit;
29569                 case exit: return done;
29570                 case done: return done;
29571                 default: ts.Debug.fail("Invalid state");
29572             }
29573         }
29574         BinaryExpressionState.nextState = nextState;
29575         function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) {
29576             stackIndex++;
29577             stateStack[stackIndex] = enter;
29578             nodeStack[stackIndex] = node;
29579             userStateStack[stackIndex] = undefined;
29580             return stackIndex;
29581         }
29582         function checkCircularity(stackIndex, nodeStack, node) {
29583             if (ts.Debug.shouldAssert(2 /* Aggressive */)) {
29584                 while (stackIndex >= 0) {
29585                     ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected.");
29586                     stackIndex--;
29587                 }
29588             }
29589         }
29590     })(BinaryExpressionState || (BinaryExpressionState = {}));
29591     /**
29592      * Holds state machine handler functions
29593      */
29594     var BinaryExpressionStateMachine = /** @class */ (function () {
29595         function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
29596             this.onEnter = onEnter;
29597             this.onLeft = onLeft;
29598             this.onOperator = onOperator;
29599             this.onRight = onRight;
29600             this.onExit = onExit;
29601             this.foldState = foldState;
29602         }
29603         return BinaryExpressionStateMachine;
29604     }());
29605     function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) {
29606         var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState);
29607         return trampoline;
29608         function trampoline(node, outerState) {
29609             var resultHolder = { value: undefined };
29610             var stateStack = [BinaryExpressionState.enter];
29611             var nodeStack = [node];
29612             var userStateStack = [undefined];
29613             var stackIndex = 0;
29614             while (stateStack[stackIndex] !== BinaryExpressionState.done) {
29615                 stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState);
29616             }
29617             ts.Debug.assertEqual(stackIndex, 0);
29618             return resultHolder.value;
29619         }
29620     }
29621     ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline;
29622 })(ts || (ts = {}));
29623 var ts;
29624 (function (ts) {
29625     function setTextRange(range, location) {
29626         return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
29627     }
29628     ts.setTextRange = setTextRange;
29629 })(ts || (ts = {}));
29630 var ts;
29631 (function (ts) {
29632     var SignatureFlags;
29633     (function (SignatureFlags) {
29634         SignatureFlags[SignatureFlags["None"] = 0] = "None";
29635         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
29636         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
29637         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
29638         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
29639         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
29640     })(SignatureFlags || (SignatureFlags = {}));
29641     var SpeculationKind;
29642     (function (SpeculationKind) {
29643         SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
29644         SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
29645         SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
29646     })(SpeculationKind || (SpeculationKind = {}));
29647     var NodeConstructor;
29648     var TokenConstructor;
29649     var IdentifierConstructor;
29650     var PrivateIdentifierConstructor;
29651     var SourceFileConstructor;
29652     /**
29653      * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`.
29654      */
29655     /* @internal */
29656     ts.parseBaseNodeFactory = {
29657         createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
29658         createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
29659         createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
29660         createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
29661         createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
29662     };
29663     /* @internal */
29664     ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
29665     function visitNode(cbNode, node) {
29666         return node && cbNode(node);
29667     }
29668     function visitNodes(cbNode, cbNodes, nodes) {
29669         if (nodes) {
29670             if (cbNodes) {
29671                 return cbNodes(nodes);
29672             }
29673             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
29674                 var node = nodes_1[_i];
29675                 var result = cbNode(node);
29676                 if (result) {
29677                     return result;
29678                 }
29679             }
29680         }
29681     }
29682     /*@internal*/
29683     function isJSDocLikeText(text, start) {
29684         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
29685             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
29686             text.charCodeAt(start + 3) !== 47 /* slash */;
29687     }
29688     ts.isJSDocLikeText = isJSDocLikeText;
29689     /**
29690      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
29691      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
29692      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
29693      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
29694      *
29695      * @param node a given node to visit its children
29696      * @param cbNode a callback to be invoked for all child nodes
29697      * @param cbNodes a callback to be invoked for embedded array
29698      *
29699      * @remarks `forEachChild` must visit the children of a node in the order
29700      * that they appear in the source code. The language service depends on this property to locate nodes by position.
29701      */
29702     function forEachChild(node, cbNode, cbNodes) {
29703         if (!node || node.kind <= 159 /* LastToken */) {
29704             return;
29705         }
29706         switch (node.kind) {
29707             case 160 /* QualifiedName */:
29708                 return visitNode(cbNode, node.left) ||
29709                     visitNode(cbNode, node.right);
29710             case 162 /* TypeParameter */:
29711                 return visitNode(cbNode, node.name) ||
29712                     visitNode(cbNode, node.constraint) ||
29713                     visitNode(cbNode, node.default) ||
29714                     visitNode(cbNode, node.expression);
29715             case 295 /* ShorthandPropertyAssignment */:
29716                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29717                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29718                     visitNode(cbNode, node.name) ||
29719                     visitNode(cbNode, node.questionToken) ||
29720                     visitNode(cbNode, node.exclamationToken) ||
29721                     visitNode(cbNode, node.equalsToken) ||
29722                     visitNode(cbNode, node.objectAssignmentInitializer);
29723             case 296 /* SpreadAssignment */:
29724                 return visitNode(cbNode, node.expression);
29725             case 163 /* Parameter */:
29726                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29727                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29728                     visitNode(cbNode, node.dotDotDotToken) ||
29729                     visitNode(cbNode, node.name) ||
29730                     visitNode(cbNode, node.questionToken) ||
29731                     visitNode(cbNode, node.type) ||
29732                     visitNode(cbNode, node.initializer);
29733             case 166 /* PropertyDeclaration */:
29734                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29735                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29736                     visitNode(cbNode, node.name) ||
29737                     visitNode(cbNode, node.questionToken) ||
29738                     visitNode(cbNode, node.exclamationToken) ||
29739                     visitNode(cbNode, node.type) ||
29740                     visitNode(cbNode, node.initializer);
29741             case 165 /* PropertySignature */:
29742                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29743                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29744                     visitNode(cbNode, node.name) ||
29745                     visitNode(cbNode, node.questionToken) ||
29746                     visitNode(cbNode, node.type) ||
29747                     visitNode(cbNode, node.initializer);
29748             case 294 /* PropertyAssignment */:
29749                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29750                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29751                     visitNode(cbNode, node.name) ||
29752                     visitNode(cbNode, node.questionToken) ||
29753                     visitNode(cbNode, node.initializer);
29754             case 253 /* VariableDeclaration */:
29755                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29756                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29757                     visitNode(cbNode, node.name) ||
29758                     visitNode(cbNode, node.exclamationToken) ||
29759                     visitNode(cbNode, node.type) ||
29760                     visitNode(cbNode, node.initializer);
29761             case 202 /* BindingElement */:
29762                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29763                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29764                     visitNode(cbNode, node.dotDotDotToken) ||
29765                     visitNode(cbNode, node.propertyName) ||
29766                     visitNode(cbNode, node.name) ||
29767                     visitNode(cbNode, node.initializer);
29768             case 178 /* FunctionType */:
29769             case 179 /* ConstructorType */:
29770             case 173 /* CallSignature */:
29771             case 174 /* ConstructSignature */:
29772             case 175 /* IndexSignature */:
29773                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29774                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29775                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
29776                     visitNodes(cbNode, cbNodes, node.parameters) ||
29777                     visitNode(cbNode, node.type);
29778             case 168 /* MethodDeclaration */:
29779             case 167 /* MethodSignature */:
29780             case 170 /* Constructor */:
29781             case 171 /* GetAccessor */:
29782             case 172 /* SetAccessor */:
29783             case 212 /* FunctionExpression */:
29784             case 255 /* FunctionDeclaration */:
29785             case 213 /* ArrowFunction */:
29786                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29787                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29788                     visitNode(cbNode, node.asteriskToken) ||
29789                     visitNode(cbNode, node.name) ||
29790                     visitNode(cbNode, node.questionToken) ||
29791                     visitNode(cbNode, node.exclamationToken) ||
29792                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
29793                     visitNodes(cbNode, cbNodes, node.parameters) ||
29794                     visitNode(cbNode, node.type) ||
29795                     visitNode(cbNode, node.equalsGreaterThanToken) ||
29796                     visitNode(cbNode, node.body);
29797             case 169 /* ClassStaticBlockDeclaration */:
29798                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29799                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29800                     visitNode(cbNode, node.body);
29801             case 177 /* TypeReference */:
29802                 return visitNode(cbNode, node.typeName) ||
29803                     visitNodes(cbNode, cbNodes, node.typeArguments);
29804             case 176 /* TypePredicate */:
29805                 return visitNode(cbNode, node.assertsModifier) ||
29806                     visitNode(cbNode, node.parameterName) ||
29807                     visitNode(cbNode, node.type);
29808             case 180 /* TypeQuery */:
29809                 return visitNode(cbNode, node.exprName);
29810             case 181 /* TypeLiteral */:
29811                 return visitNodes(cbNode, cbNodes, node.members);
29812             case 182 /* ArrayType */:
29813                 return visitNode(cbNode, node.elementType);
29814             case 183 /* TupleType */:
29815                 return visitNodes(cbNode, cbNodes, node.elements);
29816             case 186 /* UnionType */:
29817             case 187 /* IntersectionType */:
29818                 return visitNodes(cbNode, cbNodes, node.types);
29819             case 188 /* ConditionalType */:
29820                 return visitNode(cbNode, node.checkType) ||
29821                     visitNode(cbNode, node.extendsType) ||
29822                     visitNode(cbNode, node.trueType) ||
29823                     visitNode(cbNode, node.falseType);
29824             case 189 /* InferType */:
29825                 return visitNode(cbNode, node.typeParameter);
29826             case 199 /* ImportType */:
29827                 return visitNode(cbNode, node.argument) ||
29828                     visitNode(cbNode, node.qualifier) ||
29829                     visitNodes(cbNode, cbNodes, node.typeArguments);
29830             case 190 /* ParenthesizedType */:
29831             case 192 /* TypeOperator */:
29832                 return visitNode(cbNode, node.type);
29833             case 193 /* IndexedAccessType */:
29834                 return visitNode(cbNode, node.objectType) ||
29835                     visitNode(cbNode, node.indexType);
29836             case 194 /* MappedType */:
29837                 return visitNode(cbNode, node.readonlyToken) ||
29838                     visitNode(cbNode, node.typeParameter) ||
29839                     visitNode(cbNode, node.nameType) ||
29840                     visitNode(cbNode, node.questionToken) ||
29841                     visitNode(cbNode, node.type) ||
29842                     visitNodes(cbNode, cbNodes, node.members);
29843             case 195 /* LiteralType */:
29844                 return visitNode(cbNode, node.literal);
29845             case 196 /* NamedTupleMember */:
29846                 return visitNode(cbNode, node.dotDotDotToken) ||
29847                     visitNode(cbNode, node.name) ||
29848                     visitNode(cbNode, node.questionToken) ||
29849                     visitNode(cbNode, node.type);
29850             case 200 /* ObjectBindingPattern */:
29851             case 201 /* ArrayBindingPattern */:
29852                 return visitNodes(cbNode, cbNodes, node.elements);
29853             case 203 /* ArrayLiteralExpression */:
29854                 return visitNodes(cbNode, cbNodes, node.elements);
29855             case 204 /* ObjectLiteralExpression */:
29856                 return visitNodes(cbNode, cbNodes, node.properties);
29857             case 205 /* PropertyAccessExpression */:
29858                 return visitNode(cbNode, node.expression) ||
29859                     visitNode(cbNode, node.questionDotToken) ||
29860                     visitNode(cbNode, node.name);
29861             case 206 /* ElementAccessExpression */:
29862                 return visitNode(cbNode, node.expression) ||
29863                     visitNode(cbNode, node.questionDotToken) ||
29864                     visitNode(cbNode, node.argumentExpression);
29865             case 207 /* CallExpression */:
29866             case 208 /* NewExpression */:
29867                 return visitNode(cbNode, node.expression) ||
29868                     visitNode(cbNode, node.questionDotToken) ||
29869                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
29870                     visitNodes(cbNode, cbNodes, node.arguments);
29871             case 209 /* TaggedTemplateExpression */:
29872                 return visitNode(cbNode, node.tag) ||
29873                     visitNode(cbNode, node.questionDotToken) ||
29874                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
29875                     visitNode(cbNode, node.template);
29876             case 210 /* TypeAssertionExpression */:
29877                 return visitNode(cbNode, node.type) ||
29878                     visitNode(cbNode, node.expression);
29879             case 211 /* ParenthesizedExpression */:
29880                 return visitNode(cbNode, node.expression);
29881             case 214 /* DeleteExpression */:
29882                 return visitNode(cbNode, node.expression);
29883             case 215 /* TypeOfExpression */:
29884                 return visitNode(cbNode, node.expression);
29885             case 216 /* VoidExpression */:
29886                 return visitNode(cbNode, node.expression);
29887             case 218 /* PrefixUnaryExpression */:
29888                 return visitNode(cbNode, node.operand);
29889             case 223 /* YieldExpression */:
29890                 return visitNode(cbNode, node.asteriskToken) ||
29891                     visitNode(cbNode, node.expression);
29892             case 217 /* AwaitExpression */:
29893                 return visitNode(cbNode, node.expression);
29894             case 219 /* PostfixUnaryExpression */:
29895                 return visitNode(cbNode, node.operand);
29896             case 220 /* BinaryExpression */:
29897                 return visitNode(cbNode, node.left) ||
29898                     visitNode(cbNode, node.operatorToken) ||
29899                     visitNode(cbNode, node.right);
29900             case 228 /* AsExpression */:
29901                 return visitNode(cbNode, node.expression) ||
29902                     visitNode(cbNode, node.type);
29903             case 229 /* NonNullExpression */:
29904                 return visitNode(cbNode, node.expression);
29905             case 230 /* MetaProperty */:
29906                 return visitNode(cbNode, node.name);
29907             case 221 /* ConditionalExpression */:
29908                 return visitNode(cbNode, node.condition) ||
29909                     visitNode(cbNode, node.questionToken) ||
29910                     visitNode(cbNode, node.whenTrue) ||
29911                     visitNode(cbNode, node.colonToken) ||
29912                     visitNode(cbNode, node.whenFalse);
29913             case 224 /* SpreadElement */:
29914                 return visitNode(cbNode, node.expression);
29915             case 234 /* Block */:
29916             case 261 /* ModuleBlock */:
29917                 return visitNodes(cbNode, cbNodes, node.statements);
29918             case 303 /* SourceFile */:
29919                 return visitNodes(cbNode, cbNodes, node.statements) ||
29920                     visitNode(cbNode, node.endOfFileToken);
29921             case 236 /* VariableStatement */:
29922                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29923                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29924                     visitNode(cbNode, node.declarationList);
29925             case 254 /* VariableDeclarationList */:
29926                 return visitNodes(cbNode, cbNodes, node.declarations);
29927             case 237 /* ExpressionStatement */:
29928                 return visitNode(cbNode, node.expression);
29929             case 238 /* IfStatement */:
29930                 return visitNode(cbNode, node.expression) ||
29931                     visitNode(cbNode, node.thenStatement) ||
29932                     visitNode(cbNode, node.elseStatement);
29933             case 239 /* DoStatement */:
29934                 return visitNode(cbNode, node.statement) ||
29935                     visitNode(cbNode, node.expression);
29936             case 240 /* WhileStatement */:
29937                 return visitNode(cbNode, node.expression) ||
29938                     visitNode(cbNode, node.statement);
29939             case 241 /* ForStatement */:
29940                 return visitNode(cbNode, node.initializer) ||
29941                     visitNode(cbNode, node.condition) ||
29942                     visitNode(cbNode, node.incrementor) ||
29943                     visitNode(cbNode, node.statement);
29944             case 242 /* ForInStatement */:
29945                 return visitNode(cbNode, node.initializer) ||
29946                     visitNode(cbNode, node.expression) ||
29947                     visitNode(cbNode, node.statement);
29948             case 243 /* ForOfStatement */:
29949                 return visitNode(cbNode, node.awaitModifier) ||
29950                     visitNode(cbNode, node.initializer) ||
29951                     visitNode(cbNode, node.expression) ||
29952                     visitNode(cbNode, node.statement);
29953             case 244 /* ContinueStatement */:
29954             case 245 /* BreakStatement */:
29955                 return visitNode(cbNode, node.label);
29956             case 246 /* ReturnStatement */:
29957                 return visitNode(cbNode, node.expression);
29958             case 247 /* WithStatement */:
29959                 return visitNode(cbNode, node.expression) ||
29960                     visitNode(cbNode, node.statement);
29961             case 248 /* SwitchStatement */:
29962                 return visitNode(cbNode, node.expression) ||
29963                     visitNode(cbNode, node.caseBlock);
29964             case 262 /* CaseBlock */:
29965                 return visitNodes(cbNode, cbNodes, node.clauses);
29966             case 288 /* CaseClause */:
29967                 return visitNode(cbNode, node.expression) ||
29968                     visitNodes(cbNode, cbNodes, node.statements);
29969             case 289 /* DefaultClause */:
29970                 return visitNodes(cbNode, cbNodes, node.statements);
29971             case 249 /* LabeledStatement */:
29972                 return visitNode(cbNode, node.label) ||
29973                     visitNode(cbNode, node.statement);
29974             case 250 /* ThrowStatement */:
29975                 return visitNode(cbNode, node.expression);
29976             case 251 /* TryStatement */:
29977                 return visitNode(cbNode, node.tryBlock) ||
29978                     visitNode(cbNode, node.catchClause) ||
29979                     visitNode(cbNode, node.finallyBlock);
29980             case 291 /* CatchClause */:
29981                 return visitNode(cbNode, node.variableDeclaration) ||
29982                     visitNode(cbNode, node.block);
29983             case 164 /* Decorator */:
29984                 return visitNode(cbNode, node.expression);
29985             case 256 /* ClassDeclaration */:
29986             case 225 /* ClassExpression */:
29987                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29988                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29989                     visitNode(cbNode, node.name) ||
29990                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
29991                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
29992                     visitNodes(cbNode, cbNodes, node.members);
29993             case 257 /* InterfaceDeclaration */:
29994                 return visitNodes(cbNode, cbNodes, node.decorators) ||
29995                     visitNodes(cbNode, cbNodes, node.modifiers) ||
29996                     visitNode(cbNode, node.name) ||
29997                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
29998                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
29999                     visitNodes(cbNode, cbNodes, node.members);
30000             case 258 /* TypeAliasDeclaration */:
30001                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30002                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30003                     visitNode(cbNode, node.name) ||
30004                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
30005                     visitNode(cbNode, node.type);
30006             case 259 /* EnumDeclaration */:
30007                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30008                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30009                     visitNode(cbNode, node.name) ||
30010                     visitNodes(cbNode, cbNodes, node.members);
30011             case 297 /* EnumMember */:
30012                 return visitNode(cbNode, node.name) ||
30013                     visitNode(cbNode, node.initializer);
30014             case 260 /* ModuleDeclaration */:
30015                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30016                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30017                     visitNode(cbNode, node.name) ||
30018                     visitNode(cbNode, node.body);
30019             case 264 /* ImportEqualsDeclaration */:
30020                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30021                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30022                     visitNode(cbNode, node.name) ||
30023                     visitNode(cbNode, node.moduleReference);
30024             case 265 /* ImportDeclaration */:
30025                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30026                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30027                     visitNode(cbNode, node.importClause) ||
30028                     visitNode(cbNode, node.moduleSpecifier) ||
30029                     visitNode(cbNode, node.assertClause);
30030             case 266 /* ImportClause */:
30031                 return visitNode(cbNode, node.name) ||
30032                     visitNode(cbNode, node.namedBindings);
30033             case 292 /* AssertClause */:
30034                 return visitNodes(cbNode, cbNodes, node.elements);
30035             case 293 /* AssertEntry */:
30036                 return visitNode(cbNode, node.name) ||
30037                     visitNode(cbNode, node.value);
30038             case 263 /* NamespaceExportDeclaration */:
30039                 return visitNode(cbNode, node.name);
30040             case 267 /* NamespaceImport */:
30041                 return visitNode(cbNode, node.name);
30042             case 273 /* NamespaceExport */:
30043                 return visitNode(cbNode, node.name);
30044             case 268 /* NamedImports */:
30045             case 272 /* NamedExports */:
30046                 return visitNodes(cbNode, cbNodes, node.elements);
30047             case 271 /* ExportDeclaration */:
30048                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30049                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30050                     visitNode(cbNode, node.exportClause) ||
30051                     visitNode(cbNode, node.moduleSpecifier) ||
30052                     visitNode(cbNode, node.assertClause);
30053             case 269 /* ImportSpecifier */:
30054             case 274 /* ExportSpecifier */:
30055                 return visitNode(cbNode, node.propertyName) ||
30056                     visitNode(cbNode, node.name);
30057             case 270 /* ExportAssignment */:
30058                 return visitNodes(cbNode, cbNodes, node.decorators) ||
30059                     visitNodes(cbNode, cbNodes, node.modifiers) ||
30060                     visitNode(cbNode, node.expression);
30061             case 222 /* TemplateExpression */:
30062                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
30063             case 232 /* TemplateSpan */:
30064                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
30065             case 197 /* TemplateLiteralType */:
30066                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
30067             case 198 /* TemplateLiteralTypeSpan */:
30068                 return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal);
30069             case 161 /* ComputedPropertyName */:
30070                 return visitNode(cbNode, node.expression);
30071             case 290 /* HeritageClause */:
30072                 return visitNodes(cbNode, cbNodes, node.types);
30073             case 227 /* ExpressionWithTypeArguments */:
30074                 return visitNode(cbNode, node.expression) ||
30075                     visitNodes(cbNode, cbNodes, node.typeArguments);
30076             case 276 /* ExternalModuleReference */:
30077                 return visitNode(cbNode, node.expression);
30078             case 275 /* MissingDeclaration */:
30079                 return visitNodes(cbNode, cbNodes, node.decorators);
30080             case 349 /* CommaListExpression */:
30081                 return visitNodes(cbNode, cbNodes, node.elements);
30082             case 277 /* JsxElement */:
30083                 return visitNode(cbNode, node.openingElement) ||
30084                     visitNodes(cbNode, cbNodes, node.children) ||
30085                     visitNode(cbNode, node.closingElement);
30086             case 281 /* JsxFragment */:
30087                 return visitNode(cbNode, node.openingFragment) ||
30088                     visitNodes(cbNode, cbNodes, node.children) ||
30089                     visitNode(cbNode, node.closingFragment);
30090             case 278 /* JsxSelfClosingElement */:
30091             case 279 /* JsxOpeningElement */:
30092                 return visitNode(cbNode, node.tagName) ||
30093                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
30094                     visitNode(cbNode, node.attributes);
30095             case 285 /* JsxAttributes */:
30096                 return visitNodes(cbNode, cbNodes, node.properties);
30097             case 284 /* JsxAttribute */:
30098                 return visitNode(cbNode, node.name) ||
30099                     visitNode(cbNode, node.initializer);
30100             case 286 /* JsxSpreadAttribute */:
30101                 return visitNode(cbNode, node.expression);
30102             case 287 /* JsxExpression */:
30103                 return visitNode(cbNode, node.dotDotDotToken) ||
30104                     visitNode(cbNode, node.expression);
30105             case 280 /* JsxClosingElement */:
30106                 return visitNode(cbNode, node.tagName);
30107             case 184 /* OptionalType */:
30108             case 185 /* RestType */:
30109             case 307 /* JSDocTypeExpression */:
30110             case 313 /* JSDocNonNullableType */:
30111             case 312 /* JSDocNullableType */:
30112             case 314 /* JSDocOptionalType */:
30113             case 316 /* JSDocVariadicType */:
30114                 return visitNode(cbNode, node.type);
30115             case 315 /* JSDocFunctionType */:
30116                 return visitNodes(cbNode, cbNodes, node.parameters) ||
30117                     visitNode(cbNode, node.type);
30118             case 318 /* JSDocComment */:
30119                 return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
30120                     || visitNodes(cbNode, cbNodes, node.tags);
30121             case 344 /* JSDocSeeTag */:
30122                 return visitNode(cbNode, node.tagName) ||
30123                     visitNode(cbNode, node.name) ||
30124                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30125             case 308 /* JSDocNameReference */:
30126                 return visitNode(cbNode, node.name);
30127             case 309 /* JSDocMemberName */:
30128                 return visitNode(cbNode, node.left) ||
30129                     visitNode(cbNode, node.right);
30130             case 338 /* JSDocParameterTag */:
30131             case 345 /* JSDocPropertyTag */:
30132                 return visitNode(cbNode, node.tagName) ||
30133                     (node.isNameFirst
30134                         ? visitNode(cbNode, node.name) ||
30135                             visitNode(cbNode, node.typeExpression) ||
30136                             (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
30137                         : visitNode(cbNode, node.typeExpression) ||
30138                             visitNode(cbNode, node.name) ||
30139                             (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)));
30140             case 328 /* JSDocAuthorTag */:
30141                 return visitNode(cbNode, node.tagName) ||
30142                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30143             case 327 /* JSDocImplementsTag */:
30144                 return visitNode(cbNode, node.tagName) ||
30145                     visitNode(cbNode, node.class) ||
30146                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30147             case 326 /* JSDocAugmentsTag */:
30148                 return visitNode(cbNode, node.tagName) ||
30149                     visitNode(cbNode, node.class) ||
30150                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30151             case 342 /* JSDocTemplateTag */:
30152                 return visitNode(cbNode, node.tagName) ||
30153                     visitNode(cbNode, node.constraint) ||
30154                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
30155                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30156             case 343 /* JSDocTypedefTag */:
30157                 return visitNode(cbNode, node.tagName) ||
30158                     (node.typeExpression &&
30159                         node.typeExpression.kind === 307 /* JSDocTypeExpression */
30160                         ? visitNode(cbNode, node.typeExpression) ||
30161                             visitNode(cbNode, node.fullName) ||
30162                             (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))
30163                         : visitNode(cbNode, node.fullName) ||
30164                             visitNode(cbNode, node.typeExpression) ||
30165                             (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)));
30166             case 336 /* JSDocCallbackTag */:
30167                 return visitNode(cbNode, node.tagName) ||
30168                     visitNode(cbNode, node.fullName) ||
30169                     visitNode(cbNode, node.typeExpression) ||
30170                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30171             case 339 /* JSDocReturnTag */:
30172             case 341 /* JSDocTypeTag */:
30173             case 340 /* JSDocThisTag */:
30174             case 337 /* JSDocEnumTag */:
30175                 return visitNode(cbNode, node.tagName) ||
30176                     visitNode(cbNode, node.typeExpression) ||
30177                     (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30178             case 321 /* JSDocSignature */:
30179                 return ts.forEach(node.typeParameters, cbNode) ||
30180                     ts.forEach(node.parameters, cbNode) ||
30181                     visitNode(cbNode, node.type);
30182             case 322 /* JSDocLink */:
30183             case 323 /* JSDocLinkCode */:
30184             case 324 /* JSDocLinkPlain */:
30185                 return visitNode(cbNode, node.name);
30186             case 320 /* JSDocTypeLiteral */:
30187                 return ts.forEach(node.jsDocPropertyTags, cbNode);
30188             case 325 /* JSDocTag */:
30189             case 330 /* JSDocClassTag */:
30190             case 331 /* JSDocPublicTag */:
30191             case 332 /* JSDocPrivateTag */:
30192             case 333 /* JSDocProtectedTag */:
30193             case 334 /* JSDocReadonlyTag */:
30194             case 329 /* JSDocDeprecatedTag */:
30195                 return visitNode(cbNode, node.tagName)
30196                     || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
30197             case 348 /* PartiallyEmittedExpression */:
30198                 return visitNode(cbNode, node.expression);
30199         }
30200     }
30201     ts.forEachChild = forEachChild;
30202     /** @internal */
30203     /**
30204      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
30205      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
30206      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
30207      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
30208      *
30209      * @param node a given node to visit its children
30210      * @param cbNode a callback to be invoked for all child nodes
30211      * @param cbNodes a callback to be invoked for embedded array
30212      *
30213      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
30214      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
30215      */
30216     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
30217         var queue = gatherPossibleChildren(rootNode);
30218         var parents = []; // tracks parent references for elements in queue
30219         while (parents.length < queue.length) {
30220             parents.push(rootNode);
30221         }
30222         while (queue.length !== 0) {
30223             var current = queue.pop();
30224             var parent = parents.pop();
30225             if (ts.isArray(current)) {
30226                 if (cbNodes) {
30227                     var res = cbNodes(current, parent);
30228                     if (res) {
30229                         if (res === "skip")
30230                             continue;
30231                         return res;
30232                     }
30233                 }
30234                 for (var i = current.length - 1; i >= 0; --i) {
30235                     queue.push(current[i]);
30236                     parents.push(parent);
30237                 }
30238             }
30239             else {
30240                 var res = cbNode(current, parent);
30241                 if (res) {
30242                     if (res === "skip")
30243                         continue;
30244                     return res;
30245                 }
30246                 if (current.kind >= 160 /* FirstNode */) {
30247                     // add children in reverse order to the queue, so popping gives the first child
30248                     for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) {
30249                         var child = _a[_i];
30250                         queue.push(child);
30251                         parents.push(current);
30252                     }
30253                 }
30254             }
30255         }
30256     }
30257     ts.forEachChildRecursively = forEachChildRecursively;
30258     function gatherPossibleChildren(node) {
30259         var children = [];
30260         forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
30261         return children;
30262         function addWorkItem(n) {
30263             children.unshift(n);
30264         }
30265     }
30266     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
30267         if (setParentNodes === void 0) { setParentNodes = false; }
30268         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true);
30269         ts.performance.mark("beforeParse");
30270         var result;
30271         ts.perfLogger.logStartParseSourceFile(fileName);
30272         if (languageVersion === 100 /* JSON */) {
30273             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
30274         }
30275         else {
30276             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
30277         }
30278         ts.perfLogger.logStopParseSourceFile();
30279         ts.performance.mark("afterParse");
30280         ts.performance.measure("Parse", "beforeParse", "afterParse");
30281         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
30282         return result;
30283     }
30284     ts.createSourceFile = createSourceFile;
30285     function parseIsolatedEntityName(text, languageVersion) {
30286         return Parser.parseIsolatedEntityName(text, languageVersion);
30287     }
30288     ts.parseIsolatedEntityName = parseIsolatedEntityName;
30289     /**
30290      * Parse json text into SyntaxTree and return node and parse errors if any
30291      * @param fileName
30292      * @param sourceText
30293      */
30294     function parseJsonText(fileName, sourceText) {
30295         return Parser.parseJsonText(fileName, sourceText);
30296     }
30297     ts.parseJsonText = parseJsonText;
30298     // See also `isExternalOrCommonJsModule` in utilities.ts
30299     function isExternalModule(file) {
30300         return file.externalModuleIndicator !== undefined;
30301     }
30302     ts.isExternalModule = isExternalModule;
30303     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
30304     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
30305     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
30306     // this file as possible.
30307     //
30308     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
30309     // from this SourceFile that are being held onto may change as a result (including
30310     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
30311     // be used once 'update' is called on it.
30312     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
30313         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
30314         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
30315         // 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.
30316         // We will manually port the flag to the new source file.
30317         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
30318         return newSourceFile;
30319     }
30320     ts.updateSourceFile = updateSourceFile;
30321     /* @internal */
30322     function parseIsolatedJSDocComment(content, start, length) {
30323         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
30324         if (result && result.jsDoc) {
30325             // because the jsDocComment was parsed out of the source file, it might
30326             // not be covered by the fixupParentReferences.
30327             Parser.fixupParentReferences(result.jsDoc);
30328         }
30329         return result;
30330     }
30331     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
30332     /* @internal */
30333     // Exposed only for testing.
30334     function parseJSDocTypeExpressionForTests(content, start, length) {
30335         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
30336     }
30337     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
30338     // Implement the parser as a singleton module.  We do this for perf reasons because creating
30339     // parser instances can actually be expensive enough to impact us on projects with many source
30340     // files.
30341     var Parser;
30342     (function (Parser) {
30343         // Share a single scanner across all calls to parse a source file.  This helps speed things
30344         // up by avoiding the cost of creating/compiling scanners over and over again.
30345         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
30346         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
30347         // capture constructors in 'initializeState' to avoid null checks
30348         // tslint:disable variable-name
30349         var NodeConstructor;
30350         var TokenConstructor;
30351         var IdentifierConstructor;
30352         var PrivateIdentifierConstructor;
30353         var SourceFileConstructor;
30354         // tslint:enable variable-name
30355         function countNode(node) {
30356             nodeCount++;
30357             return node;
30358         }
30359         // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
30360         // constructors above, which are reset each time `initializeState` is called.
30361         var baseNodeFactory = {
30362             createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
30363             createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
30364             createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
30365             createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
30366             createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
30367         };
30368         var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
30369         var fileName;
30370         var sourceFlags;
30371         var sourceText;
30372         var languageVersion;
30373         var scriptKind;
30374         var languageVariant;
30375         var parseDiagnostics;
30376         var jsDocDiagnostics;
30377         var syntaxCursor;
30378         var currentToken;
30379         var nodeCount;
30380         var identifiers;
30381         var privateIdentifiers;
30382         var identifierCount;
30383         var parsingContext;
30384         var notParenthesizedArrow;
30385         // Flags that dictate what parsing context we're in.  For example:
30386         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
30387         // that some tokens that would be considered identifiers may be considered keywords.
30388         //
30389         // When adding more parser context flags, consider which is the more common case that the
30390         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
30391         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
30392         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
30393         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
30394         // all nodes would need extra state on them to store this info.
30395         //
30396         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
30397         // grammar specification.
30398         //
30399         // An important thing about these context concepts.  By default they are effectively inherited
30400         // while parsing through every grammar production.  i.e. if you don't change them, then when
30401         // you parse a sub-production, it will have the same context values as the parent production.
30402         // This is great most of the time.  After all, consider all the 'expression' grammar productions
30403         // and how nearly all of them pass along the 'in' and 'yield' context values:
30404         //
30405         // EqualityExpression[In, Yield] :
30406         //      RelationalExpression[?In, ?Yield]
30407         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
30408         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
30409         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
30410         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
30411         //
30412         // Where you have to be careful is then understanding what the points are in the grammar
30413         // where the values are *not* passed along.  For example:
30414         //
30415         // SingleNameBinding[Yield,GeneratorParameter]
30416         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
30417         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
30418         //
30419         // Here this is saying that if the GeneratorParameter context flag is set, that we should
30420         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
30421         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
30422         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
30423         // should leave the 'yield' context flag alone.
30424         //
30425         // Getting this all correct is tricky and requires careful reading of the grammar to
30426         // understand when these values should be changed versus when they should be inherited.
30427         //
30428         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
30429         // parsing.  These context flags are naturally stored and restored through normal recursive
30430         // descent parsing and unwinding.
30431         var contextFlags;
30432         // Indicates whether we are currently parsing top-level statements.
30433         var topLevel = true;
30434         // Whether or not we've had a parse error since creating the last AST node.  If we have
30435         // encountered an error, it will be stored on the next AST node we create.  Parse errors
30436         // can be broken down into three categories:
30437         //
30438         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
30439         //    character that was completely not understood.
30440         //
30441         // 2) A token was expected, but was not present.  This type of error is commonly produced
30442         //    by the 'parseExpected' function.
30443         //
30444         // 3) A token was present that no parsing function was able to consume.  This type of error
30445         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
30446         //    decides to skip the token.
30447         //
30448         // In all of these cases, we want to mark the next node as having had an error before it.
30449         // With this mark, we can know in incremental settings if this node can be reused, or if
30450         // we have to reparse it.  If we don't keep this information around, we may just reuse the
30451         // node.  in that event we would then not produce the same errors as we did before, causing
30452         // significant confusion problems.
30453         //
30454         // Note: it is necessary that this value be saved/restored during speculative/lookahead
30455         // parsing.  During lookahead parsing, we will often create a node.  That node will have
30456         // this value attached, and then this value will be set back to 'false'.  If we decide to
30457         // rewind, we must get back to the same value we had prior to the lookahead.
30458         //
30459         // Note: any errors at the end of the file that do not precede a regular node, should get
30460         // attached to the EOF token.
30461         var parseErrorBeforeNextFinishedNode = false;
30462         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
30463             var _a;
30464             if (setParentNodes === void 0) { setParentNodes = false; }
30465             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
30466             if (scriptKind === 6 /* JSON */) {
30467                 var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
30468                 ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
30469                 result_3.referencedFiles = ts.emptyArray;
30470                 result_3.typeReferenceDirectives = ts.emptyArray;
30471                 result_3.libReferenceDirectives = ts.emptyArray;
30472                 result_3.amdDependencies = ts.emptyArray;
30473                 result_3.hasNoDefaultLib = false;
30474                 result_3.pragmas = ts.emptyMap;
30475                 return result_3;
30476             }
30477             initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
30478             var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
30479             clearState();
30480             return result;
30481         }
30482         Parser.parseSourceFile = parseSourceFile;
30483         function parseIsolatedEntityName(content, languageVersion) {
30484             // Choice of `isDeclarationFile` should be arbitrary
30485             initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
30486             // Prime the scanner.
30487             nextToken();
30488             var entityName = parseEntityName(/*allowReservedWords*/ true);
30489             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
30490             clearState();
30491             return isInvalid ? entityName : undefined;
30492         }
30493         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
30494         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
30495             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
30496             if (setParentNodes === void 0) { setParentNodes = false; }
30497             initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
30498             sourceFlags = contextFlags;
30499             // Prime the scanner.
30500             nextToken();
30501             var pos = getNodePos();
30502             var statements, endOfFileToken;
30503             if (token() === 1 /* EndOfFileToken */) {
30504                 statements = createNodeArray([], pos, pos);
30505                 endOfFileToken = parseTokenNode();
30506             }
30507             else {
30508                 // Loop and synthesize an ArrayLiteralExpression if there are more than
30509                 // one top-level expressions to ensure all input text is consumed.
30510                 var expressions = void 0;
30511                 while (token() !== 1 /* EndOfFileToken */) {
30512                     var expression_1 = void 0;
30513                     switch (token()) {
30514                         case 22 /* OpenBracketToken */:
30515                             expression_1 = parseArrayLiteralExpression();
30516                             break;
30517                         case 110 /* TrueKeyword */:
30518                         case 95 /* FalseKeyword */:
30519                         case 104 /* NullKeyword */:
30520                             expression_1 = parseTokenNode();
30521                             break;
30522                         case 40 /* MinusToken */:
30523                             if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
30524                                 expression_1 = parsePrefixUnaryExpression();
30525                             }
30526                             else {
30527                                 expression_1 = parseObjectLiteralExpression();
30528                             }
30529                             break;
30530                         case 8 /* NumericLiteral */:
30531                         case 10 /* StringLiteral */:
30532                             if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
30533                                 expression_1 = parseLiteralNode();
30534                                 break;
30535                             }
30536                         // falls through
30537                         default:
30538                             expression_1 = parseObjectLiteralExpression();
30539                             break;
30540                     }
30541                     // Error recovery: collect multiple top-level expressions
30542                     if (expressions && ts.isArray(expressions)) {
30543                         expressions.push(expression_1);
30544                     }
30545                     else if (expressions) {
30546                         expressions = [expressions, expression_1];
30547                     }
30548                     else {
30549                         expressions = expression_1;
30550                         if (token() !== 1 /* EndOfFileToken */) {
30551                             parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token);
30552                         }
30553                     }
30554                 }
30555                 var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions);
30556                 var statement = factory.createExpressionStatement(expression);
30557                 finishNode(statement, pos);
30558                 statements = createNodeArray([statement], pos);
30559                 endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
30560             }
30561             // Set source file so that errors will be reported with this file name
30562             var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
30563             if (setParentNodes) {
30564                 fixupParentReferences(sourceFile);
30565             }
30566             sourceFile.nodeCount = nodeCount;
30567             sourceFile.identifierCount = identifierCount;
30568             sourceFile.identifiers = identifiers;
30569             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
30570             if (jsDocDiagnostics) {
30571                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
30572             }
30573             var result = sourceFile;
30574             clearState();
30575             return result;
30576         }
30577         Parser.parseJsonText = parseJsonText;
30578         function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
30579             NodeConstructor = ts.objectAllocator.getNodeConstructor();
30580             TokenConstructor = ts.objectAllocator.getTokenConstructor();
30581             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
30582             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
30583             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
30584             fileName = ts.normalizePath(_fileName);
30585             sourceText = _sourceText;
30586             languageVersion = _languageVersion;
30587             syntaxCursor = _syntaxCursor;
30588             scriptKind = _scriptKind;
30589             languageVariant = ts.getLanguageVariant(_scriptKind);
30590             parseDiagnostics = [];
30591             parsingContext = 0;
30592             identifiers = new ts.Map();
30593             privateIdentifiers = new ts.Map();
30594             identifierCount = 0;
30595             nodeCount = 0;
30596             sourceFlags = 0;
30597             topLevel = true;
30598             switch (scriptKind) {
30599                 case 1 /* JS */:
30600                 case 2 /* JSX */:
30601                     contextFlags = 131072 /* JavaScriptFile */;
30602                     break;
30603                 case 6 /* JSON */:
30604                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
30605                     break;
30606                 default:
30607                     contextFlags = 0 /* None */;
30608                     break;
30609             }
30610             parseErrorBeforeNextFinishedNode = false;
30611             // Initialize and prime the scanner before parsing the source elements.
30612             scanner.setText(sourceText);
30613             scanner.setOnError(scanError);
30614             scanner.setScriptTarget(languageVersion);
30615             scanner.setLanguageVariant(languageVariant);
30616         }
30617         function clearState() {
30618             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
30619             scanner.clearCommentDirectives();
30620             scanner.setText("");
30621             scanner.setOnError(undefined);
30622             // Clear any data.  We don't want to accidentally hold onto it for too long.
30623             sourceText = undefined;
30624             languageVersion = undefined;
30625             syntaxCursor = undefined;
30626             scriptKind = undefined;
30627             languageVariant = undefined;
30628             sourceFlags = 0;
30629             parseDiagnostics = undefined;
30630             jsDocDiagnostics = undefined;
30631             parsingContext = 0;
30632             identifiers = undefined;
30633             notParenthesizedArrow = undefined;
30634             topLevel = true;
30635         }
30636         function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
30637             var isDeclarationFile = isDeclarationFileName(fileName);
30638             if (isDeclarationFile) {
30639                 contextFlags |= 8388608 /* Ambient */;
30640             }
30641             sourceFlags = contextFlags;
30642             // Prime the scanner.
30643             nextToken();
30644             var statements = parseList(0 /* SourceElements */, parseStatement);
30645             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
30646             var endOfFileToken = addJSDocComment(parseTokenNode());
30647             var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
30648             // 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
30649             processCommentPragmas(sourceFile, sourceText);
30650             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
30651             sourceFile.commentDirectives = scanner.getCommentDirectives();
30652             sourceFile.nodeCount = nodeCount;
30653             sourceFile.identifierCount = identifierCount;
30654             sourceFile.identifiers = identifiers;
30655             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
30656             if (jsDocDiagnostics) {
30657                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
30658             }
30659             if (setParentNodes) {
30660                 fixupParentReferences(sourceFile);
30661             }
30662             return sourceFile;
30663             function reportPragmaDiagnostic(pos, end, diagnostic) {
30664                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
30665             }
30666         }
30667         function withJSDoc(node, hasJSDoc) {
30668             return hasJSDoc ? addJSDocComment(node) : node;
30669         }
30670         var hasDeprecatedTag = false;
30671         function addJSDocComment(node) {
30672             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
30673             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
30674             if (jsDoc.length)
30675                 node.jsDoc = jsDoc;
30676             if (hasDeprecatedTag) {
30677                 hasDeprecatedTag = false;
30678                 node.flags |= 134217728 /* Deprecated */;
30679             }
30680             return node;
30681         }
30682         function reparseTopLevelAwait(sourceFile) {
30683             var savedSyntaxCursor = syntaxCursor;
30684             var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
30685             syntaxCursor = { currentNode: currentNode };
30686             var statements = [];
30687             var savedParseDiagnostics = parseDiagnostics;
30688             parseDiagnostics = [];
30689             var pos = 0;
30690             var start = findNextStatementWithAwait(sourceFile.statements, 0);
30691             var _loop_3 = function () {
30692                 // append all statements between pos and start
30693                 var prevStatement = sourceFile.statements[pos];
30694                 var nextStatement = sourceFile.statements[start];
30695                 ts.addRange(statements, sourceFile.statements, pos, start);
30696                 pos = findNextStatementWithoutAwait(sourceFile.statements, start);
30697                 // append all diagnostics associated with the copied range
30698                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
30699                 var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
30700                 if (diagnosticStart >= 0) {
30701                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
30702                 }
30703                 // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
30704                 speculationHelper(function () {
30705                     var savedContextFlags = contextFlags;
30706                     contextFlags |= 32768 /* AwaitContext */;
30707                     scanner.setTextPos(nextStatement.pos);
30708                     nextToken();
30709                     while (token() !== 1 /* EndOfFileToken */) {
30710                         var startPos = scanner.getStartPos();
30711                         var statement = parseListElement(0 /* SourceElements */, parseStatement);
30712                         statements.push(statement);
30713                         if (startPos === scanner.getStartPos()) {
30714                             nextToken();
30715                         }
30716                         if (pos >= 0) {
30717                             var nonAwaitStatement = sourceFile.statements[pos];
30718                             if (statement.end === nonAwaitStatement.pos) {
30719                                 // done reparsing this section
30720                                 break;
30721                             }
30722                             if (statement.end > nonAwaitStatement.pos) {
30723                                 // we ate into the next statement, so we must reparse it.
30724                                 pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
30725                             }
30726                         }
30727                     }
30728                     contextFlags = savedContextFlags;
30729                 }, 2 /* Reparse */);
30730                 // find the next statement containing an `await`
30731                 start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
30732             };
30733             while (start !== -1) {
30734                 _loop_3();
30735             }
30736             // append all statements between pos and the end of the list
30737             if (pos >= 0) {
30738                 var prevStatement_1 = sourceFile.statements[pos];
30739                 ts.addRange(statements, sourceFile.statements, pos);
30740                 // append all diagnostics associated with the copied range
30741                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
30742                 if (diagnosticStart >= 0) {
30743                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
30744                 }
30745             }
30746             syntaxCursor = savedSyntaxCursor;
30747             return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
30748             function containsPossibleTopLevelAwait(node) {
30749                 return !(node.flags & 32768 /* AwaitContext */)
30750                     && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */);
30751             }
30752             function findNextStatementWithAwait(statements, start) {
30753                 for (var i = start; i < statements.length; i++) {
30754                     if (containsPossibleTopLevelAwait(statements[i])) {
30755                         return i;
30756                     }
30757                 }
30758                 return -1;
30759             }
30760             function findNextStatementWithoutAwait(statements, start) {
30761                 for (var i = start; i < statements.length; i++) {
30762                     if (!containsPossibleTopLevelAwait(statements[i])) {
30763                         return i;
30764                     }
30765                 }
30766                 return -1;
30767             }
30768             function currentNode(position) {
30769                 var node = baseSyntaxCursor.currentNode(position);
30770                 if (topLevel && node && containsPossibleTopLevelAwait(node)) {
30771                     node.intersectsChange = true;
30772                 }
30773                 return node;
30774             }
30775         }
30776         function fixupParentReferences(rootNode) {
30777             // normally parent references are set during binding. However, for clients that only need
30778             // a syntax tree, and no semantic features, then the binding process is an unnecessary
30779             // overhead.  This functions allows us to set all the parents, without all the expense of
30780             // binding.
30781             ts.setParentRecursive(rootNode, /*incremental*/ true);
30782         }
30783         Parser.fixupParentReferences = fixupParentReferences;
30784         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
30785             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
30786             // this is quite rare comparing to other nodes and createNode should be as fast as possible
30787             var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags);
30788             ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
30789             setExternalModuleIndicator(sourceFile);
30790             // If we parsed this as an external module, it may contain top-level await
30791             if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) {
30792                 sourceFile = reparseTopLevelAwait(sourceFile);
30793             }
30794             sourceFile.text = sourceText;
30795             sourceFile.bindDiagnostics = [];
30796             sourceFile.bindSuggestionDiagnostics = undefined;
30797             sourceFile.languageVersion = languageVersion;
30798             sourceFile.fileName = fileName;
30799             sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
30800             sourceFile.isDeclarationFile = isDeclarationFile;
30801             sourceFile.scriptKind = scriptKind;
30802             return sourceFile;
30803         }
30804         function setContextFlag(val, flag) {
30805             if (val) {
30806                 contextFlags |= flag;
30807             }
30808             else {
30809                 contextFlags &= ~flag;
30810             }
30811         }
30812         function setDisallowInContext(val) {
30813             setContextFlag(val, 4096 /* DisallowInContext */);
30814         }
30815         function setYieldContext(val) {
30816             setContextFlag(val, 8192 /* YieldContext */);
30817         }
30818         function setDecoratorContext(val) {
30819             setContextFlag(val, 16384 /* DecoratorContext */);
30820         }
30821         function setAwaitContext(val) {
30822             setContextFlag(val, 32768 /* AwaitContext */);
30823         }
30824         function doOutsideOfContext(context, func) {
30825             // contextFlagsToClear will contain only the context flags that are
30826             // currently set that we need to temporarily clear
30827             // We don't just blindly reset to the previous flags to ensure
30828             // that we do not mutate cached flags for the incremental
30829             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
30830             // HasAggregatedChildData).
30831             var contextFlagsToClear = context & contextFlags;
30832             if (contextFlagsToClear) {
30833                 // clear the requested context flags
30834                 setContextFlag(/*val*/ false, contextFlagsToClear);
30835                 var result = func();
30836                 // restore the context flags we just cleared
30837                 setContextFlag(/*val*/ true, contextFlagsToClear);
30838                 return result;
30839             }
30840             // no need to do anything special as we are not in any of the requested contexts
30841             return func();
30842         }
30843         function doInsideOfContext(context, func) {
30844             // contextFlagsToSet will contain only the context flags that
30845             // are not currently set that we need to temporarily enable.
30846             // We don't just blindly reset to the previous flags to ensure
30847             // that we do not mutate cached flags for the incremental
30848             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
30849             // HasAggregatedChildData).
30850             var contextFlagsToSet = context & ~contextFlags;
30851             if (contextFlagsToSet) {
30852                 // set the requested context flags
30853                 setContextFlag(/*val*/ true, contextFlagsToSet);
30854                 var result = func();
30855                 // reset the context flags we just set
30856                 setContextFlag(/*val*/ false, contextFlagsToSet);
30857                 return result;
30858             }
30859             // no need to do anything special as we are already in all of the requested contexts
30860             return func();
30861         }
30862         function allowInAnd(func) {
30863             return doOutsideOfContext(4096 /* DisallowInContext */, func);
30864         }
30865         function disallowInAnd(func) {
30866             return doInsideOfContext(4096 /* DisallowInContext */, func);
30867         }
30868         function doInYieldContext(func) {
30869             return doInsideOfContext(8192 /* YieldContext */, func);
30870         }
30871         function doInDecoratorContext(func) {
30872             return doInsideOfContext(16384 /* DecoratorContext */, func);
30873         }
30874         function doInAwaitContext(func) {
30875             return doInsideOfContext(32768 /* AwaitContext */, func);
30876         }
30877         function doOutsideOfAwaitContext(func) {
30878             return doOutsideOfContext(32768 /* AwaitContext */, func);
30879         }
30880         function doInYieldAndAwaitContext(func) {
30881             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
30882         }
30883         function doOutsideOfYieldAndAwaitContext(func) {
30884             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
30885         }
30886         function inContext(flags) {
30887             return (contextFlags & flags) !== 0;
30888         }
30889         function inYieldContext() {
30890             return inContext(8192 /* YieldContext */);
30891         }
30892         function inDisallowInContext() {
30893             return inContext(4096 /* DisallowInContext */);
30894         }
30895         function inDecoratorContext() {
30896             return inContext(16384 /* DecoratorContext */);
30897         }
30898         function inAwaitContext() {
30899             return inContext(32768 /* AwaitContext */);
30900         }
30901         function parseErrorAtCurrentToken(message, arg0) {
30902             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
30903         }
30904         function parseErrorAtPosition(start, length, message, arg0) {
30905             // Don't report another error if it would just be at the same position as the last error.
30906             var lastError = ts.lastOrUndefined(parseDiagnostics);
30907             if (!lastError || start !== lastError.start) {
30908                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, start, length, message, arg0));
30909             }
30910             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
30911             // node we finish so that it can't be reused incrementally.
30912             parseErrorBeforeNextFinishedNode = true;
30913         }
30914         function parseErrorAt(start, end, message, arg0) {
30915             parseErrorAtPosition(start, end - start, message, arg0);
30916         }
30917         function parseErrorAtRange(range, message, arg0) {
30918             parseErrorAt(range.pos, range.end, message, arg0);
30919         }
30920         function scanError(message, length) {
30921             parseErrorAtPosition(scanner.getTextPos(), length, message);
30922         }
30923         function getNodePos() {
30924             return scanner.getStartPos();
30925         }
30926         function hasPrecedingJSDocComment() {
30927             return scanner.hasPrecedingJSDocComment();
30928         }
30929         // Use this function to access the current token instead of reading the currentToken
30930         // variable. Since function results aren't narrowed in control flow analysis, this ensures
30931         // that the type checker doesn't make wrong assumptions about the type of the current
30932         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
30933         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
30934         // there is no performance penalty.
30935         function token() {
30936             return currentToken;
30937         }
30938         function nextTokenWithoutCheck() {
30939             return currentToken = scanner.scan();
30940         }
30941         function nextTokenAnd(func) {
30942             nextToken();
30943             return func();
30944         }
30945         function nextToken() {
30946             // if the keyword had an escape
30947             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
30948                 // issue a parse error for the escape
30949                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
30950             }
30951             return nextTokenWithoutCheck();
30952         }
30953         function nextTokenJSDoc() {
30954             return currentToken = scanner.scanJsDocToken();
30955         }
30956         function reScanGreaterToken() {
30957             return currentToken = scanner.reScanGreaterToken();
30958         }
30959         function reScanSlashToken() {
30960             return currentToken = scanner.reScanSlashToken();
30961         }
30962         function reScanTemplateToken(isTaggedTemplate) {
30963             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
30964         }
30965         function reScanTemplateHeadOrNoSubstitutionTemplate() {
30966             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
30967         }
30968         function reScanLessThanToken() {
30969             return currentToken = scanner.reScanLessThanToken();
30970         }
30971         function reScanHashToken() {
30972             return currentToken = scanner.reScanHashToken();
30973         }
30974         function scanJsxIdentifier() {
30975             return currentToken = scanner.scanJsxIdentifier();
30976         }
30977         function scanJsxText() {
30978             return currentToken = scanner.scanJsxToken();
30979         }
30980         function scanJsxAttributeValue() {
30981             return currentToken = scanner.scanJsxAttributeValue();
30982         }
30983         function speculationHelper(callback, speculationKind) {
30984             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
30985             // caller asked us to always reset our state).
30986             var saveToken = currentToken;
30987             var saveParseDiagnosticsLength = parseDiagnostics.length;
30988             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
30989             // Note: it is not actually necessary to save/restore the context flags here.  That's
30990             // because the saving/restoring of these flags happens naturally through the recursive
30991             // descent nature of our parser.  However, we still store this here just so we can
30992             // assert that invariant holds.
30993             var saveContextFlags = contextFlags;
30994             // If we're only looking ahead, then tell the scanner to only lookahead as well.
30995             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
30996             // same.
30997             var result = speculationKind !== 0 /* TryParse */
30998                 ? scanner.lookAhead(callback)
30999                 : scanner.tryScan(callback);
31000             ts.Debug.assert(saveContextFlags === contextFlags);
31001             // If our callback returned something 'falsy' or we're just looking ahead,
31002             // then unconditionally restore us to where we were.
31003             if (!result || speculationKind !== 0 /* TryParse */) {
31004                 currentToken = saveToken;
31005                 if (speculationKind !== 2 /* Reparse */) {
31006                     parseDiagnostics.length = saveParseDiagnosticsLength;
31007                 }
31008                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
31009             }
31010             return result;
31011         }
31012         /** Invokes the provided callback then unconditionally restores the parser to the state it
31013          * was in immediately prior to invoking the callback.  The result of invoking the callback
31014          * is returned from this function.
31015          */
31016         function lookAhead(callback) {
31017             return speculationHelper(callback, 1 /* Lookahead */);
31018         }
31019         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
31020          * the parser to the state it was in immediately prior to invoking the callback.  If the
31021          * callback returns something truthy, then the parser state is not rolled back.  The result
31022          * of invoking the callback is returned from this function.
31023          */
31024         function tryParse(callback) {
31025             return speculationHelper(callback, 0 /* TryParse */);
31026         }
31027         function isBindingIdentifier() {
31028             if (token() === 79 /* Identifier */) {
31029                 return true;
31030             }
31031             // `let await`/`let yield` in [Yield] or [Await] are allowed here and disallowed in the binder.
31032             return token() > 116 /* LastReservedWord */;
31033         }
31034         // Ignore strict mode flag because we will report an error in type checker instead.
31035         function isIdentifier() {
31036             if (token() === 79 /* Identifier */) {
31037                 return true;
31038             }
31039             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
31040             // considered a keyword and is not an identifier.
31041             if (token() === 125 /* YieldKeyword */ && inYieldContext()) {
31042                 return false;
31043             }
31044             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
31045             // considered a keyword and is not an identifier.
31046             if (token() === 132 /* AwaitKeyword */ && inAwaitContext()) {
31047                 return false;
31048             }
31049             return token() > 116 /* LastReservedWord */;
31050         }
31051         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
31052             if (shouldAdvance === void 0) { shouldAdvance = true; }
31053             if (token() === kind) {
31054                 if (shouldAdvance) {
31055                     nextToken();
31056                 }
31057                 return true;
31058             }
31059             // Report specific message if provided with one.  Otherwise, report generic fallback message.
31060             if (diagnosticMessage) {
31061                 parseErrorAtCurrentToken(diagnosticMessage);
31062             }
31063             else {
31064                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
31065             }
31066             return false;
31067         }
31068         var viableKeywordSuggestions = Object.keys(ts.textToKeywordObj).filter(function (keyword) { return keyword.length > 2; });
31069         /**
31070          * Provides a better error message than the generic "';' expected" if possible for
31071          * known common variants of a missing semicolon, such as from a mispelled names.
31072          *
31073          * @param node Node preceding the expected semicolon location.
31074          */
31075         function parseErrorForMissingSemicolonAfter(node) {
31076             var _a;
31077             // Tagged template literals are sometimes used in places where only simple strings are allowed, i.e.:
31078             //   module `M1` {
31079             //   ^^^^^^^^^^^ This block is parsed as a template literal like module`M1`.
31080             if (ts.isTaggedTemplateExpression(node)) {
31081                 parseErrorAt(ts.skipTrivia(sourceText, node.template.pos), node.template.end, ts.Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings);
31082                 return;
31083             }
31084             // Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
31085             var expressionText = ts.isIdentifier(node) ? ts.idText(node) : undefined;
31086             if (!expressionText || !ts.isIdentifierText(expressionText, languageVersion)) {
31087                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
31088                 return;
31089             }
31090             var pos = ts.skipTrivia(sourceText, node.pos);
31091             // Some known keywords are likely signs of syntax being used improperly.
31092             switch (expressionText) {
31093                 case "const":
31094                 case "let":
31095                 case "var":
31096                     parseErrorAt(pos, node.end, ts.Diagnostics.Variable_declaration_not_allowed_at_this_location);
31097                     return;
31098                 case "declare":
31099                     // If a declared node failed to parse, it would have emitted a diagnostic already.
31100                     return;
31101                 case "interface":
31102                     parseErrorForInvalidName(ts.Diagnostics.Interface_name_cannot_be_0, ts.Diagnostics.Interface_must_be_given_a_name, 18 /* OpenBraceToken */);
31103                     return;
31104                 case "is":
31105                     parseErrorAt(pos, scanner.getTextPos(), ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
31106                     return;
31107                 case "module":
31108                 case "namespace":
31109                     parseErrorForInvalidName(ts.Diagnostics.Namespace_name_cannot_be_0, ts.Diagnostics.Namespace_must_be_given_a_name, 18 /* OpenBraceToken */);
31110                     return;
31111                 case "type":
31112                     parseErrorForInvalidName(ts.Diagnostics.Type_alias_name_cannot_be_0, ts.Diagnostics.Type_alias_must_be_given_a_name, 63 /* EqualsToken */);
31113                     return;
31114             }
31115             // The user alternatively might have misspelled or forgotten to add a space after a common keyword.
31116             var suggestion = (_a = ts.getSpellingSuggestion(expressionText, viableKeywordSuggestions, function (n) { return n; })) !== null && _a !== void 0 ? _a : getSpaceSuggestion(expressionText);
31117             if (suggestion) {
31118                 parseErrorAt(pos, node.end, ts.Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion);
31119                 return;
31120             }
31121             // Unknown tokens are handled with their own errors in the scanner
31122             if (token() === 0 /* Unknown */) {
31123                 return;
31124             }
31125             // Otherwise, we know this some kind of unknown word, not just a missing expected semicolon.
31126             parseErrorAt(pos, node.end, ts.Diagnostics.Unexpected_keyword_or_identifier);
31127         }
31128         /**
31129          * Reports a diagnostic error for the current token being an invalid name.
31130          *
31131          * @param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
31132          * @param nameDiagnostic Diagnostic to report for all other cases.
31133          * @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
31134          */
31135         function parseErrorForInvalidName(nameDiagnostic, blankDiagnostic, tokenIfBlankName) {
31136             if (token() === tokenIfBlankName) {
31137                 parseErrorAtCurrentToken(blankDiagnostic);
31138             }
31139             else {
31140                 parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue());
31141             }
31142         }
31143         function getSpaceSuggestion(expressionText) {
31144             for (var _i = 0, viableKeywordSuggestions_1 = viableKeywordSuggestions; _i < viableKeywordSuggestions_1.length; _i++) {
31145                 var keyword = viableKeywordSuggestions_1[_i];
31146                 if (expressionText.length > keyword.length + 2 && ts.startsWith(expressionText, keyword)) {
31147                     return "".concat(keyword, " ").concat(expressionText.slice(keyword.length));
31148                 }
31149             }
31150             return undefined;
31151         }
31152         function parseSemicolonAfterPropertyName(name, type, initializer) {
31153             if (token() === 59 /* AtToken */ && !scanner.hasPrecedingLineBreak()) {
31154                 parseErrorAtCurrentToken(ts.Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations);
31155                 return;
31156             }
31157             if (token() === 20 /* OpenParenToken */) {
31158                 parseErrorAtCurrentToken(ts.Diagnostics.Cannot_start_a_function_call_in_a_type_annotation);
31159                 nextToken();
31160                 return;
31161             }
31162             if (type && !canParseSemicolon()) {
31163                 if (initializer) {
31164                     parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
31165                 }
31166                 else {
31167                     parseErrorAtCurrentToken(ts.Diagnostics.Expected_for_property_initializer);
31168                 }
31169                 return;
31170             }
31171             if (tryParseSemicolon()) {
31172                 return;
31173             }
31174             // If an initializer was parsed but there is still an error in finding the next semicolon,
31175             // we generally know there was an error already reported in the initializer...
31176             //   class Example { a = new Map([), ) }
31177             //                                ~
31178             if (initializer) {
31179                 // ...unless we've found the start of a block after a property declaration, in which
31180                 // case we can know that regardless of the initializer we should complain on the block.
31181                 //   class Example { a = 0 {} }
31182                 //                         ~
31183                 if (token() === 18 /* OpenBraceToken */) {
31184                     parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(26 /* SemicolonToken */));
31185                 }
31186                 return;
31187             }
31188             parseErrorForMissingSemicolonAfter(name);
31189         }
31190         function parseExpectedJSDoc(kind) {
31191             if (token() === kind) {
31192                 nextTokenJSDoc();
31193                 return true;
31194             }
31195             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
31196             return false;
31197         }
31198         function parseOptional(t) {
31199             if (token() === t) {
31200                 nextToken();
31201                 return true;
31202             }
31203             return false;
31204         }
31205         function parseOptionalToken(t) {
31206             if (token() === t) {
31207                 return parseTokenNode();
31208             }
31209             return undefined;
31210         }
31211         function parseOptionalTokenJSDoc(t) {
31212             if (token() === t) {
31213                 return parseTokenNodeJSDoc();
31214             }
31215             return undefined;
31216         }
31217         function parseExpectedToken(t, diagnosticMessage, arg0) {
31218             return parseOptionalToken(t) ||
31219                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
31220         }
31221         function parseExpectedTokenJSDoc(t) {
31222             return parseOptionalTokenJSDoc(t) ||
31223                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
31224         }
31225         function parseTokenNode() {
31226             var pos = getNodePos();
31227             var kind = token();
31228             nextToken();
31229             return finishNode(factory.createToken(kind), pos);
31230         }
31231         function parseTokenNodeJSDoc() {
31232             var pos = getNodePos();
31233             var kind = token();
31234             nextTokenJSDoc();
31235             return finishNode(factory.createToken(kind), pos);
31236         }
31237         function canParseSemicolon() {
31238             // If there's a real semicolon, then we can always parse it out.
31239             if (token() === 26 /* SemicolonToken */) {
31240                 return true;
31241             }
31242             // We can parse out an optional semicolon in ASI cases in the following cases.
31243             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
31244         }
31245         function tryParseSemicolon() {
31246             if (!canParseSemicolon()) {
31247                 return false;
31248             }
31249             if (token() === 26 /* SemicolonToken */) {
31250                 // consume the semicolon if it was explicitly provided.
31251                 nextToken();
31252             }
31253             return true;
31254         }
31255         function parseSemicolon() {
31256             return tryParseSemicolon() || parseExpected(26 /* SemicolonToken */);
31257         }
31258         function createNodeArray(elements, pos, end, hasTrailingComma) {
31259             var array = factory.createNodeArray(elements, hasTrailingComma);
31260             ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
31261             return array;
31262         }
31263         function finishNode(node, pos, end) {
31264             ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
31265             if (contextFlags) {
31266                 node.flags |= contextFlags;
31267             }
31268             // Keep track on the node if we encountered an error while parsing it.  If we did, then
31269             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
31270             // flag so that we don't mark any subsequent nodes.
31271             if (parseErrorBeforeNextFinishedNode) {
31272                 parseErrorBeforeNextFinishedNode = false;
31273                 node.flags |= 65536 /* ThisNodeHasError */;
31274             }
31275             return node;
31276         }
31277         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
31278             if (reportAtCurrentPosition) {
31279                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
31280             }
31281             else if (diagnosticMessage) {
31282                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
31283             }
31284             var pos = getNodePos();
31285             var result = kind === 79 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
31286                 ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
31287                     kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
31288                         kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
31289                             kind === 275 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
31290                                 factory.createToken(kind);
31291             return finishNode(result, pos);
31292         }
31293         function internIdentifier(text) {
31294             var identifier = identifiers.get(text);
31295             if (identifier === undefined) {
31296                 identifiers.set(text, identifier = text);
31297             }
31298             return identifier;
31299         }
31300         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
31301         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
31302         // each identifier in order to reduce memory consumption.
31303         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
31304             if (isIdentifier) {
31305                 identifierCount++;
31306                 var pos = getNodePos();
31307                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
31308                 var originalKeywordKind = token();
31309                 var text = internIdentifier(scanner.getTokenValue());
31310                 nextTokenWithoutCheck();
31311                 return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
31312             }
31313             if (token() === 80 /* PrivateIdentifier */) {
31314                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
31315                 return createIdentifier(/*isIdentifier*/ true);
31316             }
31317             if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 79 /* Identifier */; })) {
31318                 // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser.
31319                 return createIdentifier(/*isIdentifier*/ true);
31320             }
31321             identifierCount++;
31322             // Only for end of file because the error gets reported incorrectly on embedded script tags.
31323             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
31324             var isReservedWord = scanner.isReservedWord();
31325             var msgArg = scanner.getTokenText();
31326             var defaultMessage = isReservedWord ?
31327                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
31328                 ts.Diagnostics.Identifier_expected;
31329             return createMissingNode(79 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
31330         }
31331         function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
31332             return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
31333         }
31334         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
31335             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
31336         }
31337         function parseIdentifierName(diagnosticMessage) {
31338             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
31339         }
31340         function isLiteralPropertyName() {
31341             return ts.tokenIsIdentifierOrKeyword(token()) ||
31342                 token() === 10 /* StringLiteral */ ||
31343                 token() === 8 /* NumericLiteral */;
31344         }
31345         function isAssertionKey() {
31346             return ts.tokenIsIdentifierOrKeyword(token()) ||
31347                 token() === 10 /* StringLiteral */;
31348         }
31349         function parsePropertyNameWorker(allowComputedPropertyNames) {
31350             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
31351                 var node = parseLiteralNode();
31352                 node.text = internIdentifier(node.text);
31353                 return node;
31354             }
31355             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
31356                 return parseComputedPropertyName();
31357             }
31358             if (token() === 80 /* PrivateIdentifier */) {
31359                 return parsePrivateIdentifier();
31360             }
31361             return parseIdentifierName();
31362         }
31363         function parsePropertyName() {
31364             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
31365         }
31366         function parseComputedPropertyName() {
31367             // PropertyName [Yield]:
31368             //      LiteralPropertyName
31369             //      ComputedPropertyName[?Yield]
31370             var pos = getNodePos();
31371             parseExpected(22 /* OpenBracketToken */);
31372             // We parse any expression (including a comma expression). But the grammar
31373             // says that only an assignment expression is allowed, so the grammar checker
31374             // will error if it sees a comma expression.
31375             var expression = allowInAnd(parseExpression);
31376             parseExpected(23 /* CloseBracketToken */);
31377             return finishNode(factory.createComputedPropertyName(expression), pos);
31378         }
31379         function internPrivateIdentifier(text) {
31380             var privateIdentifier = privateIdentifiers.get(text);
31381             if (privateIdentifier === undefined) {
31382                 privateIdentifiers.set(text, privateIdentifier = text);
31383             }
31384             return privateIdentifier;
31385         }
31386         function parsePrivateIdentifier() {
31387             var pos = getNodePos();
31388             var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
31389             nextToken();
31390             return finishNode(node, pos);
31391         }
31392         function parseContextualModifier(t) {
31393             return token() === t && tryParse(nextTokenCanFollowModifier);
31394         }
31395         function nextTokenIsOnSameLineAndCanFollowModifier() {
31396             nextToken();
31397             if (scanner.hasPrecedingLineBreak()) {
31398                 return false;
31399             }
31400             return canFollowModifier();
31401         }
31402         function nextTokenCanFollowModifier() {
31403             switch (token()) {
31404                 case 85 /* ConstKeyword */:
31405                     // 'const' is only a modifier if followed by 'enum'.
31406                     return nextToken() === 92 /* EnumKeyword */;
31407                 case 93 /* ExportKeyword */:
31408                     nextToken();
31409                     if (token() === 88 /* DefaultKeyword */) {
31410                         return lookAhead(nextTokenCanFollowDefaultKeyword);
31411                     }
31412                     if (token() === 151 /* TypeKeyword */) {
31413                         return lookAhead(nextTokenCanFollowExportModifier);
31414                     }
31415                     return canFollowExportModifier();
31416                 case 88 /* DefaultKeyword */:
31417                     return nextTokenCanFollowDefaultKeyword();
31418                 case 124 /* StaticKeyword */:
31419                 case 136 /* GetKeyword */:
31420                 case 148 /* SetKeyword */:
31421                     nextToken();
31422                     return canFollowModifier();
31423                 default:
31424                     return nextTokenIsOnSameLineAndCanFollowModifier();
31425             }
31426         }
31427         function canFollowExportModifier() {
31428             return token() !== 41 /* AsteriskToken */
31429                 && token() !== 127 /* AsKeyword */
31430                 && token() !== 18 /* OpenBraceToken */
31431                 && canFollowModifier();
31432         }
31433         function nextTokenCanFollowExportModifier() {
31434             nextToken();
31435             return canFollowExportModifier();
31436         }
31437         function parseAnyContextualModifier() {
31438             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
31439         }
31440         function canFollowModifier() {
31441             return token() === 22 /* OpenBracketToken */
31442                 || token() === 18 /* OpenBraceToken */
31443                 || token() === 41 /* AsteriskToken */
31444                 || token() === 25 /* DotDotDotToken */
31445                 || isLiteralPropertyName();
31446         }
31447         function nextTokenCanFollowDefaultKeyword() {
31448             nextToken();
31449             return token() === 84 /* ClassKeyword */ || token() === 98 /* FunctionKeyword */ ||
31450                 token() === 118 /* InterfaceKeyword */ ||
31451                 (token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
31452                 (token() === 131 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
31453         }
31454         // True if positioned at the start of a list element
31455         function isListElement(parsingContext, inErrorRecovery) {
31456             var node = currentNode(parsingContext);
31457             if (node) {
31458                 return true;
31459             }
31460             switch (parsingContext) {
31461                 case 0 /* SourceElements */:
31462                 case 1 /* BlockStatements */:
31463                 case 3 /* SwitchClauseStatements */:
31464                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
31465                     // The problem is that ';' can show up in far too many contexts, and if we see one
31466                     // and assume it's a statement, then we may bail out inappropriately from whatever
31467                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
31468                     // we really don't want to assume the class is over and we're on a statement in the
31469                     // outer module.  We just want to consume and move on.
31470                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
31471                 case 2 /* SwitchClauses */:
31472                     return token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */;
31473                 case 4 /* TypeMembers */:
31474                     return lookAhead(isTypeMemberStart);
31475                 case 5 /* ClassMembers */:
31476                     // We allow semicolons as class elements (as specified by ES6) as long as we're
31477                     // not in error recovery.  If we're in error recovery, we don't want an errant
31478                     // semicolon to be treated as a class member (since they're almost always used
31479                     // for statements.
31480                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
31481                 case 6 /* EnumMembers */:
31482                     // Include open bracket computed properties. This technically also lets in indexers,
31483                     // which would be a candidate for improved error reporting.
31484                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
31485                 case 12 /* ObjectLiteralMembers */:
31486                     switch (token()) {
31487                         case 22 /* OpenBracketToken */:
31488                         case 41 /* AsteriskToken */:
31489                         case 25 /* DotDotDotToken */:
31490                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
31491                             return true;
31492                         default:
31493                             return isLiteralPropertyName();
31494                     }
31495                 case 18 /* RestProperties */:
31496                     return isLiteralPropertyName();
31497                 case 9 /* ObjectBindingElements */:
31498                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
31499                 case 24 /* AssertEntries */:
31500                     return isAssertionKey();
31501                 case 7 /* HeritageClauseElement */:
31502                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
31503                     // That way we won't consume the body of a class in its heritage clause.
31504                     if (token() === 18 /* OpenBraceToken */) {
31505                         return lookAhead(isValidHeritageClauseObjectLiteral);
31506                     }
31507                     if (!inErrorRecovery) {
31508                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
31509                     }
31510                     else {
31511                         // If we're in error recovery we tighten up what we're willing to match.
31512                         // That way we don't treat something like "this" as a valid heritage clause
31513                         // element during recovery.
31514                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
31515                     }
31516                 case 8 /* VariableDeclarations */:
31517                     return isBindingIdentifierOrPrivateIdentifierOrPattern();
31518                 case 10 /* ArrayBindingElements */:
31519                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
31520                 case 19 /* TypeParameters */:
31521                     return isIdentifier();
31522                 case 15 /* ArrayLiteralMembers */:
31523                     switch (token()) {
31524                         case 27 /* CommaToken */:
31525                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
31526                             return true;
31527                     }
31528                 // falls through
31529                 case 11 /* ArgumentExpressions */:
31530                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
31531                 case 16 /* Parameters */:
31532                     return isStartOfParameter(/*isJSDocParameter*/ false);
31533                 case 17 /* JSDocParameters */:
31534                     return isStartOfParameter(/*isJSDocParameter*/ true);
31535                 case 20 /* TypeArguments */:
31536                 case 21 /* TupleElementTypes */:
31537                     return token() === 27 /* CommaToken */ || isStartOfType();
31538                 case 22 /* HeritageClauses */:
31539                     return isHeritageClause();
31540                 case 23 /* ImportOrExportSpecifiers */:
31541                     return ts.tokenIsIdentifierOrKeyword(token());
31542                 case 13 /* JsxAttributes */:
31543                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
31544                 case 14 /* JsxChildren */:
31545                     return true;
31546             }
31547             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
31548         }
31549         function isValidHeritageClauseObjectLiteral() {
31550             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
31551             if (nextToken() === 19 /* CloseBraceToken */) {
31552                 // if we see "extends {}" then only treat the {} as what we're extending (and not
31553                 // the class body) if we have:
31554                 //
31555                 //      extends {} {
31556                 //      extends {},
31557                 //      extends {} extends
31558                 //      extends {} implements
31559                 var next = nextToken();
31560                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 94 /* ExtendsKeyword */ || next === 117 /* ImplementsKeyword */;
31561             }
31562             return true;
31563         }
31564         function nextTokenIsIdentifier() {
31565             nextToken();
31566             return isIdentifier();
31567         }
31568         function nextTokenIsIdentifierOrKeyword() {
31569             nextToken();
31570             return ts.tokenIsIdentifierOrKeyword(token());
31571         }
31572         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
31573             nextToken();
31574             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
31575         }
31576         function isHeritageClauseExtendsOrImplementsKeyword() {
31577             if (token() === 117 /* ImplementsKeyword */ ||
31578                 token() === 94 /* ExtendsKeyword */) {
31579                 return lookAhead(nextTokenIsStartOfExpression);
31580             }
31581             return false;
31582         }
31583         function nextTokenIsStartOfExpression() {
31584             nextToken();
31585             return isStartOfExpression();
31586         }
31587         function nextTokenIsStartOfType() {
31588             nextToken();
31589             return isStartOfType();
31590         }
31591         // True if positioned at a list terminator
31592         function isListTerminator(kind) {
31593             if (token() === 1 /* EndOfFileToken */) {
31594                 // Being at the end of the file ends all lists.
31595                 return true;
31596             }
31597             switch (kind) {
31598                 case 1 /* BlockStatements */:
31599                 case 2 /* SwitchClauses */:
31600                 case 4 /* TypeMembers */:
31601                 case 5 /* ClassMembers */:
31602                 case 6 /* EnumMembers */:
31603                 case 12 /* ObjectLiteralMembers */:
31604                 case 9 /* ObjectBindingElements */:
31605                 case 23 /* ImportOrExportSpecifiers */:
31606                 case 24 /* AssertEntries */:
31607                     return token() === 19 /* CloseBraceToken */;
31608                 case 3 /* SwitchClauseStatements */:
31609                     return token() === 19 /* CloseBraceToken */ || token() === 82 /* CaseKeyword */ || token() === 88 /* DefaultKeyword */;
31610                 case 7 /* HeritageClauseElement */:
31611                     return token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
31612                 case 8 /* VariableDeclarations */:
31613                     return isVariableDeclaratorListTerminator();
31614                 case 19 /* TypeParameters */:
31615                     // Tokens other than '>' are here for better error recovery
31616                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
31617                 case 11 /* ArgumentExpressions */:
31618                     // Tokens other than ')' are here for better error recovery
31619                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
31620                 case 15 /* ArrayLiteralMembers */:
31621                 case 21 /* TupleElementTypes */:
31622                 case 10 /* ArrayBindingElements */:
31623                     return token() === 23 /* CloseBracketToken */;
31624                 case 17 /* JSDocParameters */:
31625                 case 16 /* Parameters */:
31626                 case 18 /* RestProperties */:
31627                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
31628                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
31629                 case 20 /* TypeArguments */:
31630                     // All other tokens should cause the type-argument to terminate except comma token
31631                     return token() !== 27 /* CommaToken */;
31632                 case 22 /* HeritageClauses */:
31633                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
31634                 case 13 /* JsxAttributes */:
31635                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
31636                 case 14 /* JsxChildren */:
31637                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
31638                 default:
31639                     return false;
31640             }
31641         }
31642         function isVariableDeclaratorListTerminator() {
31643             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
31644             // with parsing the list of variable declarators.
31645             if (canParseSemicolon()) {
31646                 return true;
31647             }
31648             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
31649             // are done if we see an 'in' keyword in front of us. Same with for-of
31650             if (isInOrOfKeyword(token())) {
31651                 return true;
31652             }
31653             // ERROR RECOVERY TWEAK:
31654             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
31655             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
31656             // another variable declaration.
31657             if (token() === 38 /* EqualsGreaterThanToken */) {
31658                 return true;
31659             }
31660             // Keep trying to parse out variable declarators.
31661             return false;
31662         }
31663         // True if positioned at element or terminator of the current list or any enclosing list
31664         function isInSomeParsingContext() {
31665             for (var kind = 0; kind < 25 /* Count */; kind++) {
31666                 if (parsingContext & (1 << kind)) {
31667                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
31668                         return true;
31669                     }
31670                 }
31671             }
31672             return false;
31673         }
31674         // Parses a list of elements
31675         function parseList(kind, parseElement) {
31676             var saveParsingContext = parsingContext;
31677             parsingContext |= 1 << kind;
31678             var list = [];
31679             var listPos = getNodePos();
31680             while (!isListTerminator(kind)) {
31681                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
31682                     list.push(parseListElement(kind, parseElement));
31683                     continue;
31684                 }
31685                 if (abortParsingListOrMoveToNextToken(kind)) {
31686                     break;
31687                 }
31688             }
31689             parsingContext = saveParsingContext;
31690             return createNodeArray(list, listPos);
31691         }
31692         function parseListElement(parsingContext, parseElement) {
31693             var node = currentNode(parsingContext);
31694             if (node) {
31695                 return consumeNode(node);
31696             }
31697             return parseElement();
31698         }
31699         function currentNode(parsingContext) {
31700             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
31701             //
31702             // If there is an outstanding parse error that we've encountered, but not attached to
31703             // some node, then we cannot get a node from the old source tree.  This is because we
31704             // want to mark the next node we encounter as being unusable.
31705             //
31706             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
31707             // on it (or its leftmost child) as having the error.  For now though, being conservative
31708             // is nice and likely won't ever affect perf.
31709             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
31710                 return undefined;
31711             }
31712             var node = syntaxCursor.currentNode(scanner.getStartPos());
31713             // Can't reuse a missing node.
31714             // Can't reuse a node that intersected the change range.
31715             // Can't reuse a node that contains a parse error.  This is necessary so that we
31716             // produce the same set of errors again.
31717             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
31718                 return undefined;
31719             }
31720             // We can only reuse a node if it was parsed under the same strict mode that we're
31721             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
31722             // the user added 'using strict' at the top of the file, then we can't use that node
31723             // again as the presence of strict mode may cause us to parse the tokens in the file
31724             // differently.
31725             //
31726             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
31727             // are unaffected by strict mode.  It's just the parser will decide what to do with it
31728             // differently depending on what mode it is in.
31729             //
31730             // This also applies to all our other context flags as well.
31731             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
31732             if (nodeContextFlags !== contextFlags) {
31733                 return undefined;
31734             }
31735             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
31736             // in the current list parsing context that we're currently at.
31737             if (!canReuseNode(node, parsingContext)) {
31738                 return undefined;
31739             }
31740             if (node.jsDocCache) {
31741                 // jsDocCache may include tags from parent nodes, which might have been modified.
31742                 node.jsDocCache = undefined;
31743             }
31744             return node;
31745         }
31746         function consumeNode(node) {
31747             // Move the scanner so it is after the node we just consumed.
31748             scanner.setTextPos(node.end);
31749             nextToken();
31750             return node;
31751         }
31752         function isReusableParsingContext(parsingContext) {
31753             switch (parsingContext) {
31754                 case 5 /* ClassMembers */:
31755                 case 2 /* SwitchClauses */:
31756                 case 0 /* SourceElements */:
31757                 case 1 /* BlockStatements */:
31758                 case 3 /* SwitchClauseStatements */:
31759                 case 6 /* EnumMembers */:
31760                 case 4 /* TypeMembers */:
31761                 case 8 /* VariableDeclarations */:
31762                 case 17 /* JSDocParameters */:
31763                 case 16 /* Parameters */:
31764                     return true;
31765             }
31766             return false;
31767         }
31768         function canReuseNode(node, parsingContext) {
31769             switch (parsingContext) {
31770                 case 5 /* ClassMembers */:
31771                     return isReusableClassMember(node);
31772                 case 2 /* SwitchClauses */:
31773                     return isReusableSwitchClause(node);
31774                 case 0 /* SourceElements */:
31775                 case 1 /* BlockStatements */:
31776                 case 3 /* SwitchClauseStatements */:
31777                     return isReusableStatement(node);
31778                 case 6 /* EnumMembers */:
31779                     return isReusableEnumMember(node);
31780                 case 4 /* TypeMembers */:
31781                     return isReusableTypeMember(node);
31782                 case 8 /* VariableDeclarations */:
31783                     return isReusableVariableDeclaration(node);
31784                 case 17 /* JSDocParameters */:
31785                 case 16 /* Parameters */:
31786                     return isReusableParameter(node);
31787                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
31788                 // you can do so safely.  Danger areas involve nodes that may involve speculative
31789                 // parsing.  If speculative parsing is involved with the node, then the range the
31790                 // parser reached while looking ahead might be in the edited range (see the example
31791                 // in canReuseVariableDeclaratorNode for a good case of this).
31792                 // case ParsingContext.HeritageClauses:
31793                 // This would probably be safe to reuse.  There is no speculative parsing with
31794                 // heritage clauses.
31795                 // case ParsingContext.TypeParameters:
31796                 // This would probably be safe to reuse.  There is no speculative parsing with
31797                 // type parameters.  Note that that's because type *parameters* only occur in
31798                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
31799                 // *expression* contexts.
31800                 // case ParsingContext.TupleElementTypes:
31801                 // This would probably be safe to reuse.  There is no speculative parsing with
31802                 // tuple types.
31803                 // Technically, type argument list types are probably safe to reuse.  While
31804                 // speculative parsing is involved with them (since type argument lists are only
31805                 // produced from speculative parsing a < as a type argument list), we only have
31806                 // the types because speculative parsing succeeded.  Thus, the lookahead never
31807                 // went past the end of the list and rewound.
31808                 // case ParsingContext.TypeArguments:
31809                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
31810                 // need a large amount of lookahead, and we should not reuse them as they may
31811                 // have actually intersected the edit.
31812                 // case ParsingContext.ArgumentExpressions:
31813                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
31814                 // cases.  i.e. a property assignment may end with an expression, and thus might
31815                 // have lookahead far beyond it's old node.
31816                 // case ParsingContext.ObjectLiteralMembers:
31817                 // This is probably not safe to reuse.  There can be speculative parsing with
31818                 // type names in a heritage clause.  There can be generic names in the type
31819                 // name list, and there can be left hand side expressions (which can have type
31820                 // arguments.)
31821                 // case ParsingContext.HeritageClauseElement:
31822                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
31823                 // on any given element. Same for children.
31824                 // case ParsingContext.JsxAttributes:
31825                 // case ParsingContext.JsxChildren:
31826             }
31827             return false;
31828         }
31829         function isReusableClassMember(node) {
31830             if (node) {
31831                 switch (node.kind) {
31832                     case 170 /* Constructor */:
31833                     case 175 /* IndexSignature */:
31834                     case 171 /* GetAccessor */:
31835                     case 172 /* SetAccessor */:
31836                     case 166 /* PropertyDeclaration */:
31837                     case 233 /* SemicolonClassElement */:
31838                         return true;
31839                     case 168 /* MethodDeclaration */:
31840                         // Method declarations are not necessarily reusable.  An object-literal
31841                         // may have a method calls "constructor(...)" and we must reparse that
31842                         // into an actual .ConstructorDeclaration.
31843                         var methodDeclaration = node;
31844                         var nameIsConstructor = methodDeclaration.name.kind === 79 /* Identifier */ &&
31845                             methodDeclaration.name.originalKeywordKind === 134 /* ConstructorKeyword */;
31846                         return !nameIsConstructor;
31847                 }
31848             }
31849             return false;
31850         }
31851         function isReusableSwitchClause(node) {
31852             if (node) {
31853                 switch (node.kind) {
31854                     case 288 /* CaseClause */:
31855                     case 289 /* DefaultClause */:
31856                         return true;
31857                 }
31858             }
31859             return false;
31860         }
31861         function isReusableStatement(node) {
31862             if (node) {
31863                 switch (node.kind) {
31864                     case 255 /* FunctionDeclaration */:
31865                     case 236 /* VariableStatement */:
31866                     case 234 /* Block */:
31867                     case 238 /* IfStatement */:
31868                     case 237 /* ExpressionStatement */:
31869                     case 250 /* ThrowStatement */:
31870                     case 246 /* ReturnStatement */:
31871                     case 248 /* SwitchStatement */:
31872                     case 245 /* BreakStatement */:
31873                     case 244 /* ContinueStatement */:
31874                     case 242 /* ForInStatement */:
31875                     case 243 /* ForOfStatement */:
31876                     case 241 /* ForStatement */:
31877                     case 240 /* WhileStatement */:
31878                     case 247 /* WithStatement */:
31879                     case 235 /* EmptyStatement */:
31880                     case 251 /* TryStatement */:
31881                     case 249 /* LabeledStatement */:
31882                     case 239 /* DoStatement */:
31883                     case 252 /* DebuggerStatement */:
31884                     case 265 /* ImportDeclaration */:
31885                     case 264 /* ImportEqualsDeclaration */:
31886                     case 271 /* ExportDeclaration */:
31887                     case 270 /* ExportAssignment */:
31888                     case 260 /* ModuleDeclaration */:
31889                     case 256 /* ClassDeclaration */:
31890                     case 257 /* InterfaceDeclaration */:
31891                     case 259 /* EnumDeclaration */:
31892                     case 258 /* TypeAliasDeclaration */:
31893                         return true;
31894                 }
31895             }
31896             return false;
31897         }
31898         function isReusableEnumMember(node) {
31899             return node.kind === 297 /* EnumMember */;
31900         }
31901         function isReusableTypeMember(node) {
31902             if (node) {
31903                 switch (node.kind) {
31904                     case 174 /* ConstructSignature */:
31905                     case 167 /* MethodSignature */:
31906                     case 175 /* IndexSignature */:
31907                     case 165 /* PropertySignature */:
31908                     case 173 /* CallSignature */:
31909                         return true;
31910                 }
31911             }
31912             return false;
31913         }
31914         function isReusableVariableDeclaration(node) {
31915             if (node.kind !== 253 /* VariableDeclaration */) {
31916                 return false;
31917             }
31918             // Very subtle incremental parsing bug.  Consider the following code:
31919             //
31920             //      let v = new List < A, B
31921             //
31922             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
31923             // on one side and "B" on the other. If you then change that to:
31924             //
31925             //      let v = new List < A, B >()
31926             //
31927             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
31928             // start reparsing at "B" and we completely fail to handle this properly.
31929             //
31930             // In order to prevent this, we do not allow a variable declarator to be reused if it
31931             // has an initializer.
31932             var variableDeclarator = node;
31933             return variableDeclarator.initializer === undefined;
31934         }
31935         function isReusableParameter(node) {
31936             if (node.kind !== 163 /* Parameter */) {
31937                 return false;
31938             }
31939             // See the comment in isReusableVariableDeclaration for why we do this.
31940             var parameter = node;
31941             return parameter.initializer === undefined;
31942         }
31943         // Returns true if we should abort parsing.
31944         function abortParsingListOrMoveToNextToken(kind) {
31945             parsingContextErrors(kind);
31946             if (isInSomeParsingContext()) {
31947                 return true;
31948             }
31949             nextToken();
31950             return false;
31951         }
31952         function parsingContextErrors(context) {
31953             switch (context) {
31954                 case 0 /* SourceElements */:
31955                     return token() === 88 /* DefaultKeyword */
31956                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(93 /* ExportKeyword */))
31957                         : parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
31958                 case 1 /* BlockStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
31959                 case 2 /* SwitchClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.case_or_default_expected);
31960                 case 3 /* SwitchClauseStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Statement_expected);
31961                 case 18 /* RestProperties */: // fallthrough
31962                 case 4 /* TypeMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_or_signature_expected);
31963                 case 5 /* ClassMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected);
31964                 case 6 /* EnumMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Enum_member_expected);
31965                 case 7 /* HeritageClauseElement */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_expected);
31966                 case 8 /* VariableDeclarations */:
31967                     return ts.isKeyword(token())
31968                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, ts.tokenToString(token()))
31969                         : parseErrorAtCurrentToken(ts.Diagnostics.Variable_declaration_expected);
31970                 case 9 /* ObjectBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_destructuring_pattern_expected);
31971                 case 10 /* ArrayBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Array_element_destructuring_pattern_expected);
31972                 case 11 /* ArgumentExpressions */: return parseErrorAtCurrentToken(ts.Diagnostics.Argument_expression_expected);
31973                 case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected);
31974                 case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected);
31975                 case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
31976                 case 16 /* Parameters */:
31977                     return ts.isKeyword(token())
31978                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token()))
31979                         : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
31980                 case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected);
31981                 case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected);
31982                 case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected);
31983                 case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_expected);
31984                 case 23 /* ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
31985                 case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
31986                 case 14 /* JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
31987                 default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);`
31988             }
31989         }
31990         // Parses a comma-delimited list of elements
31991         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
31992             var saveParsingContext = parsingContext;
31993             parsingContext |= 1 << kind;
31994             var list = [];
31995             var listPos = getNodePos();
31996             var commaStart = -1; // Meaning the previous token was not a comma
31997             while (true) {
31998                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
31999                     var startPos = scanner.getStartPos();
32000                     list.push(parseListElement(kind, parseElement));
32001                     commaStart = scanner.getTokenPos();
32002                     if (parseOptional(27 /* CommaToken */)) {
32003                         // No need to check for a zero length node since we know we parsed a comma
32004                         continue;
32005                     }
32006                     commaStart = -1; // Back to the state where the last token was not a comma
32007                     if (isListTerminator(kind)) {
32008                         break;
32009                     }
32010                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
32011                     // out a comma so we give a good error message.
32012                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
32013                     // If the token was a semicolon, and the caller allows that, then skip it and
32014                     // continue.  This ensures we get back on track and don't result in tons of
32015                     // parse errors.  For example, this can happen when people do things like use
32016                     // a semicolon to delimit object literal members.   Note: we'll have already
32017                     // reported an error when we called parseExpected above.
32018                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
32019                         nextToken();
32020                     }
32021                     if (startPos === scanner.getStartPos()) {
32022                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
32023                         // Consume a token to advance the parser in some way and avoid an infinite loop
32024                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
32025                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
32026                         nextToken();
32027                     }
32028                     continue;
32029                 }
32030                 if (isListTerminator(kind)) {
32031                     break;
32032                 }
32033                 if (abortParsingListOrMoveToNextToken(kind)) {
32034                     break;
32035                 }
32036             }
32037             parsingContext = saveParsingContext;
32038             // Recording the trailing comma is deliberately done after the previous
32039             // loop, and not just if we see a list terminator. This is because the list
32040             // may have ended incorrectly, but it is still important to know if there
32041             // was a trailing comma.
32042             // Check if the last token was a comma.
32043             // Always preserve a trailing comma by marking it on the NodeArray
32044             return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0);
32045         }
32046         function getExpectedCommaDiagnostic(kind) {
32047             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
32048         }
32049         function createMissingList() {
32050             var list = createNodeArray([], getNodePos());
32051             list.isMissingList = true;
32052             return list;
32053         }
32054         function isMissingList(arr) {
32055             return !!arr.isMissingList;
32056         }
32057         function parseBracketedList(kind, parseElement, open, close) {
32058             if (parseExpected(open)) {
32059                 var result = parseDelimitedList(kind, parseElement);
32060                 parseExpected(close);
32061                 return result;
32062             }
32063             return createMissingList();
32064         }
32065         function parseEntityName(allowReservedWords, diagnosticMessage) {
32066             var pos = getNodePos();
32067             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
32068             var dotPos = getNodePos();
32069             while (parseOptional(24 /* DotToken */)) {
32070                 if (token() === 29 /* LessThanToken */) {
32071                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
32072                     entity.jsdocDotPos = dotPos;
32073                     break;
32074                 }
32075                 dotPos = getNodePos();
32076                 entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
32077             }
32078             return entity;
32079         }
32080         function createQualifiedName(entity, name) {
32081             return finishNode(factory.createQualifiedName(entity, name), entity.pos);
32082         }
32083         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
32084             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
32085             // However, often we'll encounter this in error situations when the identifier or keyword
32086             // is actually starting another valid construct.
32087             //
32088             // So, we check for the following specific case:
32089             //
32090             //      name.
32091             //      identifierOrKeyword identifierNameOrKeyword
32092             //
32093             // Note: the newlines are important here.  For example, if that above code
32094             // were rewritten into:
32095             //
32096             //      name.identifierOrKeyword
32097             //      identifierNameOrKeyword
32098             //
32099             // Then we would consider it valid.  That's because ASI would take effect and
32100             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
32101             // In the first case though, ASI will not take effect because there is not a
32102             // line terminator after the identifier or keyword.
32103             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
32104                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
32105                 if (matchesPattern) {
32106                     // Report that we need an identifier.  However, report it right after the dot,
32107                     // and not on the next token.  This is because the next token might actually
32108                     // be an identifier and the error would be quite confusing.
32109                     return createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
32110                 }
32111             }
32112             if (token() === 80 /* PrivateIdentifier */) {
32113                 var node = parsePrivateIdentifier();
32114                 return allowPrivateIdentifiers ? node : createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
32115             }
32116             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
32117         }
32118         function parseTemplateSpans(isTaggedTemplate) {
32119             var pos = getNodePos();
32120             var list = [];
32121             var node;
32122             do {
32123                 node = parseTemplateSpan(isTaggedTemplate);
32124                 list.push(node);
32125             } while (node.literal.kind === 16 /* TemplateMiddle */);
32126             return createNodeArray(list, pos);
32127         }
32128         function parseTemplateExpression(isTaggedTemplate) {
32129             var pos = getNodePos();
32130             return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
32131         }
32132         function parseTemplateType() {
32133             var pos = getNodePos();
32134             return finishNode(factory.createTemplateLiteralType(parseTemplateHead(/*isTaggedTemplate*/ false), parseTemplateTypeSpans()), pos);
32135         }
32136         function parseTemplateTypeSpans() {
32137             var pos = getNodePos();
32138             var list = [];
32139             var node;
32140             do {
32141                 node = parseTemplateTypeSpan();
32142                 list.push(node);
32143             } while (node.literal.kind === 16 /* TemplateMiddle */);
32144             return createNodeArray(list, pos);
32145         }
32146         function parseTemplateTypeSpan() {
32147             var pos = getNodePos();
32148             return finishNode(factory.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos);
32149         }
32150         function parseLiteralOfTemplateSpan(isTaggedTemplate) {
32151             if (token() === 19 /* CloseBraceToken */) {
32152                 reScanTemplateToken(isTaggedTemplate);
32153                 return parseTemplateMiddleOrTemplateTail();
32154             }
32155             else {
32156                 // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
32157                 return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
32158             }
32159         }
32160         function parseTemplateSpan(isTaggedTemplate) {
32161             var pos = getNodePos();
32162             return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
32163         }
32164         function parseLiteralNode() {
32165             return parseLiteralLikeNode(token());
32166         }
32167         function parseTemplateHead(isTaggedTemplate) {
32168             if (isTaggedTemplate) {
32169                 reScanTemplateHeadOrNoSubstitutionTemplate();
32170             }
32171             var fragment = parseLiteralLikeNode(token());
32172             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
32173             return fragment;
32174         }
32175         function parseTemplateMiddleOrTemplateTail() {
32176             var fragment = parseLiteralLikeNode(token());
32177             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
32178             return fragment;
32179         }
32180         function getTemplateLiteralRawText(kind) {
32181             var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
32182             var tokenText = scanner.getTokenText();
32183             return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
32184         }
32185         function parseLiteralLikeNode(kind) {
32186             var pos = getNodePos();
32187             var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
32188                 // Octal literals are not allowed in strict mode or ES5
32189                 // Note that theoretically the following condition would hold true literals like 009,
32190                 // which is not octal. But because of how the scanner separates the tokens, we would
32191                 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
32192                 // We also do not need to check for negatives because any prefix operator would be part of a
32193                 // parent unary expression.
32194                 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
32195                     kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
32196                         ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
32197                             ts.Debug.fail();
32198             if (scanner.hasExtendedUnicodeEscape()) {
32199                 node.hasExtendedUnicodeEscape = true;
32200             }
32201             if (scanner.isUnterminated()) {
32202                 node.isUnterminated = true;
32203             }
32204             nextToken();
32205             return finishNode(node, pos);
32206         }
32207         // TYPES
32208         function parseEntityNameOfTypeReference() {
32209             return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
32210         }
32211         function parseTypeArgumentsOfTypeReference() {
32212             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
32213                 return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
32214             }
32215         }
32216         function parseTypeReference() {
32217             var pos = getNodePos();
32218             return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
32219         }
32220         // If true, we should abort parsing an error function.
32221         function typeHasArrowFunctionBlockingParseError(node) {
32222             switch (node.kind) {
32223                 case 177 /* TypeReference */:
32224                     return ts.nodeIsMissing(node.typeName);
32225                 case 178 /* FunctionType */:
32226                 case 179 /* ConstructorType */: {
32227                     var _a = node, parameters = _a.parameters, type = _a.type;
32228                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
32229                 }
32230                 case 190 /* ParenthesizedType */:
32231                     return typeHasArrowFunctionBlockingParseError(node.type);
32232                 default:
32233                     return false;
32234             }
32235         }
32236         function parseThisTypePredicate(lhs) {
32237             nextToken();
32238             return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
32239         }
32240         function parseThisTypeNode() {
32241             var pos = getNodePos();
32242             nextToken();
32243             return finishNode(factory.createThisTypeNode(), pos);
32244         }
32245         function parseJSDocAllType() {
32246             var pos = getNodePos();
32247             nextToken();
32248             return finishNode(factory.createJSDocAllType(), pos);
32249         }
32250         function parseJSDocNonNullableType() {
32251             var pos = getNodePos();
32252             nextToken();
32253             return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
32254         }
32255         function parseJSDocUnknownOrNullableType() {
32256             var pos = getNodePos();
32257             // skip the ?
32258             nextToken();
32259             // Need to lookahead to decide if this is a nullable or unknown type.
32260             // Here are cases where we'll pick the unknown type:
32261             //
32262             //      Foo(?,
32263             //      { a: ? }
32264             //      Foo(?)
32265             //      Foo<?>
32266             //      Foo(?=
32267             //      (?|
32268             if (token() === 27 /* CommaToken */ ||
32269                 token() === 19 /* CloseBraceToken */ ||
32270                 token() === 21 /* CloseParenToken */ ||
32271                 token() === 31 /* GreaterThanToken */ ||
32272                 token() === 63 /* EqualsToken */ ||
32273                 token() === 51 /* BarToken */) {
32274                 return finishNode(factory.createJSDocUnknownType(), pos);
32275             }
32276             else {
32277                 return finishNode(factory.createJSDocNullableType(parseType()), pos);
32278             }
32279         }
32280         function parseJSDocFunctionType() {
32281             var pos = getNodePos();
32282             var hasJSDoc = hasPrecedingJSDocComment();
32283             if (lookAhead(nextTokenIsOpenParen)) {
32284                 nextToken();
32285                 var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
32286                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32287                 return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
32288             }
32289             return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
32290         }
32291         function parseJSDocParameter() {
32292             var pos = getNodePos();
32293             var name;
32294             if (token() === 108 /* ThisKeyword */ || token() === 103 /* NewKeyword */) {
32295                 name = parseIdentifierName();
32296                 parseExpected(58 /* ColonToken */);
32297             }
32298             return finishNode(factory.createParameterDeclaration(
32299             /*decorators*/ undefined, 
32300             /*modifiers*/ undefined, 
32301             /*dotDotDotToken*/ undefined, 
32302             // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
32303             name, 
32304             /*questionToken*/ undefined, parseJSDocType(), 
32305             /*initializer*/ undefined), pos);
32306         }
32307         function parseJSDocType() {
32308             scanner.setInJSDocType(true);
32309             var pos = getNodePos();
32310             if (parseOptional(141 /* ModuleKeyword */)) {
32311                 // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
32312                 var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
32313                 terminate: while (true) {
32314                     switch (token()) {
32315                         case 19 /* CloseBraceToken */:
32316                         case 1 /* EndOfFileToken */:
32317                         case 27 /* CommaToken */:
32318                         case 5 /* WhitespaceTrivia */:
32319                             break terminate;
32320                         default:
32321                             nextTokenJSDoc();
32322                     }
32323                 }
32324                 scanner.setInJSDocType(false);
32325                 return finishNode(moduleTag, pos);
32326             }
32327             var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
32328             var type = parseTypeOrTypePredicate();
32329             scanner.setInJSDocType(false);
32330             if (hasDotDotDot) {
32331                 type = finishNode(factory.createJSDocVariadicType(type), pos);
32332             }
32333             if (token() === 63 /* EqualsToken */) {
32334                 nextToken();
32335                 return finishNode(factory.createJSDocOptionalType(type), pos);
32336             }
32337             return type;
32338         }
32339         function parseTypeQuery() {
32340             var pos = getNodePos();
32341             parseExpected(112 /* TypeOfKeyword */);
32342             return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
32343         }
32344         function parseTypeParameter() {
32345             var pos = getNodePos();
32346             var name = parseIdentifier();
32347             var constraint;
32348             var expression;
32349             if (parseOptional(94 /* ExtendsKeyword */)) {
32350                 // It's not uncommon for people to write improper constraints to a generic.  If the
32351                 // user writes a constraint that is an expression and not an actual type, then parse
32352                 // it out as an expression (so we can recover well), but report that a type is needed
32353                 // instead.
32354                 if (isStartOfType() || !isStartOfExpression()) {
32355                     constraint = parseType();
32356                 }
32357                 else {
32358                     // It was not a type, and it looked like an expression.  Parse out an expression
32359                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
32360                     // and not parseExpression here.  If the user has:
32361                     //
32362                     //      <T extends "">
32363                     //
32364                     // We do *not* want to consume the `>` as we're consuming the expression for "".
32365                     expression = parseUnaryExpressionOrHigher();
32366                 }
32367             }
32368             var defaultType = parseOptional(63 /* EqualsToken */) ? parseType() : undefined;
32369             var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
32370             node.expression = expression;
32371             return finishNode(node, pos);
32372         }
32373         function parseTypeParameters() {
32374             if (token() === 29 /* LessThanToken */) {
32375                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
32376             }
32377         }
32378         function isStartOfParameter(isJSDocParameter) {
32379             return token() === 25 /* DotDotDotToken */ ||
32380                 isBindingIdentifierOrPrivateIdentifierOrPattern() ||
32381                 ts.isModifierKind(token()) ||
32382                 token() === 59 /* AtToken */ ||
32383                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
32384         }
32385         function parseNameOfParameter(modifiers) {
32386             // FormalParameter [Yield,Await]:
32387             //      BindingElement[?Yield,?Await]
32388             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
32389             if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && ts.isModifierKind(token())) {
32390                 // in cases like
32391                 // 'use strict'
32392                 // function foo(static)
32393                 // isParameter('static') === true, because of isModifier('static')
32394                 // however 'static' is not a legal identifier in a strict mode.
32395                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
32396                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
32397                 // to avoid this we'll advance cursor to the next token.
32398                 nextToken();
32399             }
32400             return name;
32401         }
32402         function parseParameterInOuterAwaitContext() {
32403             return parseParameterWorker(/*inOuterAwaitContext*/ true);
32404         }
32405         function parseParameter() {
32406             return parseParameterWorker(/*inOuterAwaitContext*/ false);
32407         }
32408         function parseParameterWorker(inOuterAwaitContext) {
32409             var pos = getNodePos();
32410             var hasJSDoc = hasPrecedingJSDocComment();
32411             // FormalParameter [Yield,Await]:
32412             //      BindingElement[?Yield,?Await]
32413             // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
32414             var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
32415             if (token() === 108 /* ThisKeyword */) {
32416                 var node_1 = factory.createParameterDeclaration(decorators, 
32417                 /*modifiers*/ undefined, 
32418                 /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), 
32419                 /*questionToken*/ undefined, parseTypeAnnotation(), 
32420                 /*initializer*/ undefined);
32421                 if (decorators) {
32422                     parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters);
32423                 }
32424                 return withJSDoc(finishNode(node_1, pos), hasJSDoc);
32425             }
32426             var savedTopLevel = topLevel;
32427             topLevel = false;
32428             var modifiers = parseModifiers();
32429             var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
32430             topLevel = savedTopLevel;
32431             return node;
32432         }
32433         function parseReturnType(returnToken, isType) {
32434             if (shouldParseReturnType(returnToken, isType)) {
32435                 return parseTypeOrTypePredicate();
32436             }
32437         }
32438         function shouldParseReturnType(returnToken, isType) {
32439             if (returnToken === 38 /* EqualsGreaterThanToken */) {
32440                 parseExpected(returnToken);
32441                 return true;
32442             }
32443             else if (parseOptional(58 /* ColonToken */)) {
32444                 return true;
32445             }
32446             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
32447                 // This is easy to get backward, especially in type contexts, so parse the type anyway
32448                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
32449                 nextToken();
32450                 return true;
32451             }
32452             return false;
32453         }
32454         function parseParametersWorker(flags) {
32455             // FormalParameters [Yield,Await]: (modified)
32456             //      [empty]
32457             //      FormalParameterList[?Yield,Await]
32458             //
32459             // FormalParameter[Yield,Await]: (modified)
32460             //      BindingElement[?Yield,Await]
32461             //
32462             // BindingElement [Yield,Await]: (modified)
32463             //      SingleNameBinding[?Yield,?Await]
32464             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
32465             //
32466             // SingleNameBinding [Yield,Await]:
32467             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
32468             var savedYieldContext = inYieldContext();
32469             var savedAwaitContext = inAwaitContext();
32470             setYieldContext(!!(flags & 1 /* Yield */));
32471             setAwaitContext(!!(flags & 2 /* Await */));
32472             var parameters = flags & 32 /* JSDoc */ ?
32473                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
32474                 parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
32475             setYieldContext(savedYieldContext);
32476             setAwaitContext(savedAwaitContext);
32477             return parameters;
32478         }
32479         function parseParameters(flags) {
32480             // FormalParameters [Yield,Await]: (modified)
32481             //      [empty]
32482             //      FormalParameterList[?Yield,Await]
32483             //
32484             // FormalParameter[Yield,Await]: (modified)
32485             //      BindingElement[?Yield,Await]
32486             //
32487             // BindingElement [Yield,Await]: (modified)
32488             //      SingleNameBinding[?Yield,?Await]
32489             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
32490             //
32491             // SingleNameBinding [Yield,Await]:
32492             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
32493             if (!parseExpected(20 /* OpenParenToken */)) {
32494                 return createMissingList();
32495             }
32496             var parameters = parseParametersWorker(flags);
32497             parseExpected(21 /* CloseParenToken */);
32498             return parameters;
32499         }
32500         function parseTypeMemberSemicolon() {
32501             // We allow type members to be separated by commas or (possibly ASI) semicolons.
32502             // First check if it was a comma.  If so, we're done with the member.
32503             if (parseOptional(27 /* CommaToken */)) {
32504                 return;
32505             }
32506             // Didn't have a comma.  We must have a (possible ASI) semicolon.
32507             parseSemicolon();
32508         }
32509         function parseSignatureMember(kind) {
32510             var pos = getNodePos();
32511             var hasJSDoc = hasPrecedingJSDocComment();
32512             if (kind === 174 /* ConstructSignature */) {
32513                 parseExpected(103 /* NewKeyword */);
32514             }
32515             var typeParameters = parseTypeParameters();
32516             var parameters = parseParameters(4 /* Type */);
32517             var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
32518             parseTypeMemberSemicolon();
32519             var node = kind === 173 /* CallSignature */
32520                 ? factory.createCallSignature(typeParameters, parameters, type)
32521                 : factory.createConstructSignature(typeParameters, parameters, type);
32522             return withJSDoc(finishNode(node, pos), hasJSDoc);
32523         }
32524         function isIndexSignature() {
32525             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
32526         }
32527         function isUnambiguouslyIndexSignature() {
32528             // The only allowed sequence is:
32529             //
32530             //   [id:
32531             //
32532             // However, for error recovery, we also check the following cases:
32533             //
32534             //   [...
32535             //   [id,
32536             //   [id?,
32537             //   [id?:
32538             //   [id?]
32539             //   [public id
32540             //   [private id
32541             //   [protected id
32542             //   []
32543             //
32544             nextToken();
32545             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
32546                 return true;
32547             }
32548             if (ts.isModifierKind(token())) {
32549                 nextToken();
32550                 if (isIdentifier()) {
32551                     return true;
32552                 }
32553             }
32554             else if (!isIdentifier()) {
32555                 return false;
32556             }
32557             else {
32558                 // Skip the identifier
32559                 nextToken();
32560             }
32561             // A colon signifies a well formed indexer
32562             // A comma should be a badly formed indexer because comma expressions are not allowed
32563             // in computed properties.
32564             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
32565                 return true;
32566             }
32567             // Question mark could be an indexer with an optional property,
32568             // or it could be a conditional expression in a computed property.
32569             if (token() !== 57 /* QuestionToken */) {
32570                 return false;
32571             }
32572             // If any of the following tokens are after the question mark, it cannot
32573             // be a conditional expression, so treat it as an indexer.
32574             nextToken();
32575             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
32576         }
32577         function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
32578             var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
32579             var type = parseTypeAnnotation();
32580             parseTypeMemberSemicolon();
32581             var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
32582             return withJSDoc(finishNode(node, pos), hasJSDoc);
32583         }
32584         function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
32585             var name = parsePropertyName();
32586             var questionToken = parseOptionalToken(57 /* QuestionToken */);
32587             var node;
32588             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32589                 // Method signatures don't exist in expression contexts.  So they have neither
32590                 // [Yield] nor [Await]
32591                 var typeParameters = parseTypeParameters();
32592                 var parameters = parseParameters(4 /* Type */);
32593                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
32594                 node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
32595             }
32596             else {
32597                 var type = parseTypeAnnotation();
32598                 node = factory.createPropertySignature(modifiers, name, questionToken, type);
32599                 // Although type literal properties cannot not have initializers, we attempt
32600                 // to parse an initializer so we can report in the checker that an interface
32601                 // property or type literal property cannot have an initializer.
32602                 if (token() === 63 /* EqualsToken */)
32603                     node.initializer = parseInitializer();
32604             }
32605             parseTypeMemberSemicolon();
32606             return withJSDoc(finishNode(node, pos), hasJSDoc);
32607         }
32608         function isTypeMemberStart() {
32609             // Return true if we have the start of a signature member
32610             if (token() === 20 /* OpenParenToken */ ||
32611                 token() === 29 /* LessThanToken */ ||
32612                 token() === 136 /* GetKeyword */ ||
32613                 token() === 148 /* SetKeyword */) {
32614                 return true;
32615             }
32616             var idToken = false;
32617             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
32618             while (ts.isModifierKind(token())) {
32619                 idToken = true;
32620                 nextToken();
32621             }
32622             // Index signatures and computed property names are type members
32623             if (token() === 22 /* OpenBracketToken */) {
32624                 return true;
32625             }
32626             // Try to get the first property-like token following all modifiers
32627             if (isLiteralPropertyName()) {
32628                 idToken = true;
32629                 nextToken();
32630             }
32631             // If we were able to get any potential identifier, check that it is
32632             // the start of a member declaration
32633             if (idToken) {
32634                 return token() === 20 /* OpenParenToken */ ||
32635                     token() === 29 /* LessThanToken */ ||
32636                     token() === 57 /* QuestionToken */ ||
32637                     token() === 58 /* ColonToken */ ||
32638                     token() === 27 /* CommaToken */ ||
32639                     canParseSemicolon();
32640             }
32641             return false;
32642         }
32643         function parseTypeMember() {
32644             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32645                 return parseSignatureMember(173 /* CallSignature */);
32646             }
32647             if (token() === 103 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
32648                 return parseSignatureMember(174 /* ConstructSignature */);
32649             }
32650             var pos = getNodePos();
32651             var hasJSDoc = hasPrecedingJSDocComment();
32652             var modifiers = parseModifiers();
32653             if (parseContextualModifier(136 /* GetKeyword */)) {
32654                 return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 171 /* GetAccessor */);
32655             }
32656             if (parseContextualModifier(148 /* SetKeyword */)) {
32657                 return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SetAccessor */);
32658             }
32659             if (isIndexSignature()) {
32660                 return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
32661             }
32662             return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
32663         }
32664         function nextTokenIsOpenParenOrLessThan() {
32665             nextToken();
32666             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
32667         }
32668         function nextTokenIsDot() {
32669             return nextToken() === 24 /* DotToken */;
32670         }
32671         function nextTokenIsOpenParenOrLessThanOrDot() {
32672             switch (nextToken()) {
32673                 case 20 /* OpenParenToken */:
32674                 case 29 /* LessThanToken */:
32675                 case 24 /* DotToken */:
32676                     return true;
32677             }
32678             return false;
32679         }
32680         function parseTypeLiteral() {
32681             var pos = getNodePos();
32682             return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
32683         }
32684         function parseObjectTypeMembers() {
32685             var members;
32686             if (parseExpected(18 /* OpenBraceToken */)) {
32687                 members = parseList(4 /* TypeMembers */, parseTypeMember);
32688                 parseExpected(19 /* CloseBraceToken */);
32689             }
32690             else {
32691                 members = createMissingList();
32692             }
32693             return members;
32694         }
32695         function isStartOfMappedType() {
32696             nextToken();
32697             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
32698                 return nextToken() === 144 /* ReadonlyKeyword */;
32699             }
32700             if (token() === 144 /* ReadonlyKeyword */) {
32701                 nextToken();
32702             }
32703             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 101 /* InKeyword */;
32704         }
32705         function parseMappedTypeParameter() {
32706             var pos = getNodePos();
32707             var name = parseIdentifierName();
32708             parseExpected(101 /* InKeyword */);
32709             var type = parseType();
32710             return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
32711         }
32712         function parseMappedType() {
32713             var pos = getNodePos();
32714             parseExpected(18 /* OpenBraceToken */);
32715             var readonlyToken;
32716             if (token() === 144 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
32717                 readonlyToken = parseTokenNode();
32718                 if (readonlyToken.kind !== 144 /* ReadonlyKeyword */) {
32719                     parseExpected(144 /* ReadonlyKeyword */);
32720                 }
32721             }
32722             parseExpected(22 /* OpenBracketToken */);
32723             var typeParameter = parseMappedTypeParameter();
32724             var nameType = parseOptional(127 /* AsKeyword */) ? parseType() : undefined;
32725             parseExpected(23 /* CloseBracketToken */);
32726             var questionToken;
32727             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
32728                 questionToken = parseTokenNode();
32729                 if (questionToken.kind !== 57 /* QuestionToken */) {
32730                     parseExpected(57 /* QuestionToken */);
32731                 }
32732             }
32733             var type = parseTypeAnnotation();
32734             parseSemicolon();
32735             var members = parseList(4 /* TypeMembers */, parseTypeMember);
32736             parseExpected(19 /* CloseBraceToken */);
32737             return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos);
32738         }
32739         function parseTupleElementType() {
32740             var pos = getNodePos();
32741             if (parseOptional(25 /* DotDotDotToken */)) {
32742                 return finishNode(factory.createRestTypeNode(parseType()), pos);
32743             }
32744             var type = parseType();
32745             if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
32746                 var node = factory.createOptionalTypeNode(type.type);
32747                 ts.setTextRange(node, type);
32748                 node.flags = type.flags;
32749                 return node;
32750             }
32751             return type;
32752         }
32753         function isNextTokenColonOrQuestionColon() {
32754             return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
32755         }
32756         function isTupleElementName() {
32757             if (token() === 25 /* DotDotDotToken */) {
32758                 return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
32759             }
32760             return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
32761         }
32762         function parseTupleElementNameOrTupleElementType() {
32763             if (lookAhead(isTupleElementName)) {
32764                 var pos = getNodePos();
32765                 var hasJSDoc = hasPrecedingJSDocComment();
32766                 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
32767                 var name = parseIdentifierName();
32768                 var questionToken = parseOptionalToken(57 /* QuestionToken */);
32769                 parseExpected(58 /* ColonToken */);
32770                 var type = parseTupleElementType();
32771                 var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
32772                 return withJSDoc(finishNode(node, pos), hasJSDoc);
32773             }
32774             return parseTupleElementType();
32775         }
32776         function parseTupleType() {
32777             var pos = getNodePos();
32778             return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
32779         }
32780         function parseParenthesizedType() {
32781             var pos = getNodePos();
32782             parseExpected(20 /* OpenParenToken */);
32783             var type = parseType();
32784             parseExpected(21 /* CloseParenToken */);
32785             return finishNode(factory.createParenthesizedType(type), pos);
32786         }
32787         function parseModifiersForConstructorType() {
32788             var modifiers;
32789             if (token() === 126 /* AbstractKeyword */) {
32790                 var pos = getNodePos();
32791                 nextToken();
32792                 var modifier = finishNode(factory.createToken(126 /* AbstractKeyword */), pos);
32793                 modifiers = createNodeArray([modifier], pos);
32794             }
32795             return modifiers;
32796         }
32797         function parseFunctionOrConstructorType() {
32798             var pos = getNodePos();
32799             var hasJSDoc = hasPrecedingJSDocComment();
32800             var modifiers = parseModifiersForConstructorType();
32801             var isConstructorType = parseOptional(103 /* NewKeyword */);
32802             var typeParameters = parseTypeParameters();
32803             var parameters = parseParameters(4 /* Type */);
32804             var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
32805             var node = isConstructorType
32806                 ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type)
32807                 : factory.createFunctionTypeNode(typeParameters, parameters, type);
32808             if (!isConstructorType)
32809                 node.modifiers = modifiers;
32810             return withJSDoc(finishNode(node, pos), hasJSDoc);
32811         }
32812         function parseKeywordAndNoDot() {
32813             var node = parseTokenNode();
32814             return token() === 24 /* DotToken */ ? undefined : node;
32815         }
32816         function parseLiteralTypeNode(negative) {
32817             var pos = getNodePos();
32818             if (negative) {
32819                 nextToken();
32820             }
32821             var expression = token() === 110 /* TrueKeyword */ || token() === 95 /* FalseKeyword */ || token() === 104 /* NullKeyword */ ?
32822                 parseTokenNode() :
32823                 parseLiteralLikeNode(token());
32824             if (negative) {
32825                 expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
32826             }
32827             return finishNode(factory.createLiteralTypeNode(expression), pos);
32828         }
32829         function isStartOfTypeOfImportType() {
32830             nextToken();
32831             return token() === 100 /* ImportKeyword */;
32832         }
32833         function parseImportType() {
32834             sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
32835             var pos = getNodePos();
32836             var isTypeOf = parseOptional(112 /* TypeOfKeyword */);
32837             parseExpected(100 /* ImportKeyword */);
32838             parseExpected(20 /* OpenParenToken */);
32839             var type = parseType();
32840             parseExpected(21 /* CloseParenToken */);
32841             var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
32842             var typeArguments = parseTypeArgumentsOfTypeReference();
32843             return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
32844         }
32845         function nextTokenIsNumericOrBigIntLiteral() {
32846             nextToken();
32847             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
32848         }
32849         function parseNonArrayType() {
32850             switch (token()) {
32851                 case 130 /* AnyKeyword */:
32852                 case 154 /* UnknownKeyword */:
32853                 case 149 /* StringKeyword */:
32854                 case 146 /* NumberKeyword */:
32855                 case 157 /* BigIntKeyword */:
32856                 case 150 /* SymbolKeyword */:
32857                 case 133 /* BooleanKeyword */:
32858                 case 152 /* UndefinedKeyword */:
32859                 case 143 /* NeverKeyword */:
32860                 case 147 /* ObjectKeyword */:
32861                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
32862                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
32863                 case 66 /* AsteriskEqualsToken */:
32864                     // If there is '*=', treat it as * followed by postfix =
32865                     scanner.reScanAsteriskEqualsToken();
32866                 // falls through
32867                 case 41 /* AsteriskToken */:
32868                     return parseJSDocAllType();
32869                 case 60 /* QuestionQuestionToken */:
32870                     // If there is '??', treat it as prefix-'?' in JSDoc type.
32871                     scanner.reScanQuestionToken();
32872                 // falls through
32873                 case 57 /* QuestionToken */:
32874                     return parseJSDocUnknownOrNullableType();
32875                 case 98 /* FunctionKeyword */:
32876                     return parseJSDocFunctionType();
32877                 case 53 /* ExclamationToken */:
32878                     return parseJSDocNonNullableType();
32879                 case 14 /* NoSubstitutionTemplateLiteral */:
32880                 case 10 /* StringLiteral */:
32881                 case 8 /* NumericLiteral */:
32882                 case 9 /* BigIntLiteral */:
32883                 case 110 /* TrueKeyword */:
32884                 case 95 /* FalseKeyword */:
32885                 case 104 /* NullKeyword */:
32886                     return parseLiteralTypeNode();
32887                 case 40 /* MinusToken */:
32888                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
32889                 case 114 /* VoidKeyword */:
32890                     return parseTokenNode();
32891                 case 108 /* ThisKeyword */: {
32892                     var thisKeyword = parseThisTypeNode();
32893                     if (token() === 139 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
32894                         return parseThisTypePredicate(thisKeyword);
32895                     }
32896                     else {
32897                         return thisKeyword;
32898                     }
32899                 }
32900                 case 112 /* TypeOfKeyword */:
32901                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
32902                 case 18 /* OpenBraceToken */:
32903                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
32904                 case 22 /* OpenBracketToken */:
32905                     return parseTupleType();
32906                 case 20 /* OpenParenToken */:
32907                     return parseParenthesizedType();
32908                 case 100 /* ImportKeyword */:
32909                     return parseImportType();
32910                 case 128 /* AssertsKeyword */:
32911                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
32912                 case 15 /* TemplateHead */:
32913                     return parseTemplateType();
32914                 default:
32915                     return parseTypeReference();
32916             }
32917         }
32918         function isStartOfType(inStartOfParameter) {
32919             switch (token()) {
32920                 case 130 /* AnyKeyword */:
32921                 case 154 /* UnknownKeyword */:
32922                 case 149 /* StringKeyword */:
32923                 case 146 /* NumberKeyword */:
32924                 case 157 /* BigIntKeyword */:
32925                 case 133 /* BooleanKeyword */:
32926                 case 144 /* ReadonlyKeyword */:
32927                 case 150 /* SymbolKeyword */:
32928                 case 153 /* UniqueKeyword */:
32929                 case 114 /* VoidKeyword */:
32930                 case 152 /* UndefinedKeyword */:
32931                 case 104 /* NullKeyword */:
32932                 case 108 /* ThisKeyword */:
32933                 case 112 /* TypeOfKeyword */:
32934                 case 143 /* NeverKeyword */:
32935                 case 18 /* OpenBraceToken */:
32936                 case 22 /* OpenBracketToken */:
32937                 case 29 /* LessThanToken */:
32938                 case 51 /* BarToken */:
32939                 case 50 /* AmpersandToken */:
32940                 case 103 /* NewKeyword */:
32941                 case 10 /* StringLiteral */:
32942                 case 8 /* NumericLiteral */:
32943                 case 9 /* BigIntLiteral */:
32944                 case 110 /* TrueKeyword */:
32945                 case 95 /* FalseKeyword */:
32946                 case 147 /* ObjectKeyword */:
32947                 case 41 /* AsteriskToken */:
32948                 case 57 /* QuestionToken */:
32949                 case 53 /* ExclamationToken */:
32950                 case 25 /* DotDotDotToken */:
32951                 case 137 /* InferKeyword */:
32952                 case 100 /* ImportKeyword */:
32953                 case 128 /* AssertsKeyword */:
32954                 case 14 /* NoSubstitutionTemplateLiteral */:
32955                 case 15 /* TemplateHead */:
32956                     return true;
32957                 case 98 /* FunctionKeyword */:
32958                     return !inStartOfParameter;
32959                 case 40 /* MinusToken */:
32960                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
32961                 case 20 /* OpenParenToken */:
32962                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
32963                     // or something that starts a type. We don't want to consider things like '(1)' a type.
32964                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
32965                 default:
32966                     return isIdentifier();
32967             }
32968         }
32969         function isStartOfParenthesizedOrFunctionType() {
32970             nextToken();
32971             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
32972         }
32973         function parsePostfixTypeOrHigher() {
32974             var pos = getNodePos();
32975             var type = parseNonArrayType();
32976             while (!scanner.hasPrecedingLineBreak()) {
32977                 switch (token()) {
32978                     case 53 /* ExclamationToken */:
32979                         nextToken();
32980                         type = finishNode(factory.createJSDocNonNullableType(type), pos);
32981                         break;
32982                     case 57 /* QuestionToken */:
32983                         // If next token is start of a type we have a conditional type
32984                         if (lookAhead(nextTokenIsStartOfType)) {
32985                             return type;
32986                         }
32987                         nextToken();
32988                         type = finishNode(factory.createJSDocNullableType(type), pos);
32989                         break;
32990                     case 22 /* OpenBracketToken */:
32991                         parseExpected(22 /* OpenBracketToken */);
32992                         if (isStartOfType()) {
32993                             var indexType = parseType();
32994                             parseExpected(23 /* CloseBracketToken */);
32995                             type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
32996                         }
32997                         else {
32998                             parseExpected(23 /* CloseBracketToken */);
32999                             type = finishNode(factory.createArrayTypeNode(type), pos);
33000                         }
33001                         break;
33002                     default:
33003                         return type;
33004                 }
33005             }
33006             return type;
33007         }
33008         function parseTypeOperator(operator) {
33009             var pos = getNodePos();
33010             parseExpected(operator);
33011             return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
33012         }
33013         function parseTypeParameterOfInferType() {
33014             var pos = getNodePos();
33015             return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(), 
33016             /*constraint*/ undefined, 
33017             /*defaultType*/ undefined), pos);
33018         }
33019         function parseInferType() {
33020             var pos = getNodePos();
33021             parseExpected(137 /* InferKeyword */);
33022             return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
33023         }
33024         function parseTypeOperatorOrHigher() {
33025             var operator = token();
33026             switch (operator) {
33027                 case 140 /* KeyOfKeyword */:
33028                 case 153 /* UniqueKeyword */:
33029                 case 144 /* ReadonlyKeyword */:
33030                     return parseTypeOperator(operator);
33031                 case 137 /* InferKeyword */:
33032                     return parseInferType();
33033             }
33034             return parsePostfixTypeOrHigher();
33035         }
33036         function parseFunctionOrConstructorTypeToError(isInUnionType) {
33037             // the function type and constructor type shorthand notation
33038             // are not allowed directly in unions and intersections, but we'll
33039             // try to parse them gracefully and issue a helpful message.
33040             if (isStartOfFunctionTypeOrConstructorType()) {
33041                 var type = parseFunctionOrConstructorType();
33042                 var diagnostic = void 0;
33043                 if (ts.isFunctionTypeNode(type)) {
33044                     diagnostic = isInUnionType
33045                         ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
33046                         : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
33047                 }
33048                 else {
33049                     diagnostic = isInUnionType
33050                         ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
33051                         : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
33052                 }
33053                 parseErrorAtRange(type, diagnostic);
33054                 return type;
33055             }
33056             return undefined;
33057         }
33058         function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
33059             var pos = getNodePos();
33060             var isUnionType = operator === 51 /* BarToken */;
33061             var hasLeadingOperator = parseOptional(operator);
33062             var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
33063                 || parseConstituentType();
33064             if (token() === operator || hasLeadingOperator) {
33065                 var types = [type];
33066                 while (parseOptional(operator)) {
33067                     types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
33068                 }
33069                 type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
33070             }
33071             return type;
33072         }
33073         function parseIntersectionTypeOrHigher() {
33074             return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
33075         }
33076         function parseUnionTypeOrHigher() {
33077             return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
33078         }
33079         function nextTokenIsNewKeyword() {
33080             nextToken();
33081             return token() === 103 /* NewKeyword */;
33082         }
33083         function isStartOfFunctionTypeOrConstructorType() {
33084             if (token() === 29 /* LessThanToken */) {
33085                 return true;
33086             }
33087             if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
33088                 return true;
33089             }
33090             return token() === 103 /* NewKeyword */ ||
33091                 token() === 126 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword);
33092         }
33093         function skipParameterStart() {
33094             if (ts.isModifierKind(token())) {
33095                 // Skip modifiers
33096                 parseModifiers();
33097             }
33098             if (isIdentifier() || token() === 108 /* ThisKeyword */) {
33099                 nextToken();
33100                 return true;
33101             }
33102             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
33103                 // Return true if we can parse an array or object binding pattern with no errors
33104                 var previousErrorCount = parseDiagnostics.length;
33105                 parseIdentifierOrPattern();
33106                 return previousErrorCount === parseDiagnostics.length;
33107             }
33108             return false;
33109         }
33110         function isUnambiguouslyStartOfFunctionType() {
33111             nextToken();
33112             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
33113                 // ( )
33114                 // ( ...
33115                 return true;
33116             }
33117             if (skipParameterStart()) {
33118                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
33119                 // now see if we have something that indicates a parameter declaration
33120                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
33121                     token() === 57 /* QuestionToken */ || token() === 63 /* EqualsToken */) {
33122                     // ( xxx :
33123                     // ( xxx ,
33124                     // ( xxx ?
33125                     // ( xxx =
33126                     return true;
33127                 }
33128                 if (token() === 21 /* CloseParenToken */) {
33129                     nextToken();
33130                     if (token() === 38 /* EqualsGreaterThanToken */) {
33131                         // ( xxx ) =>
33132                         return true;
33133                     }
33134                 }
33135             }
33136             return false;
33137         }
33138         function parseTypeOrTypePredicate() {
33139             var pos = getNodePos();
33140             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
33141             var type = parseType();
33142             if (typePredicateVariable) {
33143                 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
33144             }
33145             else {
33146                 return type;
33147             }
33148         }
33149         function parseTypePredicatePrefix() {
33150             var id = parseIdentifier();
33151             if (token() === 139 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
33152                 nextToken();
33153                 return id;
33154             }
33155         }
33156         function parseAssertsTypePredicate() {
33157             var pos = getNodePos();
33158             var assertsModifier = parseExpectedToken(128 /* AssertsKeyword */);
33159             var parameterName = token() === 108 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
33160             var type = parseOptional(139 /* IsKeyword */) ? parseType() : undefined;
33161             return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
33162         }
33163         function parseType() {
33164             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
33165             // apply to 'type' contexts.  So we disable these parameters here before moving on.
33166             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
33167         }
33168         function parseTypeWorker(noConditionalTypes) {
33169             if (isStartOfFunctionTypeOrConstructorType()) {
33170                 return parseFunctionOrConstructorType();
33171             }
33172             var pos = getNodePos();
33173             var type = parseUnionTypeOrHigher();
33174             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(94 /* ExtendsKeyword */)) {
33175                 // The type following 'extends' is not permitted to be another conditional type
33176                 var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
33177                 parseExpected(57 /* QuestionToken */);
33178                 var trueType = parseTypeWorker();
33179                 parseExpected(58 /* ColonToken */);
33180                 var falseType = parseTypeWorker();
33181                 return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
33182             }
33183             return type;
33184         }
33185         function parseTypeAnnotation() {
33186             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
33187         }
33188         // EXPRESSIONS
33189         function isStartOfLeftHandSideExpression() {
33190             switch (token()) {
33191                 case 108 /* ThisKeyword */:
33192                 case 106 /* SuperKeyword */:
33193                 case 104 /* NullKeyword */:
33194                 case 110 /* TrueKeyword */:
33195                 case 95 /* FalseKeyword */:
33196                 case 8 /* NumericLiteral */:
33197                 case 9 /* BigIntLiteral */:
33198                 case 10 /* StringLiteral */:
33199                 case 14 /* NoSubstitutionTemplateLiteral */:
33200                 case 15 /* TemplateHead */:
33201                 case 20 /* OpenParenToken */:
33202                 case 22 /* OpenBracketToken */:
33203                 case 18 /* OpenBraceToken */:
33204                 case 98 /* FunctionKeyword */:
33205                 case 84 /* ClassKeyword */:
33206                 case 103 /* NewKeyword */:
33207                 case 43 /* SlashToken */:
33208                 case 68 /* SlashEqualsToken */:
33209                 case 79 /* Identifier */:
33210                     return true;
33211                 case 100 /* ImportKeyword */:
33212                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
33213                 default:
33214                     return isIdentifier();
33215             }
33216         }
33217         function isStartOfExpression() {
33218             if (isStartOfLeftHandSideExpression()) {
33219                 return true;
33220             }
33221             switch (token()) {
33222                 case 39 /* PlusToken */:
33223                 case 40 /* MinusToken */:
33224                 case 54 /* TildeToken */:
33225                 case 53 /* ExclamationToken */:
33226                 case 89 /* DeleteKeyword */:
33227                 case 112 /* TypeOfKeyword */:
33228                 case 114 /* VoidKeyword */:
33229                 case 45 /* PlusPlusToken */:
33230                 case 46 /* MinusMinusToken */:
33231                 case 29 /* LessThanToken */:
33232                 case 132 /* AwaitKeyword */:
33233                 case 125 /* YieldKeyword */:
33234                 case 80 /* PrivateIdentifier */:
33235                     // Yield/await always starts an expression.  Either it is an identifier (in which case
33236                     // it is definitely an expression).  Or it's a keyword (either because we're in
33237                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
33238                     return true;
33239                 default:
33240                     // Error tolerance.  If we see the start of some binary operator, we consider
33241                     // that the start of an expression.  That way we'll parse out a missing identifier,
33242                     // give a good message about an identifier being missing, and then consume the
33243                     // rest of the binary expression.
33244                     if (isBinaryOperator()) {
33245                         return true;
33246                     }
33247                     return isIdentifier();
33248             }
33249         }
33250         function isStartOfExpressionStatement() {
33251             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
33252             return token() !== 18 /* OpenBraceToken */ &&
33253                 token() !== 98 /* FunctionKeyword */ &&
33254                 token() !== 84 /* ClassKeyword */ &&
33255                 token() !== 59 /* AtToken */ &&
33256                 isStartOfExpression();
33257         }
33258         function parseExpression() {
33259             // Expression[in]:
33260             //      AssignmentExpression[in]
33261             //      Expression[in] , AssignmentExpression[in]
33262             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
33263             var saveDecoratorContext = inDecoratorContext();
33264             if (saveDecoratorContext) {
33265                 setDecoratorContext(/*val*/ false);
33266             }
33267             var pos = getNodePos();
33268             var expr = parseAssignmentExpressionOrHigher();
33269             var operatorToken;
33270             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
33271                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
33272             }
33273             if (saveDecoratorContext) {
33274                 setDecoratorContext(/*val*/ true);
33275             }
33276             return expr;
33277         }
33278         function parseInitializer() {
33279             return parseOptional(63 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
33280         }
33281         function parseAssignmentExpressionOrHigher() {
33282             //  AssignmentExpression[in,yield]:
33283             //      1) ConditionalExpression[?in,?yield]
33284             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
33285             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
33286             //      4) ArrowFunctionExpression[?in,?yield]
33287             //      5) AsyncArrowFunctionExpression[in,yield,await]
33288             //      6) [+Yield] YieldExpression[?In]
33289             //
33290             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
33291             // (i.e. they're both BinaryExpressions with an assignment operator in it).
33292             // First, do the simple check if we have a YieldExpression (production '6').
33293             if (isYieldExpression()) {
33294                 return parseYieldExpression();
33295             }
33296             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
33297             // parameter list or is an async arrow function.
33298             // AsyncArrowFunctionExpression:
33299             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
33300             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
33301             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
33302             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
33303             //
33304             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
33305             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
33306             // with AssignmentExpression if we see one.
33307             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
33308             if (arrowExpression) {
33309                 return arrowExpression;
33310             }
33311             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
33312             // start with a LogicalOrExpression, while the assignment productions can only start with
33313             // LeftHandSideExpressions.
33314             //
33315             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
33316             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
33317             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
33318             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
33319             // and consumes anything.
33320             var pos = getNodePos();
33321             var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
33322             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
33323             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
33324             // identifier and the current token is an arrow.
33325             if (expr.kind === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
33326                 return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
33327             }
33328             // Now see if we might be in cases '2' or '3'.
33329             // If the expression was a LHS expression, and we have an assignment operator, then
33330             // we're in '2' or '3'. Consume the assignment and return.
33331             //
33332             // Note: we call reScanGreaterToken so that we get an appropriately merged token
33333             // for cases like `> > =` becoming `>>=`
33334             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
33335                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos);
33336             }
33337             // It wasn't an assignment or a lambda.  This is a conditional expression:
33338             return parseConditionalExpressionRest(expr, pos);
33339         }
33340         function isYieldExpression() {
33341             if (token() === 125 /* YieldKeyword */) {
33342                 // If we have a 'yield' keyword, and this is a context where yield expressions are
33343                 // allowed, then definitely parse out a yield expression.
33344                 if (inYieldContext()) {
33345                     return true;
33346                 }
33347                 // We're in a context where 'yield expr' is not allowed.  However, if we can
33348                 // definitely tell that the user was trying to parse a 'yield expr' and not
33349                 // just a normal expr that start with a 'yield' identifier, then parse out
33350                 // a 'yield expr'.  We can then report an error later that they are only
33351                 // allowed in generator expressions.
33352                 //
33353                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
33354                 // invocation expression of something called 'yield'.  However, if we have
33355                 // 'yield foo' then that is not legal as a normal expression, so we can
33356                 // definitely recognize this as a yield expression.
33357                 //
33358                 // for now we just check if the next token is an identifier.  More heuristics
33359                 // can be added here later as necessary.  We just need to make sure that we
33360                 // don't accidentally consume something legal.
33361                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
33362             }
33363             return false;
33364         }
33365         function nextTokenIsIdentifierOnSameLine() {
33366             nextToken();
33367             return !scanner.hasPrecedingLineBreak() && isIdentifier();
33368         }
33369         function parseYieldExpression() {
33370             var pos = getNodePos();
33371             // YieldExpression[In] :
33372             //      yield
33373             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
33374             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
33375             nextToken();
33376             if (!scanner.hasPrecedingLineBreak() &&
33377                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
33378                 return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
33379             }
33380             else {
33381                 // if the next token is not on the same line as yield.  or we don't have an '*' or
33382                 // the start of an expression, then this is just a simple "yield" expression.
33383                 return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
33384             }
33385         }
33386         function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
33387             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
33388             var parameter = factory.createParameterDeclaration(
33389             /*decorators*/ undefined, 
33390             /*modifiers*/ undefined, 
33391             /*dotDotDotToken*/ undefined, identifier, 
33392             /*questionToken*/ undefined, 
33393             /*type*/ undefined, 
33394             /*initializer*/ undefined);
33395             finishNode(parameter, identifier.pos);
33396             var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
33397             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
33398             var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
33399             var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
33400             return addJSDocComment(finishNode(node, pos));
33401         }
33402         function tryParseParenthesizedArrowFunctionExpression() {
33403             var triState = isParenthesizedArrowFunctionExpression();
33404             if (triState === 0 /* False */) {
33405                 // It's definitely not a parenthesized arrow function expression.
33406                 return undefined;
33407             }
33408             // If we definitely have an arrow function, then we can just parse one, not requiring a
33409             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
33410             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
33411             // expression instead.
33412             return triState === 1 /* True */ ?
33413                 parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
33414                 tryParse(parsePossibleParenthesizedArrowFunctionExpression);
33415         }
33416         //  True        -> We definitely expect a parenthesized arrow function here.
33417         //  False       -> There *cannot* be a parenthesized arrow function here.
33418         //  Unknown     -> There *might* be a parenthesized arrow function here.
33419         //                 Speculatively look ahead to be sure, and rollback if not.
33420         function isParenthesizedArrowFunctionExpression() {
33421             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 131 /* AsyncKeyword */) {
33422                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
33423             }
33424             if (token() === 38 /* EqualsGreaterThanToken */) {
33425                 // ERROR RECOVERY TWEAK:
33426                 // If we see a standalone => try to parse it as an arrow function expression as that's
33427                 // likely what the user intended to write.
33428                 return 1 /* True */;
33429             }
33430             // Definitely not a parenthesized arrow function.
33431             return 0 /* False */;
33432         }
33433         function isParenthesizedArrowFunctionExpressionWorker() {
33434             if (token() === 131 /* AsyncKeyword */) {
33435                 nextToken();
33436                 if (scanner.hasPrecedingLineBreak()) {
33437                     return 0 /* False */;
33438                 }
33439                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
33440                     return 0 /* False */;
33441                 }
33442             }
33443             var first = token();
33444             var second = nextToken();
33445             if (first === 20 /* OpenParenToken */) {
33446                 if (second === 21 /* CloseParenToken */) {
33447                     // Simple cases: "() =>", "(): ", and "() {".
33448                     // This is an arrow function with no parameters.
33449                     // The last one is not actually an arrow function,
33450                     // but this is probably what the user intended.
33451                     var third = nextToken();
33452                     switch (third) {
33453                         case 38 /* EqualsGreaterThanToken */:
33454                         case 58 /* ColonToken */:
33455                         case 18 /* OpenBraceToken */:
33456                             return 1 /* True */;
33457                         default:
33458                             return 0 /* False */;
33459                     }
33460                 }
33461                 // If encounter "([" or "({", this could be the start of a binding pattern.
33462                 // Examples:
33463                 //      ([ x ]) => { }
33464                 //      ({ x }) => { }
33465                 //      ([ x ])
33466                 //      ({ x })
33467                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
33468                     return 2 /* Unknown */;
33469                 }
33470                 // Simple case: "(..."
33471                 // This is an arrow function with a rest parameter.
33472                 if (second === 25 /* DotDotDotToken */) {
33473                     return 1 /* True */;
33474                 }
33475                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
33476                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
33477                 // a good error message.
33478                 if (ts.isModifierKind(second) && second !== 131 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
33479                     return 1 /* True */;
33480                 }
33481                 // If we had "(" followed by something that's not an identifier,
33482                 // then this definitely doesn't look like a lambda.  "this" is not
33483                 // valid, but we want to parse it and then give a semantic error.
33484                 if (!isIdentifier() && second !== 108 /* ThisKeyword */) {
33485                     return 0 /* False */;
33486                 }
33487                 switch (nextToken()) {
33488                     case 58 /* ColonToken */:
33489                         // If we have something like "(a:", then we must have a
33490                         // type-annotated parameter in an arrow function expression.
33491                         return 1 /* True */;
33492                     case 57 /* QuestionToken */:
33493                         nextToken();
33494                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
33495                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 63 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
33496                             return 1 /* True */;
33497                         }
33498                         // Otherwise it is definitely not a lambda.
33499                         return 0 /* False */;
33500                     case 27 /* CommaToken */:
33501                     case 63 /* EqualsToken */:
33502                     case 21 /* CloseParenToken */:
33503                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
33504                         return 2 /* Unknown */;
33505                 }
33506                 // It is definitely not an arrow function
33507                 return 0 /* False */;
33508             }
33509             else {
33510                 ts.Debug.assert(first === 29 /* LessThanToken */);
33511                 // If we have "<" not followed by an identifier,
33512                 // then this definitely is not an arrow function.
33513                 if (!isIdentifier()) {
33514                     return 0 /* False */;
33515                 }
33516                 // JSX overrides
33517                 if (languageVariant === 1 /* JSX */) {
33518                     var isArrowFunctionInJsx = lookAhead(function () {
33519                         var third = nextToken();
33520                         if (third === 94 /* ExtendsKeyword */) {
33521                             var fourth = nextToken();
33522                             switch (fourth) {
33523                                 case 63 /* EqualsToken */:
33524                                 case 31 /* GreaterThanToken */:
33525                                     return false;
33526                                 default:
33527                                     return true;
33528                             }
33529                         }
33530                         else if (third === 27 /* CommaToken */) {
33531                             return true;
33532                         }
33533                         return false;
33534                     });
33535                     if (isArrowFunctionInJsx) {
33536                         return 1 /* True */;
33537                     }
33538                     return 0 /* False */;
33539                 }
33540                 // This *could* be a parenthesized arrow function.
33541                 return 2 /* Unknown */;
33542             }
33543         }
33544         function parsePossibleParenthesizedArrowFunctionExpression() {
33545             var tokenPos = scanner.getTokenPos();
33546             if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
33547                 return undefined;
33548             }
33549             var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
33550             if (!result) {
33551                 (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
33552             }
33553             return result;
33554         }
33555         function tryParseAsyncSimpleArrowFunctionExpression() {
33556             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
33557             if (token() === 131 /* AsyncKeyword */) {
33558                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
33559                     var pos = getNodePos();
33560                     var asyncModifier = parseModifiersForArrowFunction();
33561                     var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
33562                     return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
33563                 }
33564             }
33565             return undefined;
33566         }
33567         function isUnParenthesizedAsyncArrowFunctionWorker() {
33568             // AsyncArrowFunctionExpression:
33569             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
33570             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
33571             if (token() === 131 /* AsyncKeyword */) {
33572                 nextToken();
33573                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
33574                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
33575                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
33576                     return 0 /* False */;
33577                 }
33578                 // Check for un-parenthesized AsyncArrowFunction
33579                 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
33580                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 79 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
33581                     return 1 /* True */;
33582                 }
33583             }
33584             return 0 /* False */;
33585         }
33586         function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
33587             var pos = getNodePos();
33588             var hasJSDoc = hasPrecedingJSDocComment();
33589             var modifiers = parseModifiersForArrowFunction();
33590             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
33591             // Arrow functions are never generators.
33592             //
33593             // If we're speculatively parsing a signature for a parenthesized arrow function, then
33594             // we have to have a complete parameter list.  Otherwise we might see something like
33595             // a => (b => c)
33596             // And think that "(b =>" was actually a parenthesized arrow function with a missing
33597             // close paren.
33598             var typeParameters = parseTypeParameters();
33599             var parameters;
33600             if (!parseExpected(20 /* OpenParenToken */)) {
33601                 if (!allowAmbiguity) {
33602                     return undefined;
33603                 }
33604                 parameters = createMissingList();
33605             }
33606             else {
33607                 parameters = parseParametersWorker(isAsync);
33608                 if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
33609                     return undefined;
33610                 }
33611             }
33612             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33613             if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
33614                 return undefined;
33615             }
33616             // Parsing a signature isn't enough.
33617             // Parenthesized arrow signatures often look like other valid expressions.
33618             // For instance:
33619             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
33620             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
33621             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
33622             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
33623             //
33624             // So we need just a bit of lookahead to ensure that it can only be a signature.
33625             var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
33626             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
33627                 // Returning undefined here will cause our caller to rewind to where we started from.
33628                 return undefined;
33629             }
33630             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
33631             // have an opening brace, just in case we're in an error state.
33632             var lastToken = token();
33633             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
33634             var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
33635                 ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
33636                 : parseIdentifier();
33637             var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
33638             return withJSDoc(finishNode(node, pos), hasJSDoc);
33639         }
33640         function parseArrowFunctionExpressionBody(isAsync) {
33641             if (token() === 18 /* OpenBraceToken */) {
33642                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
33643             }
33644             if (token() !== 26 /* SemicolonToken */ &&
33645                 token() !== 98 /* FunctionKeyword */ &&
33646                 token() !== 84 /* ClassKeyword */ &&
33647                 isStartOfStatement() &&
33648                 !isStartOfExpressionStatement()) {
33649                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
33650                 //
33651                 // Here we try to recover from a potential error situation in the case where the
33652                 // user meant to supply a block. For example, if the user wrote:
33653                 //
33654                 //  a =>
33655                 //      let v = 0;
33656                 //  }
33657                 //
33658                 // they may be missing an open brace.  Check to see if that's the case so we can
33659                 // try to recover better.  If we don't do this, then the next close curly we see may end
33660                 // up preemptively closing the containing construct.
33661                 //
33662                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
33663                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
33664             }
33665             var savedTopLevel = topLevel;
33666             topLevel = false;
33667             var node = isAsync
33668                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
33669                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
33670             topLevel = savedTopLevel;
33671             return node;
33672         }
33673         function parseConditionalExpressionRest(leftOperand, pos) {
33674             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
33675             var questionToken = parseOptionalToken(57 /* QuestionToken */);
33676             if (!questionToken) {
33677                 return leftOperand;
33678             }
33679             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
33680             // we do not that for the 'whenFalse' part.
33681             var colonToken;
33682             return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
33683                 ? parseAssignmentExpressionOrHigher()
33684                 : createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
33685         }
33686         function parseBinaryExpressionOrHigher(precedence) {
33687             var pos = getNodePos();
33688             var leftOperand = parseUnaryExpressionOrHigher();
33689             return parseBinaryExpressionRest(precedence, leftOperand, pos);
33690         }
33691         function isInOrOfKeyword(t) {
33692             return t === 101 /* InKeyword */ || t === 159 /* OfKeyword */;
33693         }
33694         function parseBinaryExpressionRest(precedence, leftOperand, pos) {
33695             while (true) {
33696                 // We either have a binary operator here, or we're finished.  We call
33697                 // reScanGreaterToken so that we merge token sequences like > and = into >=
33698                 reScanGreaterToken();
33699                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
33700                 // Check the precedence to see if we should "take" this operator
33701                 // - For left associative operator (all operator but **), consume the operator,
33702                 //   recursively call the function below, and parse binaryExpression as a rightOperand
33703                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
33704                 //   For example:
33705                 //      a - b - c;
33706                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
33707                 //      a * b - c
33708                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
33709                 //      a - b * c;
33710                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
33711                 // - For right associative operator (**), consume the operator, recursively call the function
33712                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
33713                 //   the operator is strictly grater than the current precedence
33714                 //   For example:
33715                 //      a ** b ** c;
33716                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
33717                 //      a - b ** c;
33718                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
33719                 //      a ** b - c
33720                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
33721                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
33722                     newPrecedence >= precedence :
33723                     newPrecedence > precedence;
33724                 if (!consumeCurrentOperator) {
33725                     break;
33726                 }
33727                 if (token() === 101 /* InKeyword */ && inDisallowInContext()) {
33728                     break;
33729                 }
33730                 if (token() === 127 /* AsKeyword */) {
33731                     // Make sure we *do* perform ASI for constructs like this:
33732                     //    var x = foo
33733                     //    as (Bar)
33734                     // This should be parsed as an initialized variable, followed
33735                     // by a function call to 'as' with the argument 'Bar'
33736                     if (scanner.hasPrecedingLineBreak()) {
33737                         break;
33738                     }
33739                     else {
33740                         nextToken();
33741                         leftOperand = makeAsExpression(leftOperand, parseType());
33742                     }
33743                 }
33744                 else {
33745                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
33746                 }
33747             }
33748             return leftOperand;
33749         }
33750         function isBinaryOperator() {
33751             if (inDisallowInContext() && token() === 101 /* InKeyword */) {
33752                 return false;
33753             }
33754             return ts.getBinaryOperatorPrecedence(token()) > 0;
33755         }
33756         function makeBinaryExpression(left, operatorToken, right, pos) {
33757             return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
33758         }
33759         function makeAsExpression(left, right) {
33760             return finishNode(factory.createAsExpression(left, right), left.pos);
33761         }
33762         function parsePrefixUnaryExpression() {
33763             var pos = getNodePos();
33764             return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
33765         }
33766         function parseDeleteExpression() {
33767             var pos = getNodePos();
33768             return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
33769         }
33770         function parseTypeOfExpression() {
33771             var pos = getNodePos();
33772             return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
33773         }
33774         function parseVoidExpression() {
33775             var pos = getNodePos();
33776             return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
33777         }
33778         function isAwaitExpression() {
33779             if (token() === 132 /* AwaitKeyword */) {
33780                 if (inAwaitContext()) {
33781                     return true;
33782                 }
33783                 // here we are using similar heuristics as 'isYieldExpression'
33784                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
33785             }
33786             return false;
33787         }
33788         function parseAwaitExpression() {
33789             var pos = getNodePos();
33790             return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
33791         }
33792         /**
33793          * Parse ES7 exponential expression and await expression
33794          *
33795          * ES7 ExponentiationExpression:
33796          *      1) UnaryExpression[?Yield]
33797          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
33798          *
33799          */
33800         function parseUnaryExpressionOrHigher() {
33801             /**
33802              * ES7 UpdateExpression:
33803              *      1) LeftHandSideExpression[?Yield]
33804              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
33805              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
33806              *      4) ++UnaryExpression[?Yield]
33807              *      5) --UnaryExpression[?Yield]
33808              */
33809             if (isUpdateExpression()) {
33810                 var pos = getNodePos();
33811                 var updateExpression = parseUpdateExpression();
33812                 return token() === 42 /* AsteriskAsteriskToken */ ?
33813                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
33814                     updateExpression;
33815             }
33816             /**
33817              * ES7 UnaryExpression:
33818              *      1) UpdateExpression[?yield]
33819              *      2) delete UpdateExpression[?yield]
33820              *      3) void UpdateExpression[?yield]
33821              *      4) typeof UpdateExpression[?yield]
33822              *      5) + UpdateExpression[?yield]
33823              *      6) - UpdateExpression[?yield]
33824              *      7) ~ UpdateExpression[?yield]
33825              *      8) ! UpdateExpression[?yield]
33826              */
33827             var unaryOperator = token();
33828             var simpleUnaryExpression = parseSimpleUnaryExpression();
33829             if (token() === 42 /* AsteriskAsteriskToken */) {
33830                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
33831                 var end = simpleUnaryExpression.end;
33832                 if (simpleUnaryExpression.kind === 210 /* TypeAssertionExpression */) {
33833                     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);
33834                 }
33835                 else {
33836                     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));
33837                 }
33838             }
33839             return simpleUnaryExpression;
33840         }
33841         /**
33842          * Parse ES7 simple-unary expression or higher:
33843          *
33844          * ES7 UnaryExpression:
33845          *      1) UpdateExpression[?yield]
33846          *      2) delete UnaryExpression[?yield]
33847          *      3) void UnaryExpression[?yield]
33848          *      4) typeof UnaryExpression[?yield]
33849          *      5) + UnaryExpression[?yield]
33850          *      6) - UnaryExpression[?yield]
33851          *      7) ~ UnaryExpression[?yield]
33852          *      8) ! UnaryExpression[?yield]
33853          *      9) [+Await] await UnaryExpression[?yield]
33854          */
33855         function parseSimpleUnaryExpression() {
33856             switch (token()) {
33857                 case 39 /* PlusToken */:
33858                 case 40 /* MinusToken */:
33859                 case 54 /* TildeToken */:
33860                 case 53 /* ExclamationToken */:
33861                     return parsePrefixUnaryExpression();
33862                 case 89 /* DeleteKeyword */:
33863                     return parseDeleteExpression();
33864                 case 112 /* TypeOfKeyword */:
33865                     return parseTypeOfExpression();
33866                 case 114 /* VoidKeyword */:
33867                     return parseVoidExpression();
33868                 case 29 /* LessThanToken */:
33869                     // This is modified UnaryExpression grammar in TypeScript
33870                     //  UnaryExpression (modified):
33871                     //      < type > UnaryExpression
33872                     return parseTypeAssertion();
33873                 case 132 /* AwaitKeyword */:
33874                     if (isAwaitExpression()) {
33875                         return parseAwaitExpression();
33876                     }
33877                 // falls through
33878                 default:
33879                     return parseUpdateExpression();
33880             }
33881         }
33882         /**
33883          * Check if the current token can possibly be an ES7 increment expression.
33884          *
33885          * ES7 UpdateExpression:
33886          *      LeftHandSideExpression[?Yield]
33887          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
33888          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
33889          *      ++LeftHandSideExpression[?Yield]
33890          *      --LeftHandSideExpression[?Yield]
33891          */
33892         function isUpdateExpression() {
33893             // This function is called inside parseUnaryExpression to decide
33894             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
33895             switch (token()) {
33896                 case 39 /* PlusToken */:
33897                 case 40 /* MinusToken */:
33898                 case 54 /* TildeToken */:
33899                 case 53 /* ExclamationToken */:
33900                 case 89 /* DeleteKeyword */:
33901                 case 112 /* TypeOfKeyword */:
33902                 case 114 /* VoidKeyword */:
33903                 case 132 /* AwaitKeyword */:
33904                     return false;
33905                 case 29 /* LessThanToken */:
33906                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
33907                     if (languageVariant !== 1 /* JSX */) {
33908                         return false;
33909                     }
33910                 // We are in JSX context and the token is part of JSXElement.
33911                 // falls through
33912                 default:
33913                     return true;
33914             }
33915         }
33916         /**
33917          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
33918          *
33919          * ES7 UpdateExpression[yield]:
33920          *      1) LeftHandSideExpression[?yield]
33921          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
33922          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
33923          *      4) ++LeftHandSideExpression[?yield]
33924          *      5) --LeftHandSideExpression[?yield]
33925          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
33926          */
33927         function parseUpdateExpression() {
33928             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
33929                 var pos = getNodePos();
33930                 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
33931             }
33932             else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
33933                 // JSXElement is part of primaryExpression
33934                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
33935             }
33936             var expression = parseLeftHandSideExpressionOrHigher();
33937             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
33938             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
33939                 var operator = token();
33940                 nextToken();
33941                 return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
33942             }
33943             return expression;
33944         }
33945         function parseLeftHandSideExpressionOrHigher() {
33946             // Original Ecma:
33947             // LeftHandSideExpression: See 11.2
33948             //      NewExpression
33949             //      CallExpression
33950             //
33951             // Our simplification:
33952             //
33953             // LeftHandSideExpression: See 11.2
33954             //      MemberExpression
33955             //      CallExpression
33956             //
33957             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
33958             // MemberExpression to make our lives easier.
33959             //
33960             // to best understand the below code, it's important to see how CallExpression expands
33961             // out into its own productions:
33962             //
33963             // CallExpression:
33964             //      MemberExpression Arguments
33965             //      CallExpression Arguments
33966             //      CallExpression[Expression]
33967             //      CallExpression.IdentifierName
33968             //      import (AssignmentExpression)
33969             //      super Arguments
33970             //      super.IdentifierName
33971             //
33972             // Because of the recursion in these calls, we need to bottom out first. There are three
33973             // bottom out states we can run into: 1) We see 'super' which must start either of
33974             // the last two CallExpression productions. 2) We see 'import' which must start import call.
33975             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
33976             // or starts the beginning of the first four CallExpression productions.
33977             var pos = getNodePos();
33978             var expression;
33979             if (token() === 100 /* ImportKeyword */) {
33980                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
33981                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
33982                     // For example:
33983                     //      var foo3 = require("subfolder
33984                     //      import * as foo1 from "module-from-node
33985                     // We want this import to be a statement rather than import call expression
33986                     sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
33987                     expression = parseTokenNode();
33988                 }
33989                 else if (lookAhead(nextTokenIsDot)) {
33990                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
33991                     nextToken(); // advance past the 'import'
33992                     nextToken(); // advance past the dot
33993                     expression = finishNode(factory.createMetaProperty(100 /* ImportKeyword */, parseIdentifierName()), pos);
33994                     sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
33995                 }
33996                 else {
33997                     expression = parseMemberExpressionOrHigher();
33998                 }
33999             }
34000             else {
34001                 expression = token() === 106 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
34002             }
34003             // Now, we *may* be complete.  However, we might have consumed the start of a
34004             // CallExpression or OptionalExpression.  As such, we need to consume the rest
34005             // of it here to be complete.
34006             return parseCallExpressionRest(pos, expression);
34007         }
34008         function parseMemberExpressionOrHigher() {
34009             // Note: to make our lives simpler, we decompose the NewExpression productions and
34010             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
34011             // like so:
34012             //
34013             //   PrimaryExpression : See 11.1
34014             //      this
34015             //      Identifier
34016             //      Literal
34017             //      ArrayLiteral
34018             //      ObjectLiteral
34019             //      (Expression)
34020             //      FunctionExpression
34021             //      new MemberExpression Arguments?
34022             //
34023             //   MemberExpression : See 11.2
34024             //      PrimaryExpression
34025             //      MemberExpression[Expression]
34026             //      MemberExpression.IdentifierName
34027             //
34028             //   CallExpression : See 11.2
34029             //      MemberExpression
34030             //      CallExpression Arguments
34031             //      CallExpression[Expression]
34032             //      CallExpression.IdentifierName
34033             //
34034             // Technically this is ambiguous.  i.e. CallExpression defines:
34035             //
34036             //   CallExpression:
34037             //      CallExpression Arguments
34038             //
34039             // If you see: "new Foo()"
34040             //
34041             // Then that could be treated as a single ObjectCreationExpression, or it could be
34042             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
34043             // the original grammar) by making sure that if we see an ObjectCreationExpression
34044             // we always consume arguments if they are there. So we treat "new Foo()" as an
34045             // object creation only, and not at all as an invocation.  Another way to think
34046             // about this is that for every "new" that we see, we will consume an argument list if
34047             // it is there as part of the *associated* object creation node.  Any additional
34048             // argument lists we see, will become invocation expressions.
34049             //
34050             // Because there are no other places in the grammar now that refer to FunctionExpression
34051             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
34052             // production.
34053             //
34054             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
34055             // of the recursion immediately.  So we parse out a primary expression to start with.
34056             var pos = getNodePos();
34057             var expression = parsePrimaryExpression();
34058             return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
34059         }
34060         function parseSuperExpression() {
34061             var pos = getNodePos();
34062             var expression = parseTokenNode();
34063             if (token() === 29 /* LessThanToken */) {
34064                 var startPos = getNodePos();
34065                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
34066                 if (typeArguments !== undefined) {
34067                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
34068                 }
34069             }
34070             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
34071                 return expression;
34072             }
34073             // If we have seen "super" it must be followed by '(' or '.'.
34074             // If it wasn't then just try to parse out a '.' and report an error.
34075             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
34076             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
34077             return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
34078         }
34079         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag) {
34080             var pos = getNodePos();
34081             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
34082             var result;
34083             if (opening.kind === 279 /* JsxOpeningElement */) {
34084                 var children = parseJsxChildren(opening);
34085                 var closingElement = void 0;
34086                 var lastChild = children[children.length - 1];
34087                 if ((lastChild === null || lastChild === void 0 ? void 0 : lastChild.kind) === 277 /* JsxElement */
34088                     && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName)
34089                     && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) {
34090                     // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement,
34091                     // restructure (<div>(...<span>...</div>)) --> (<div>(...<span>...</>)</div>)
34092                     // (no need to error; the parent will error)
34093                     var end = lastChild.children.end;
34094                     var newLast = finishNode(factory.createJsxElement(lastChild.openingElement, lastChild.children, finishNode(factory.createJsxClosingElement(finishNode(factory.createIdentifier(""), end, end)), end, end)), lastChild.openingElement.pos, end);
34095                     children = createNodeArray(__spreadArray(__spreadArray([], children.slice(0, children.length - 1), true), [newLast], false), children.pos, end);
34096                     closingElement = lastChild.closingElement;
34097                 }
34098                 else {
34099                     closingElement = parseJsxClosingElement(opening, inExpressionContext);
34100                     if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
34101                         if (openingTag && ts.isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) {
34102                             // opening incorrectly matched with its parent's closing -- put error on opening
34103                             parseErrorAtRange(opening.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
34104                         }
34105                         else {
34106                             // other opening/closing mismatches -- put error on closing
34107                             parseErrorAtRange(closingElement.tagName, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
34108                         }
34109                     }
34110                 }
34111                 result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
34112             }
34113             else if (opening.kind === 282 /* JsxOpeningFragment */) {
34114                 result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
34115             }
34116             else {
34117                 ts.Debug.assert(opening.kind === 278 /* JsxSelfClosingElement */);
34118                 // Nothing else to do for self-closing elements
34119                 result = opening;
34120             }
34121             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
34122             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
34123             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
34124             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
34125             // does less damage and we can report a better error.
34126             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
34127             // of one sort or another.
34128             if (inExpressionContext && token() === 29 /* LessThanToken */) {
34129                 var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
34130                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
34131                 if (invalidElement) {
34132                     var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
34133                     ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
34134                     parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
34135                     return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
34136                 }
34137             }
34138             return result;
34139         }
34140         function parseJsxText() {
34141             var pos = getNodePos();
34142             var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
34143             currentToken = scanner.scanJsxToken();
34144             return finishNode(node, pos);
34145         }
34146         function parseJsxChild(openingTag, token) {
34147             switch (token) {
34148                 case 1 /* EndOfFileToken */:
34149                     // If we hit EOF, issue the error at the tag that lacks the closing element
34150                     // rather than at the end of the file (which is useless)
34151                     if (ts.isJsxOpeningFragment(openingTag)) {
34152                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
34153                     }
34154                     else {
34155                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
34156                         // or to cover only 'Foo' in < Foo >
34157                         var tag = openingTag.tagName;
34158                         var start = ts.skipTrivia(sourceText, tag.pos);
34159                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
34160                     }
34161                     return undefined;
34162                 case 30 /* LessThanSlashToken */:
34163                 case 7 /* ConflictMarkerTrivia */:
34164                     return undefined;
34165                 case 11 /* JsxText */:
34166                 case 12 /* JsxTextAllWhiteSpaces */:
34167                     return parseJsxText();
34168                 case 18 /* OpenBraceToken */:
34169                     return parseJsxExpression(/*inExpressionContext*/ false);
34170                 case 29 /* LessThanToken */:
34171                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false, /*topInvalidNodePosition*/ undefined, openingTag);
34172                 default:
34173                     return ts.Debug.assertNever(token);
34174             }
34175         }
34176         function parseJsxChildren(openingTag) {
34177             var list = [];
34178             var listPos = getNodePos();
34179             var saveParsingContext = parsingContext;
34180             parsingContext |= 1 << 14 /* JsxChildren */;
34181             while (true) {
34182                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
34183                 if (!child)
34184                     break;
34185                 list.push(child);
34186                 if (ts.isJsxOpeningElement(openingTag)
34187                     && (child === null || child === void 0 ? void 0 : child.kind) === 277 /* JsxElement */
34188                     && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName)
34189                     && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) {
34190                     // stop after parsing a mismatched child like <div>...(<span></div>) in order to reattach the </div> higher
34191                     break;
34192                 }
34193             }
34194             parsingContext = saveParsingContext;
34195             return createNodeArray(list, listPos);
34196         }
34197         function parseJsxAttributes() {
34198             var pos = getNodePos();
34199             return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
34200         }
34201         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
34202             var pos = getNodePos();
34203             parseExpected(29 /* LessThanToken */);
34204             if (token() === 31 /* GreaterThanToken */) {
34205                 // See below for explanation of scanJsxText
34206                 scanJsxText();
34207                 return finishNode(factory.createJsxOpeningFragment(), pos);
34208             }
34209             var tagName = parseJsxElementName();
34210             var typeArguments = (contextFlags & 131072 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : undefined;
34211             var attributes = parseJsxAttributes();
34212             var node;
34213             if (token() === 31 /* GreaterThanToken */) {
34214                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
34215                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
34216                 // scanning errors
34217                 scanJsxText();
34218                 node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
34219             }
34220             else {
34221                 parseExpected(43 /* SlashToken */);
34222                 if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
34223                     // manually advance the scanner in order to look for jsx text inside jsx
34224                     if (inExpressionContext) {
34225                         nextToken();
34226                     }
34227                     else {
34228                         scanJsxText();
34229                     }
34230                 }
34231                 node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
34232             }
34233             return finishNode(node, pos);
34234         }
34235         function parseJsxElementName() {
34236             var pos = getNodePos();
34237             scanJsxIdentifier();
34238             // JsxElement can have name in the form of
34239             //      propertyAccessExpression
34240             //      primaryExpression in the form of an identifier and "this" keyword
34241             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
34242             // We only want to consider "this" as a primaryExpression
34243             var expression = token() === 108 /* ThisKeyword */ ?
34244                 parseTokenNode() : parseIdentifierName();
34245             while (parseOptional(24 /* DotToken */)) {
34246                 expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
34247             }
34248             return expression;
34249         }
34250         function parseJsxExpression(inExpressionContext) {
34251             var pos = getNodePos();
34252             if (!parseExpected(18 /* OpenBraceToken */)) {
34253                 return undefined;
34254             }
34255             var dotDotDotToken;
34256             var expression;
34257             if (token() !== 19 /* CloseBraceToken */) {
34258                 dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
34259                 // Only an AssignmentExpression is valid here per the JSX spec,
34260                 // but we can unambiguously parse a comma sequence and provide
34261                 // a better error message in grammar checking.
34262                 expression = parseExpression();
34263             }
34264             if (inExpressionContext) {
34265                 parseExpected(19 /* CloseBraceToken */);
34266             }
34267             else {
34268                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
34269                     scanJsxText();
34270                 }
34271             }
34272             return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
34273         }
34274         function parseJsxAttribute() {
34275             if (token() === 18 /* OpenBraceToken */) {
34276                 return parseJsxSpreadAttribute();
34277             }
34278             scanJsxIdentifier();
34279             var pos = getNodePos();
34280             return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* EqualsToken */ ? undefined :
34281                 scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
34282                     parseJsxExpression(/*inExpressionContext*/ true)), pos);
34283         }
34284         function parseJsxSpreadAttribute() {
34285             var pos = getNodePos();
34286             parseExpected(18 /* OpenBraceToken */);
34287             parseExpected(25 /* DotDotDotToken */);
34288             var expression = parseExpression();
34289             parseExpected(19 /* CloseBraceToken */);
34290             return finishNode(factory.createJsxSpreadAttribute(expression), pos);
34291         }
34292         function parseJsxClosingElement(open, inExpressionContext) {
34293             var pos = getNodePos();
34294             parseExpected(30 /* LessThanSlashToken */);
34295             var tagName = parseJsxElementName();
34296             if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
34297                 // manually advance the scanner in order to look for jsx text inside jsx
34298                 if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) {
34299                     nextToken();
34300                 }
34301                 else {
34302                     scanJsxText();
34303                 }
34304             }
34305             return finishNode(factory.createJsxClosingElement(tagName), pos);
34306         }
34307         function parseJsxClosingFragment(inExpressionContext) {
34308             var pos = getNodePos();
34309             parseExpected(30 /* LessThanSlashToken */);
34310             if (ts.tokenIsIdentifierOrKeyword(token())) {
34311                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
34312             }
34313             if (parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
34314                 // manually advance the scanner in order to look for jsx text inside jsx
34315                 if (inExpressionContext) {
34316                     nextToken();
34317                 }
34318                 else {
34319                     scanJsxText();
34320                 }
34321             }
34322             return finishNode(factory.createJsxJsxClosingFragment(), pos);
34323         }
34324         function parseTypeAssertion() {
34325             var pos = getNodePos();
34326             parseExpected(29 /* LessThanToken */);
34327             var type = parseType();
34328             parseExpected(31 /* GreaterThanToken */);
34329             var expression = parseSimpleUnaryExpression();
34330             return finishNode(factory.createTypeAssertion(type, expression), pos);
34331         }
34332         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
34333             nextToken();
34334             return ts.tokenIsIdentifierOrKeyword(token())
34335                 || token() === 22 /* OpenBracketToken */
34336                 || isTemplateStartOfTaggedTemplate();
34337         }
34338         function isStartOfOptionalPropertyOrElementAccessChain() {
34339             return token() === 28 /* QuestionDotToken */
34340                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
34341         }
34342         function tryReparseOptionalChain(node) {
34343             if (node.flags & 32 /* OptionalChain */) {
34344                 return true;
34345             }
34346             // check for an optional chain in a non-null expression
34347             if (ts.isNonNullExpression(node)) {
34348                 var expr = node.expression;
34349                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
34350                     expr = expr.expression;
34351                 }
34352                 if (expr.flags & 32 /* OptionalChain */) {
34353                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
34354                     while (ts.isNonNullExpression(node)) {
34355                         node.flags |= 32 /* OptionalChain */;
34356                         node = node.expression;
34357                     }
34358                     return true;
34359                 }
34360             }
34361             return false;
34362         }
34363         function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
34364             var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
34365             var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
34366             var propertyAccess = isOptionalChain ?
34367                 factory.createPropertyAccessChain(expression, questionDotToken, name) :
34368                 factory.createPropertyAccessExpression(expression, name);
34369             if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
34370                 parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
34371             }
34372             return finishNode(propertyAccess, pos);
34373         }
34374         function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
34375             var argumentExpression;
34376             if (token() === 23 /* CloseBracketToken */) {
34377                 argumentExpression = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
34378             }
34379             else {
34380                 var argument = allowInAnd(parseExpression);
34381                 if (ts.isStringOrNumericLiteralLike(argument)) {
34382                     argument.text = internIdentifier(argument.text);
34383                 }
34384                 argumentExpression = argument;
34385             }
34386             parseExpected(23 /* CloseBracketToken */);
34387             var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
34388                 factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
34389                 factory.createElementAccessExpression(expression, argumentExpression);
34390             return finishNode(indexedAccess, pos);
34391         }
34392         function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
34393             while (true) {
34394                 var questionDotToken = void 0;
34395                 var isPropertyAccess = false;
34396                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
34397                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
34398                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
34399                 }
34400                 else {
34401                     isPropertyAccess = parseOptional(24 /* DotToken */);
34402                 }
34403                 if (isPropertyAccess) {
34404                     expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
34405                     continue;
34406                 }
34407                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
34408                     nextToken();
34409                     expression = finishNode(factory.createNonNullExpression(expression), pos);
34410                     continue;
34411                 }
34412                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
34413                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
34414                     expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
34415                     continue;
34416                 }
34417                 if (isTemplateStartOfTaggedTemplate()) {
34418                     expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
34419                     continue;
34420                 }
34421                 return expression;
34422             }
34423         }
34424         function isTemplateStartOfTaggedTemplate() {
34425             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
34426         }
34427         function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
34428             var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
34429                 (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
34430                 parseTemplateExpression(/*isTaggedTemplate*/ true));
34431             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
34432                 tagExpression.flags |= 32 /* OptionalChain */;
34433             }
34434             tagExpression.questionDotToken = questionDotToken;
34435             return finishNode(tagExpression, pos);
34436         }
34437         function parseCallExpressionRest(pos, expression) {
34438             while (true) {
34439                 expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
34440                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
34441                 // handle 'foo<<T>()'
34442                 // parse template arguments only in TypeScript files (not in JavaScript files).
34443                 if ((contextFlags & 131072 /* JavaScriptFile */) === 0 && (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */)) {
34444                     // See if this is the start of a generic invocation.  If so, consume it and
34445                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
34446                     // part of an arithmetic expression.  Break out so we consume it higher in the
34447                     // stack.
34448                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
34449                     if (typeArguments) {
34450                         if (isTemplateStartOfTaggedTemplate()) {
34451                             expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
34452                             continue;
34453                         }
34454                         var argumentList = parseArgumentList();
34455                         var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
34456                             factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
34457                             factory.createCallExpression(expression, typeArguments, argumentList);
34458                         expression = finishNode(callExpr, pos);
34459                         continue;
34460                     }
34461                 }
34462                 else if (token() === 20 /* OpenParenToken */) {
34463                     var argumentList = parseArgumentList();
34464                     var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
34465                         factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
34466                         factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
34467                     expression = finishNode(callExpr, pos);
34468                     continue;
34469                 }
34470                 if (questionDotToken) {
34471                     // We failed to parse anything, so report a missing identifier here.
34472                     var name = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
34473                     expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
34474                 }
34475                 break;
34476             }
34477             return expression;
34478         }
34479         function parseArgumentList() {
34480             parseExpected(20 /* OpenParenToken */);
34481             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
34482             parseExpected(21 /* CloseParenToken */);
34483             return result;
34484         }
34485         function parseTypeArgumentsInExpression() {
34486             if ((contextFlags & 131072 /* JavaScriptFile */) !== 0) {
34487                 // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators.
34488                 return undefined;
34489             }
34490             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
34491                 return undefined;
34492             }
34493             nextToken();
34494             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
34495             if (!parseExpected(31 /* GreaterThanToken */)) {
34496                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
34497                 return undefined;
34498             }
34499             // If we have a '<', then only parse this as a argument list if the type arguments
34500             // are complete and we have an open paren.  if we don't, rewind and return nothing.
34501             return typeArguments && canFollowTypeArgumentsInExpression()
34502                 ? typeArguments
34503                 : undefined;
34504         }
34505         function canFollowTypeArgumentsInExpression() {
34506             switch (token()) {
34507                 case 20 /* OpenParenToken */: // foo<x>(
34508                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
34509                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
34510                 // these are the only tokens can legally follow a type argument
34511                 // list. So we definitely want to treat them as type arg lists.
34512                 // falls through
34513                 case 24 /* DotToken */: // foo<x>.
34514                 case 21 /* CloseParenToken */: // foo<x>)
34515                 case 23 /* CloseBracketToken */: // foo<x>]
34516                 case 58 /* ColonToken */: // foo<x>:
34517                 case 26 /* SemicolonToken */: // foo<x>;
34518                 case 57 /* QuestionToken */: // foo<x>?
34519                 case 34 /* EqualsEqualsToken */: // foo<x> ==
34520                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
34521                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
34522                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
34523                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
34524                 case 56 /* BarBarToken */: // foo<x> ||
34525                 case 60 /* QuestionQuestionToken */: // foo<x> ??
34526                 case 52 /* CaretToken */: // foo<x> ^
34527                 case 50 /* AmpersandToken */: // foo<x> &
34528                 case 51 /* BarToken */: // foo<x> |
34529                 case 19 /* CloseBraceToken */: // foo<x> }
34530                 case 1 /* EndOfFileToken */: // foo<x>
34531                     // these cases can't legally follow a type arg list.  However, they're not legal
34532                     // expressions either.  The user is probably in the middle of a generic type. So
34533                     // treat it as such.
34534                     return true;
34535                 case 27 /* CommaToken */: // foo<x>,
34536                 case 18 /* OpenBraceToken */: // foo<x> {
34537                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
34538                 // as an invocation expression.  Instead, we want to parse out the expression
34539                 // in isolation from the type arguments.
34540                 // falls through
34541                 default:
34542                     // Anything else treat as an expression.
34543                     return false;
34544             }
34545         }
34546         function parsePrimaryExpression() {
34547             switch (token()) {
34548                 case 8 /* NumericLiteral */:
34549                 case 9 /* BigIntLiteral */:
34550                 case 10 /* StringLiteral */:
34551                 case 14 /* NoSubstitutionTemplateLiteral */:
34552                     return parseLiteralNode();
34553                 case 108 /* ThisKeyword */:
34554                 case 106 /* SuperKeyword */:
34555                 case 104 /* NullKeyword */:
34556                 case 110 /* TrueKeyword */:
34557                 case 95 /* FalseKeyword */:
34558                     return parseTokenNode();
34559                 case 20 /* OpenParenToken */:
34560                     return parseParenthesizedExpression();
34561                 case 22 /* OpenBracketToken */:
34562                     return parseArrayLiteralExpression();
34563                 case 18 /* OpenBraceToken */:
34564                     return parseObjectLiteralExpression();
34565                 case 131 /* AsyncKeyword */:
34566                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
34567                     // If we encounter `async [no LineTerminator here] function` then this is an async
34568                     // function; otherwise, its an identifier.
34569                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
34570                         break;
34571                     }
34572                     return parseFunctionExpression();
34573                 case 84 /* ClassKeyword */:
34574                     return parseClassExpression();
34575                 case 98 /* FunctionKeyword */:
34576                     return parseFunctionExpression();
34577                 case 103 /* NewKeyword */:
34578                     return parseNewExpressionOrNewDotTarget();
34579                 case 43 /* SlashToken */:
34580                 case 68 /* SlashEqualsToken */:
34581                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
34582                         return parseLiteralNode();
34583                     }
34584                     break;
34585                 case 15 /* TemplateHead */:
34586                     return parseTemplateExpression(/* isTaggedTemplate */ false);
34587                 case 80 /* PrivateIdentifier */:
34588                     return parsePrivateIdentifier();
34589             }
34590             return parseIdentifier(ts.Diagnostics.Expression_expected);
34591         }
34592         function parseParenthesizedExpression() {
34593             var pos = getNodePos();
34594             var hasJSDoc = hasPrecedingJSDocComment();
34595             parseExpected(20 /* OpenParenToken */);
34596             var expression = allowInAnd(parseExpression);
34597             parseExpected(21 /* CloseParenToken */);
34598             return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
34599         }
34600         function parseSpreadElement() {
34601             var pos = getNodePos();
34602             parseExpected(25 /* DotDotDotToken */);
34603             var expression = parseAssignmentExpressionOrHigher();
34604             return finishNode(factory.createSpreadElement(expression), pos);
34605         }
34606         function parseArgumentOrArrayLiteralElement() {
34607             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
34608                 token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
34609                     parseAssignmentExpressionOrHigher();
34610         }
34611         function parseArgumentExpression() {
34612             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
34613         }
34614         function parseArrayLiteralExpression() {
34615             var pos = getNodePos();
34616             parseExpected(22 /* OpenBracketToken */);
34617             var multiLine = scanner.hasPrecedingLineBreak();
34618             var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
34619             parseExpected(23 /* CloseBracketToken */);
34620             return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
34621         }
34622         function parseObjectLiteralElement() {
34623             var pos = getNodePos();
34624             var hasJSDoc = hasPrecedingJSDocComment();
34625             if (parseOptionalToken(25 /* DotDotDotToken */)) {
34626                 var expression = parseAssignmentExpressionOrHigher();
34627                 return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
34628             }
34629             var decorators = parseDecorators();
34630             var modifiers = parseModifiers();
34631             if (parseContextualModifier(136 /* GetKeyword */)) {
34632                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 171 /* GetAccessor */);
34633             }
34634             if (parseContextualModifier(148 /* SetKeyword */)) {
34635                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SetAccessor */);
34636             }
34637             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
34638             var tokenIsIdentifier = isIdentifier();
34639             var name = parsePropertyName();
34640             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
34641             var questionToken = parseOptionalToken(57 /* QuestionToken */);
34642             var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
34643             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
34644                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
34645             }
34646             // check if it is short-hand property assignment or normal property assignment
34647             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
34648             // CoverInitializedName[Yield] :
34649             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
34650             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
34651             var node;
34652             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
34653             if (isShorthandPropertyAssignment) {
34654                 var equalsToken = parseOptionalToken(63 /* EqualsToken */);
34655                 var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
34656                 node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
34657                 // Save equals token for error reporting.
34658                 // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
34659                 node.equalsToken = equalsToken;
34660             }
34661             else {
34662                 parseExpected(58 /* ColonToken */);
34663                 var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
34664                 node = factory.createPropertyAssignment(name, initializer);
34665             }
34666             // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
34667             node.decorators = decorators;
34668             node.modifiers = modifiers;
34669             node.questionToken = questionToken;
34670             node.exclamationToken = exclamationToken;
34671             return withJSDoc(finishNode(node, pos), hasJSDoc);
34672         }
34673         function parseObjectLiteralExpression() {
34674             var pos = getNodePos();
34675             var openBracePosition = scanner.getTokenPos();
34676             parseExpected(18 /* OpenBraceToken */);
34677             var multiLine = scanner.hasPrecedingLineBreak();
34678             var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
34679             if (!parseExpected(19 /* CloseBraceToken */)) {
34680                 var lastError = ts.lastOrUndefined(parseDiagnostics);
34681                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
34682                     ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
34683                 }
34684             }
34685             return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
34686         }
34687         function parseFunctionExpression() {
34688             // GeneratorExpression:
34689             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
34690             //
34691             // FunctionExpression:
34692             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
34693             var savedDecoratorContext = inDecoratorContext();
34694             setDecoratorContext(/*val*/ false);
34695             var pos = getNodePos();
34696             var hasJSDoc = hasPrecedingJSDocComment();
34697             var modifiers = parseModifiers();
34698             parseExpected(98 /* FunctionKeyword */);
34699             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
34700             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
34701             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
34702             var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
34703                 isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
34704                     isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
34705                         parseOptionalBindingIdentifier();
34706             var typeParameters = parseTypeParameters();
34707             var parameters = parseParameters(isGenerator | isAsync);
34708             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
34709             var body = parseFunctionBlock(isGenerator | isAsync);
34710             setDecoratorContext(savedDecoratorContext);
34711             var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
34712             return withJSDoc(finishNode(node, pos), hasJSDoc);
34713         }
34714         function parseOptionalBindingIdentifier() {
34715             return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
34716         }
34717         function parseNewExpressionOrNewDotTarget() {
34718             var pos = getNodePos();
34719             parseExpected(103 /* NewKeyword */);
34720             if (parseOptional(24 /* DotToken */)) {
34721                 var name = parseIdentifierName();
34722                 return finishNode(factory.createMetaProperty(103 /* NewKeyword */, name), pos);
34723             }
34724             var expressionPos = getNodePos();
34725             var expression = parsePrimaryExpression();
34726             var typeArguments;
34727             while (true) {
34728                 expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
34729                 typeArguments = tryParse(parseTypeArgumentsInExpression);
34730                 if (isTemplateStartOfTaggedTemplate()) {
34731                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
34732                     expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
34733                     typeArguments = undefined;
34734                 }
34735                 break;
34736             }
34737             var argumentsArray;
34738             if (token() === 20 /* OpenParenToken */) {
34739                 argumentsArray = parseArgumentList();
34740             }
34741             else if (typeArguments) {
34742                 parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
34743             }
34744             return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
34745         }
34746         // STATEMENTS
34747         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
34748             var pos = getNodePos();
34749             var hasJSDoc = hasPrecedingJSDocComment();
34750             var openBracePosition = scanner.getTokenPos();
34751             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
34752                 var multiLine = scanner.hasPrecedingLineBreak();
34753                 var statements = parseList(1 /* BlockStatements */, parseStatement);
34754                 if (!parseExpected(19 /* CloseBraceToken */)) {
34755                     var lastError = ts.lastOrUndefined(parseDiagnostics);
34756                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
34757                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
34758                     }
34759                 }
34760                 var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc);
34761                 if (token() === 63 /* EqualsToken */) {
34762                     parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses);
34763                     nextToken();
34764                 }
34765                 return result;
34766             }
34767             else {
34768                 var statements = createMissingList();
34769                 return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc);
34770             }
34771         }
34772         function parseFunctionBlock(flags, diagnosticMessage) {
34773             var savedYieldContext = inYieldContext();
34774             setYieldContext(!!(flags & 1 /* Yield */));
34775             var savedAwaitContext = inAwaitContext();
34776             setAwaitContext(!!(flags & 2 /* Await */));
34777             var savedTopLevel = topLevel;
34778             topLevel = false;
34779             // We may be in a [Decorator] context when parsing a function expression or
34780             // arrow function. The body of the function is not in [Decorator] context.
34781             var saveDecoratorContext = inDecoratorContext();
34782             if (saveDecoratorContext) {
34783                 setDecoratorContext(/*val*/ false);
34784             }
34785             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
34786             if (saveDecoratorContext) {
34787                 setDecoratorContext(/*val*/ true);
34788             }
34789             topLevel = savedTopLevel;
34790             setYieldContext(savedYieldContext);
34791             setAwaitContext(savedAwaitContext);
34792             return block;
34793         }
34794         function parseEmptyStatement() {
34795             var pos = getNodePos();
34796             var hasJSDoc = hasPrecedingJSDocComment();
34797             parseExpected(26 /* SemicolonToken */);
34798             return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc);
34799         }
34800         function parseIfStatement() {
34801             var pos = getNodePos();
34802             var hasJSDoc = hasPrecedingJSDocComment();
34803             parseExpected(99 /* IfKeyword */);
34804             parseExpected(20 /* OpenParenToken */);
34805             var expression = allowInAnd(parseExpression);
34806             parseExpected(21 /* CloseParenToken */);
34807             var thenStatement = parseStatement();
34808             var elseStatement = parseOptional(91 /* ElseKeyword */) ? parseStatement() : undefined;
34809             return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc);
34810         }
34811         function parseDoStatement() {
34812             var pos = getNodePos();
34813             var hasJSDoc = hasPrecedingJSDocComment();
34814             parseExpected(90 /* DoKeyword */);
34815             var statement = parseStatement();
34816             parseExpected(115 /* WhileKeyword */);
34817             parseExpected(20 /* OpenParenToken */);
34818             var expression = allowInAnd(parseExpression);
34819             parseExpected(21 /* CloseParenToken */);
34820             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
34821             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
34822             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
34823             //  do;while(0)x will have a semicolon inserted before x.
34824             parseOptional(26 /* SemicolonToken */);
34825             return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc);
34826         }
34827         function parseWhileStatement() {
34828             var pos = getNodePos();
34829             var hasJSDoc = hasPrecedingJSDocComment();
34830             parseExpected(115 /* WhileKeyword */);
34831             parseExpected(20 /* OpenParenToken */);
34832             var expression = allowInAnd(parseExpression);
34833             parseExpected(21 /* CloseParenToken */);
34834             var statement = parseStatement();
34835             return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc);
34836         }
34837         function parseForOrForInOrForOfStatement() {
34838             var pos = getNodePos();
34839             var hasJSDoc = hasPrecedingJSDocComment();
34840             parseExpected(97 /* ForKeyword */);
34841             var awaitToken = parseOptionalToken(132 /* AwaitKeyword */);
34842             parseExpected(20 /* OpenParenToken */);
34843             var initializer;
34844             if (token() !== 26 /* SemicolonToken */) {
34845                 if (token() === 113 /* VarKeyword */ || token() === 119 /* LetKeyword */ || token() === 85 /* ConstKeyword */) {
34846                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
34847                 }
34848                 else {
34849                     initializer = disallowInAnd(parseExpression);
34850                 }
34851             }
34852             var node;
34853             if (awaitToken ? parseExpected(159 /* OfKeyword */) : parseOptional(159 /* OfKeyword */)) {
34854                 var expression = allowInAnd(parseAssignmentExpressionOrHigher);
34855                 parseExpected(21 /* CloseParenToken */);
34856                 node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
34857             }
34858             else if (parseOptional(101 /* InKeyword */)) {
34859                 var expression = allowInAnd(parseExpression);
34860                 parseExpected(21 /* CloseParenToken */);
34861                 node = factory.createForInStatement(initializer, expression, parseStatement());
34862             }
34863             else {
34864                 parseExpected(26 /* SemicolonToken */);
34865                 var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
34866                     ? allowInAnd(parseExpression)
34867                     : undefined;
34868                 parseExpected(26 /* SemicolonToken */);
34869                 var incrementor = token() !== 21 /* CloseParenToken */
34870                     ? allowInAnd(parseExpression)
34871                     : undefined;
34872                 parseExpected(21 /* CloseParenToken */);
34873                 node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
34874             }
34875             return withJSDoc(finishNode(node, pos), hasJSDoc);
34876         }
34877         function parseBreakOrContinueStatement(kind) {
34878             var pos = getNodePos();
34879             var hasJSDoc = hasPrecedingJSDocComment();
34880             parseExpected(kind === 245 /* BreakStatement */ ? 81 /* BreakKeyword */ : 86 /* ContinueKeyword */);
34881             var label = canParseSemicolon() ? undefined : parseIdentifier();
34882             parseSemicolon();
34883             var node = kind === 245 /* BreakStatement */
34884                 ? factory.createBreakStatement(label)
34885                 : factory.createContinueStatement(label);
34886             return withJSDoc(finishNode(node, pos), hasJSDoc);
34887         }
34888         function parseReturnStatement() {
34889             var pos = getNodePos();
34890             var hasJSDoc = hasPrecedingJSDocComment();
34891             parseExpected(105 /* ReturnKeyword */);
34892             var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
34893             parseSemicolon();
34894             return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc);
34895         }
34896         function parseWithStatement() {
34897             var pos = getNodePos();
34898             var hasJSDoc = hasPrecedingJSDocComment();
34899             parseExpected(116 /* WithKeyword */);
34900             parseExpected(20 /* OpenParenToken */);
34901             var expression = allowInAnd(parseExpression);
34902             parseExpected(21 /* CloseParenToken */);
34903             var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
34904             return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc);
34905         }
34906         function parseCaseClause() {
34907             var pos = getNodePos();
34908             parseExpected(82 /* CaseKeyword */);
34909             var expression = allowInAnd(parseExpression);
34910             parseExpected(58 /* ColonToken */);
34911             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
34912             return finishNode(factory.createCaseClause(expression, statements), pos);
34913         }
34914         function parseDefaultClause() {
34915             var pos = getNodePos();
34916             parseExpected(88 /* DefaultKeyword */);
34917             parseExpected(58 /* ColonToken */);
34918             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
34919             return finishNode(factory.createDefaultClause(statements), pos);
34920         }
34921         function parseCaseOrDefaultClause() {
34922             return token() === 82 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
34923         }
34924         function parseCaseBlock() {
34925             var pos = getNodePos();
34926             parseExpected(18 /* OpenBraceToken */);
34927             var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
34928             parseExpected(19 /* CloseBraceToken */);
34929             return finishNode(factory.createCaseBlock(clauses), pos);
34930         }
34931         function parseSwitchStatement() {
34932             var pos = getNodePos();
34933             var hasJSDoc = hasPrecedingJSDocComment();
34934             parseExpected(107 /* SwitchKeyword */);
34935             parseExpected(20 /* OpenParenToken */);
34936             var expression = allowInAnd(parseExpression);
34937             parseExpected(21 /* CloseParenToken */);
34938             var caseBlock = parseCaseBlock();
34939             return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc);
34940         }
34941         function parseThrowStatement() {
34942             // ThrowStatement[Yield] :
34943             //      throw [no LineTerminator here]Expression[In, ?Yield];
34944             var pos = getNodePos();
34945             var hasJSDoc = hasPrecedingJSDocComment();
34946             parseExpected(109 /* ThrowKeyword */);
34947             // Because of automatic semicolon insertion, we need to report error if this
34948             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
34949             // directly as that might consume an expression on the following line.
34950             // Instead, we create a "missing" identifier, but don't report an error. The actual error
34951             // will be reported in the grammar walker.
34952             var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
34953             if (expression === undefined) {
34954                 identifierCount++;
34955                 expression = finishNode(factory.createIdentifier(""), getNodePos());
34956             }
34957             if (!tryParseSemicolon()) {
34958                 parseErrorForMissingSemicolonAfter(expression);
34959             }
34960             return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc);
34961         }
34962         // TODO: Review for error recovery
34963         function parseTryStatement() {
34964             var pos = getNodePos();
34965             var hasJSDoc = hasPrecedingJSDocComment();
34966             parseExpected(111 /* TryKeyword */);
34967             var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
34968             var catchClause = token() === 83 /* CatchKeyword */ ? parseCatchClause() : undefined;
34969             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
34970             // one out no matter what.
34971             var finallyBlock;
34972             if (!catchClause || token() === 96 /* FinallyKeyword */) {
34973                 parseExpected(96 /* FinallyKeyword */);
34974                 finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
34975             }
34976             return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc);
34977         }
34978         function parseCatchClause() {
34979             var pos = getNodePos();
34980             parseExpected(83 /* CatchKeyword */);
34981             var variableDeclaration;
34982             if (parseOptional(20 /* OpenParenToken */)) {
34983                 variableDeclaration = parseVariableDeclaration();
34984                 parseExpected(21 /* CloseParenToken */);
34985             }
34986             else {
34987                 // Keep shape of node to avoid degrading performance.
34988                 variableDeclaration = undefined;
34989             }
34990             var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
34991             return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
34992         }
34993         function parseDebuggerStatement() {
34994             var pos = getNodePos();
34995             var hasJSDoc = hasPrecedingJSDocComment();
34996             parseExpected(87 /* DebuggerKeyword */);
34997             parseSemicolon();
34998             return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc);
34999         }
35000         function parseExpressionOrLabeledStatement() {
35001             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
35002             // out an expression, seeing if it is identifier and then seeing if it is followed by
35003             // a colon.
35004             var pos = getNodePos();
35005             var hasJSDoc = hasPrecedingJSDocComment();
35006             var node;
35007             var hasParen = token() === 20 /* OpenParenToken */;
35008             var expression = allowInAnd(parseExpression);
35009             if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
35010                 node = factory.createLabeledStatement(expression, parseStatement());
35011             }
35012             else {
35013                 if (!tryParseSemicolon()) {
35014                     parseErrorForMissingSemicolonAfter(expression);
35015                 }
35016                 node = factory.createExpressionStatement(expression);
35017                 if (hasParen) {
35018                     // do not parse the same jsdoc twice
35019                     hasJSDoc = false;
35020                 }
35021             }
35022             return withJSDoc(finishNode(node, pos), hasJSDoc);
35023         }
35024         function nextTokenIsIdentifierOrKeywordOnSameLine() {
35025             nextToken();
35026             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
35027         }
35028         function nextTokenIsClassKeywordOnSameLine() {
35029             nextToken();
35030             return token() === 84 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
35031         }
35032         function nextTokenIsFunctionKeywordOnSameLine() {
35033             nextToken();
35034             return token() === 98 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
35035         }
35036         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
35037             nextToken();
35038             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
35039         }
35040         function isDeclaration() {
35041             while (true) {
35042                 switch (token()) {
35043                     case 113 /* VarKeyword */:
35044                     case 119 /* LetKeyword */:
35045                     case 85 /* ConstKeyword */:
35046                     case 98 /* FunctionKeyword */:
35047                     case 84 /* ClassKeyword */:
35048                     case 92 /* EnumKeyword */:
35049                         return true;
35050                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
35051                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
35052                     // count on to parse out the respective declarations. For instance, we exploit this to say that
35053                     //
35054                     //    namespace n
35055                     //
35056                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
35057                     //
35058                     //    namespace
35059                     //    n
35060                     //
35061                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
35062                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
35063                     //
35064                     // *Note*: 'interface' is actually a strict mode reserved word. So while
35065                     //
35066                     //   "use strict"
35067                     //   interface
35068                     //   I {}
35069                     //
35070                     // could be legal, it would add complexity for very little gain.
35071                     case 118 /* InterfaceKeyword */:
35072                     case 151 /* TypeKeyword */:
35073                         return nextTokenIsIdentifierOnSameLine();
35074                     case 141 /* ModuleKeyword */:
35075                     case 142 /* NamespaceKeyword */:
35076                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
35077                     case 126 /* AbstractKeyword */:
35078                     case 131 /* AsyncKeyword */:
35079                     case 135 /* DeclareKeyword */:
35080                     case 121 /* PrivateKeyword */:
35081                     case 122 /* ProtectedKeyword */:
35082                     case 123 /* PublicKeyword */:
35083                     case 144 /* ReadonlyKeyword */:
35084                         nextToken();
35085                         // ASI takes effect for this modifier.
35086                         if (scanner.hasPrecedingLineBreak()) {
35087                             return false;
35088                         }
35089                         continue;
35090                     case 156 /* GlobalKeyword */:
35091                         nextToken();
35092                         return token() === 18 /* OpenBraceToken */ || token() === 79 /* Identifier */ || token() === 93 /* ExportKeyword */;
35093                     case 100 /* ImportKeyword */:
35094                         nextToken();
35095                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
35096                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
35097                     case 93 /* ExportKeyword */:
35098                         var currentToken_1 = nextToken();
35099                         if (currentToken_1 === 151 /* TypeKeyword */) {
35100                             currentToken_1 = lookAhead(nextToken);
35101                         }
35102                         if (currentToken_1 === 63 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
35103                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 88 /* DefaultKeyword */ ||
35104                             currentToken_1 === 127 /* AsKeyword */) {
35105                             return true;
35106                         }
35107                         continue;
35108                     case 124 /* StaticKeyword */:
35109                         nextToken();
35110                         continue;
35111                     default:
35112                         return false;
35113                 }
35114             }
35115         }
35116         function isStartOfDeclaration() {
35117             return lookAhead(isDeclaration);
35118         }
35119         function isStartOfStatement() {
35120             switch (token()) {
35121                 case 59 /* AtToken */:
35122                 case 26 /* SemicolonToken */:
35123                 case 18 /* OpenBraceToken */:
35124                 case 113 /* VarKeyword */:
35125                 case 119 /* LetKeyword */:
35126                 case 98 /* FunctionKeyword */:
35127                 case 84 /* ClassKeyword */:
35128                 case 92 /* EnumKeyword */:
35129                 case 99 /* IfKeyword */:
35130                 case 90 /* DoKeyword */:
35131                 case 115 /* WhileKeyword */:
35132                 case 97 /* ForKeyword */:
35133                 case 86 /* ContinueKeyword */:
35134                 case 81 /* BreakKeyword */:
35135                 case 105 /* ReturnKeyword */:
35136                 case 116 /* WithKeyword */:
35137                 case 107 /* SwitchKeyword */:
35138                 case 109 /* ThrowKeyword */:
35139                 case 111 /* TryKeyword */:
35140                 case 87 /* DebuggerKeyword */:
35141                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
35142                 // however, we say they are here so that we may gracefully parse them and error later.
35143                 // falls through
35144                 case 83 /* CatchKeyword */:
35145                 case 96 /* FinallyKeyword */:
35146                     return true;
35147                 case 100 /* ImportKeyword */:
35148                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
35149                 case 85 /* ConstKeyword */:
35150                 case 93 /* ExportKeyword */:
35151                     return isStartOfDeclaration();
35152                 case 131 /* AsyncKeyword */:
35153                 case 135 /* DeclareKeyword */:
35154                 case 118 /* InterfaceKeyword */:
35155                 case 141 /* ModuleKeyword */:
35156                 case 142 /* NamespaceKeyword */:
35157                 case 151 /* TypeKeyword */:
35158                 case 156 /* GlobalKeyword */:
35159                     // When these don't start a declaration, they're an identifier in an expression statement
35160                     return true;
35161                 case 123 /* PublicKeyword */:
35162                 case 121 /* PrivateKeyword */:
35163                 case 122 /* ProtectedKeyword */:
35164                 case 124 /* StaticKeyword */:
35165                 case 144 /* ReadonlyKeyword */:
35166                     // When these don't start a declaration, they may be the start of a class member if an identifier
35167                     // immediately follows. Otherwise they're an identifier in an expression statement.
35168                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
35169                 default:
35170                     return isStartOfExpression();
35171             }
35172         }
35173         function nextTokenIsBindingIdentifierOrStartOfDestructuring() {
35174             nextToken();
35175             return isBindingIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
35176         }
35177         function isLetDeclaration() {
35178             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
35179             // or [.
35180             return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring);
35181         }
35182         function parseStatement() {
35183             switch (token()) {
35184                 case 26 /* SemicolonToken */:
35185                     return parseEmptyStatement();
35186                 case 18 /* OpenBraceToken */:
35187                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
35188                 case 113 /* VarKeyword */:
35189                     return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
35190                 case 119 /* LetKeyword */:
35191                     if (isLetDeclaration()) {
35192                         return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
35193                     }
35194                     break;
35195                 case 98 /* FunctionKeyword */:
35196                     return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
35197                 case 84 /* ClassKeyword */:
35198                     return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
35199                 case 99 /* IfKeyword */:
35200                     return parseIfStatement();
35201                 case 90 /* DoKeyword */:
35202                     return parseDoStatement();
35203                 case 115 /* WhileKeyword */:
35204                     return parseWhileStatement();
35205                 case 97 /* ForKeyword */:
35206                     return parseForOrForInOrForOfStatement();
35207                 case 86 /* ContinueKeyword */:
35208                     return parseBreakOrContinueStatement(244 /* ContinueStatement */);
35209                 case 81 /* BreakKeyword */:
35210                     return parseBreakOrContinueStatement(245 /* BreakStatement */);
35211                 case 105 /* ReturnKeyword */:
35212                     return parseReturnStatement();
35213                 case 116 /* WithKeyword */:
35214                     return parseWithStatement();
35215                 case 107 /* SwitchKeyword */:
35216                     return parseSwitchStatement();
35217                 case 109 /* ThrowKeyword */:
35218                     return parseThrowStatement();
35219                 case 111 /* TryKeyword */:
35220                 // Include 'catch' and 'finally' for error recovery.
35221                 // falls through
35222                 case 83 /* CatchKeyword */:
35223                 case 96 /* FinallyKeyword */:
35224                     return parseTryStatement();
35225                 case 87 /* DebuggerKeyword */:
35226                     return parseDebuggerStatement();
35227                 case 59 /* AtToken */:
35228                     return parseDeclaration();
35229                 case 131 /* AsyncKeyword */:
35230                 case 118 /* InterfaceKeyword */:
35231                 case 151 /* TypeKeyword */:
35232                 case 141 /* ModuleKeyword */:
35233                 case 142 /* NamespaceKeyword */:
35234                 case 135 /* DeclareKeyword */:
35235                 case 85 /* ConstKeyword */:
35236                 case 92 /* EnumKeyword */:
35237                 case 93 /* ExportKeyword */:
35238                 case 100 /* ImportKeyword */:
35239                 case 121 /* PrivateKeyword */:
35240                 case 122 /* ProtectedKeyword */:
35241                 case 123 /* PublicKeyword */:
35242                 case 126 /* AbstractKeyword */:
35243                 case 124 /* StaticKeyword */:
35244                 case 144 /* ReadonlyKeyword */:
35245                 case 156 /* GlobalKeyword */:
35246                     if (isStartOfDeclaration()) {
35247                         return parseDeclaration();
35248                     }
35249                     break;
35250             }
35251             return parseExpressionOrLabeledStatement();
35252         }
35253         function isDeclareModifier(modifier) {
35254             return modifier.kind === 135 /* DeclareKeyword */;
35255         }
35256         function parseDeclaration() {
35257             // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
35258             //       if we can't reuse the declaration, so that we don't do this work twice?
35259             //
35260             // `parseListElement` attempted to get the reused node at this position,
35261             // but the ambient context flag was not yet set, so the node appeared
35262             // not reusable in that context.
35263             var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
35264             if (isAmbient) {
35265                 var node = tryReuseAmbientDeclaration();
35266                 if (node) {
35267                     return node;
35268                 }
35269             }
35270             var pos = getNodePos();
35271             var hasJSDoc = hasPrecedingJSDocComment();
35272             var decorators = parseDecorators();
35273             var modifiers = parseModifiers();
35274             if (isAmbient) {
35275                 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
35276                     var m = _a[_i];
35277                     m.flags |= 8388608 /* Ambient */;
35278                 }
35279                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
35280             }
35281             else {
35282                 return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
35283             }
35284         }
35285         function tryReuseAmbientDeclaration() {
35286             return doInsideOfContext(8388608 /* Ambient */, function () {
35287                 var node = currentNode(parsingContext);
35288                 if (node) {
35289                     return consumeNode(node);
35290                 }
35291             });
35292         }
35293         function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
35294             switch (token()) {
35295                 case 113 /* VarKeyword */:
35296                 case 119 /* LetKeyword */:
35297                 case 85 /* ConstKeyword */:
35298                     return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
35299                 case 98 /* FunctionKeyword */:
35300                     return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
35301                 case 84 /* ClassKeyword */:
35302                     return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
35303                 case 118 /* InterfaceKeyword */:
35304                     return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
35305                 case 151 /* TypeKeyword */:
35306                     return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
35307                 case 92 /* EnumKeyword */:
35308                     return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
35309                 case 156 /* GlobalKeyword */:
35310                 case 141 /* ModuleKeyword */:
35311                 case 142 /* NamespaceKeyword */:
35312                     return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
35313                 case 100 /* ImportKeyword */:
35314                     return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
35315                 case 93 /* ExportKeyword */:
35316                     nextToken();
35317                     switch (token()) {
35318                         case 88 /* DefaultKeyword */:
35319                         case 63 /* EqualsToken */:
35320                             return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
35321                         case 127 /* AsKeyword */:
35322                             return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
35323                         default:
35324                             return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
35325                     }
35326                 default:
35327                     if (decorators || modifiers) {
35328                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
35329                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
35330                         var missing = createMissingNode(275 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
35331                         ts.setTextRangePos(missing, pos);
35332                         missing.decorators = decorators;
35333                         missing.modifiers = modifiers;
35334                         return missing;
35335                     }
35336                     return undefined; // TODO: GH#18217
35337             }
35338         }
35339         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
35340             nextToken();
35341             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
35342         }
35343         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
35344             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
35345                 parseSemicolon();
35346                 return;
35347             }
35348             return parseFunctionBlock(flags, diagnosticMessage);
35349         }
35350         // DECLARATIONS
35351         function parseArrayBindingElement() {
35352             var pos = getNodePos();
35353             if (token() === 27 /* CommaToken */) {
35354                 return finishNode(factory.createOmittedExpression(), pos);
35355             }
35356             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
35357             var name = parseIdentifierOrPattern();
35358             var initializer = parseInitializer();
35359             return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
35360         }
35361         function parseObjectBindingElement() {
35362             var pos = getNodePos();
35363             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
35364             var tokenIsIdentifier = isBindingIdentifier();
35365             var propertyName = parsePropertyName();
35366             var name;
35367             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
35368                 name = propertyName;
35369                 propertyName = undefined;
35370             }
35371             else {
35372                 parseExpected(58 /* ColonToken */);
35373                 name = parseIdentifierOrPattern();
35374             }
35375             var initializer = parseInitializer();
35376             return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
35377         }
35378         function parseObjectBindingPattern() {
35379             var pos = getNodePos();
35380             parseExpected(18 /* OpenBraceToken */);
35381             var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
35382             parseExpected(19 /* CloseBraceToken */);
35383             return finishNode(factory.createObjectBindingPattern(elements), pos);
35384         }
35385         function parseArrayBindingPattern() {
35386             var pos = getNodePos();
35387             parseExpected(22 /* OpenBracketToken */);
35388             var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
35389             parseExpected(23 /* CloseBracketToken */);
35390             return finishNode(factory.createArrayBindingPattern(elements), pos);
35391         }
35392         function isBindingIdentifierOrPrivateIdentifierOrPattern() {
35393             return token() === 18 /* OpenBraceToken */
35394                 || token() === 22 /* OpenBracketToken */
35395                 || token() === 80 /* PrivateIdentifier */
35396                 || isBindingIdentifier();
35397         }
35398         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
35399             if (token() === 22 /* OpenBracketToken */) {
35400                 return parseArrayBindingPattern();
35401             }
35402             if (token() === 18 /* OpenBraceToken */) {
35403                 return parseObjectBindingPattern();
35404             }
35405             return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
35406         }
35407         function parseVariableDeclarationAllowExclamation() {
35408             return parseVariableDeclaration(/*allowExclamation*/ true);
35409         }
35410         function parseVariableDeclaration(allowExclamation) {
35411             var pos = getNodePos();
35412             var hasJSDoc = hasPrecedingJSDocComment();
35413             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
35414             var exclamationToken;
35415             if (allowExclamation && name.kind === 79 /* Identifier */ &&
35416                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
35417                 exclamationToken = parseTokenNode();
35418             }
35419             var type = parseTypeAnnotation();
35420             var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
35421             var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
35422             return withJSDoc(finishNode(node, pos), hasJSDoc);
35423         }
35424         function parseVariableDeclarationList(inForStatementInitializer) {
35425             var pos = getNodePos();
35426             var flags = 0;
35427             switch (token()) {
35428                 case 113 /* VarKeyword */:
35429                     break;
35430                 case 119 /* LetKeyword */:
35431                     flags |= 1 /* Let */;
35432                     break;
35433                 case 85 /* ConstKeyword */:
35434                     flags |= 2 /* Const */;
35435                     break;
35436                 default:
35437                     ts.Debug.fail();
35438             }
35439             nextToken();
35440             // The user may have written the following:
35441             //
35442             //    for (let of X) { }
35443             //
35444             // In this case, we want to parse an empty declaration list, and then parse 'of'
35445             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
35446             // So we need to look ahead to determine if 'of' should be treated as a keyword in
35447             // this context.
35448             // The checker will then give an error that there is an empty declaration list.
35449             var declarations;
35450             if (token() === 159 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
35451                 declarations = createMissingList();
35452             }
35453             else {
35454                 var savedDisallowIn = inDisallowInContext();
35455                 setDisallowInContext(inForStatementInitializer);
35456                 declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
35457                 setDisallowInContext(savedDisallowIn);
35458             }
35459             return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
35460         }
35461         function canFollowContextualOfKeyword() {
35462             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
35463         }
35464         function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
35465             var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
35466             parseSemicolon();
35467             var node = factory.createVariableStatement(modifiers, declarationList);
35468             // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
35469             node.decorators = decorators;
35470             return withJSDoc(finishNode(node, pos), hasJSDoc);
35471         }
35472         function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
35473             var savedAwaitContext = inAwaitContext();
35474             var modifierFlags = ts.modifiersToFlags(modifiers);
35475             parseExpected(98 /* FunctionKeyword */);
35476             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
35477             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
35478             var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
35479             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
35480             var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
35481             var typeParameters = parseTypeParameters();
35482             if (modifierFlags & 1 /* Export */)
35483                 setAwaitContext(/*value*/ true);
35484             var parameters = parseParameters(isGenerator | isAsync);
35485             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
35486             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
35487             setAwaitContext(savedAwaitContext);
35488             var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
35489             return withJSDoc(finishNode(node, pos), hasJSDoc);
35490         }
35491         function parseConstructorName() {
35492             if (token() === 134 /* ConstructorKeyword */) {
35493                 return parseExpected(134 /* ConstructorKeyword */);
35494             }
35495             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
35496                 return tryParse(function () {
35497                     var literalNode = parseLiteralNode();
35498                     return literalNode.text === "constructor" ? literalNode : undefined;
35499                 });
35500             }
35501         }
35502         function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
35503             return tryParse(function () {
35504                 if (parseConstructorName()) {
35505                     var typeParameters = parseTypeParameters();
35506                     var parameters = parseParameters(0 /* None */);
35507                     var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
35508                     var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
35509                     var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
35510                     // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
35511                     node.typeParameters = typeParameters;
35512                     node.type = type;
35513                     return withJSDoc(finishNode(node, pos), hasJSDoc);
35514                 }
35515             });
35516         }
35517         function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
35518             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
35519             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
35520             var typeParameters = parseTypeParameters();
35521             var parameters = parseParameters(isGenerator | isAsync);
35522             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
35523             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
35524             var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
35525             // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
35526             node.exclamationToken = exclamationToken;
35527             return withJSDoc(finishNode(node, pos), hasJSDoc);
35528         }
35529         function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
35530             var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
35531             var type = parseTypeAnnotation();
35532             var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
35533             parseSemicolonAfterPropertyName(name, type, initializer);
35534             var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
35535             return withJSDoc(finishNode(node, pos), hasJSDoc);
35536         }
35537         function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
35538             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
35539             var name = parsePropertyName();
35540             // Note: this is not legal as per the grammar.  But we allow it in the parser and
35541             // report an error in the grammar checker.
35542             var questionToken = parseOptionalToken(57 /* QuestionToken */);
35543             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
35544                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
35545             }
35546             return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
35547         }
35548         function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
35549             var name = parsePropertyName();
35550             var typeParameters = parseTypeParameters();
35551             var parameters = parseParameters(0 /* None */);
35552             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
35553             var body = parseFunctionBlockOrSemicolon(0 /* None */);
35554             var node = kind === 171 /* GetAccessor */
35555                 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
35556                 : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
35557             // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
35558             node.typeParameters = typeParameters;
35559             if (type && node.kind === 172 /* SetAccessor */)
35560                 node.type = type;
35561             return withJSDoc(finishNode(node, pos), hasJSDoc);
35562         }
35563         function isClassMemberStart() {
35564             var idToken;
35565             if (token() === 59 /* AtToken */) {
35566                 return true;
35567             }
35568             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
35569             while (ts.isModifierKind(token())) {
35570                 idToken = token();
35571                 // If the idToken is a class modifier (protected, private, public, and static), it is
35572                 // certain that we are starting to parse class member. This allows better error recovery
35573                 // Example:
35574                 //      public foo() ...     // true
35575                 //      public @dec blah ... // true; we will then report an error later
35576                 //      export public ...    // true; we will then report an error later
35577                 if (ts.isClassMemberModifier(idToken)) {
35578                     return true;
35579                 }
35580                 nextToken();
35581             }
35582             if (token() === 41 /* AsteriskToken */) {
35583                 return true;
35584             }
35585             // Try to get the first property-like token following all modifiers.
35586             // This can either be an identifier or the 'get' or 'set' keywords.
35587             if (isLiteralPropertyName()) {
35588                 idToken = token();
35589                 nextToken();
35590             }
35591             // Index signatures and computed properties are class members; we can parse.
35592             if (token() === 22 /* OpenBracketToken */) {
35593                 return true;
35594             }
35595             // If we were able to get any potential identifier...
35596             if (idToken !== undefined) {
35597                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
35598                 if (!ts.isKeyword(idToken) || idToken === 148 /* SetKeyword */ || idToken === 136 /* GetKeyword */) {
35599                     return true;
35600                 }
35601                 // If it *is* a keyword, but not an accessor, check a little farther along
35602                 // to see if it should actually be parsed as a class member.
35603                 switch (token()) {
35604                     case 20 /* OpenParenToken */: // Method declaration
35605                     case 29 /* LessThanToken */: // Generic Method declaration
35606                     case 53 /* ExclamationToken */: // Non-null assertion on property name
35607                     case 58 /* ColonToken */: // Type Annotation for declaration
35608                     case 63 /* EqualsToken */: // Initializer for declaration
35609                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
35610                         return true;
35611                     default:
35612                         // Covers
35613                         //  - Semicolons     (declaration termination)
35614                         //  - Closing braces (end-of-class, must be declaration)
35615                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
35616                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
35617                         return canParseSemicolon();
35618                 }
35619             }
35620             return false;
35621         }
35622         function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) {
35623             parseExpectedToken(124 /* StaticKeyword */);
35624             var body = parseClassStaticBlockBody();
35625             return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc);
35626         }
35627         function parseClassStaticBlockBody() {
35628             var savedYieldContext = inYieldContext();
35629             var savedAwaitContext = inAwaitContext();
35630             setYieldContext(false);
35631             setAwaitContext(true);
35632             var body = parseBlock(/*ignoreMissingOpenBrace*/ false);
35633             setYieldContext(savedYieldContext);
35634             setAwaitContext(savedAwaitContext);
35635             return body;
35636         }
35637         function parseDecoratorExpression() {
35638             if (inAwaitContext() && token() === 132 /* AwaitKeyword */) {
35639                 // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
35640                 // This simply parses the missing identifier and moves on.
35641                 var pos = getNodePos();
35642                 var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
35643                 nextToken();
35644                 var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
35645                 return parseCallExpressionRest(pos, memberExpression);
35646             }
35647             return parseLeftHandSideExpressionOrHigher();
35648         }
35649         function tryParseDecorator() {
35650             var pos = getNodePos();
35651             if (!parseOptional(59 /* AtToken */)) {
35652                 return undefined;
35653             }
35654             var expression = doInDecoratorContext(parseDecoratorExpression);
35655             return finishNode(factory.createDecorator(expression), pos);
35656         }
35657         function parseDecorators() {
35658             var pos = getNodePos();
35659             var list, decorator;
35660             while (decorator = tryParseDecorator()) {
35661                 list = ts.append(list, decorator);
35662             }
35663             return list && createNodeArray(list, pos);
35664         }
35665         function tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) {
35666             var pos = getNodePos();
35667             var kind = token();
35668             if (token() === 85 /* ConstKeyword */ && permitInvalidConstAsModifier) {
35669                 // We need to ensure that any subsequent modifiers appear on the same line
35670                 // so that when 'const' is a standalone declaration, we don't issue an error.
35671                 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
35672                     return undefined;
35673                 }
35674             }
35675             else if (stopOnStartOfClassStaticBlock && token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
35676                 return undefined;
35677             }
35678             else if (hasSeenStaticModifier && token() === 124 /* StaticKeyword */) {
35679                 return undefined;
35680             }
35681             else {
35682                 if (!parseAnyContextualModifier()) {
35683                     return undefined;
35684                 }
35685             }
35686             return finishNode(factory.createToken(kind), pos);
35687         }
35688         /*
35689          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
35690          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
35691          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
35692          *
35693          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
35694          */
35695         function parseModifiers(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock) {
35696             var pos = getNodePos();
35697             var list, modifier, hasSeenStatic = false;
35698             while (modifier = tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock, hasSeenStatic)) {
35699                 if (modifier.kind === 124 /* StaticKeyword */)
35700                     hasSeenStatic = true;
35701                 list = ts.append(list, modifier);
35702             }
35703             return list && createNodeArray(list, pos);
35704         }
35705         function parseModifiersForArrowFunction() {
35706             var modifiers;
35707             if (token() === 131 /* AsyncKeyword */) {
35708                 var pos = getNodePos();
35709                 nextToken();
35710                 var modifier = finishNode(factory.createToken(131 /* AsyncKeyword */), pos);
35711                 modifiers = createNodeArray([modifier], pos);
35712             }
35713             return modifiers;
35714         }
35715         function parseClassElement() {
35716             var pos = getNodePos();
35717             if (token() === 26 /* SemicolonToken */) {
35718                 nextToken();
35719                 return finishNode(factory.createSemicolonClassElement(), pos);
35720             }
35721             var hasJSDoc = hasPrecedingJSDocComment();
35722             var decorators = parseDecorators();
35723             var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true, /*stopOnStartOfClassStaticBlock*/ true);
35724             if (token() === 124 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) {
35725                 return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers);
35726             }
35727             if (parseContextualModifier(136 /* GetKeyword */)) {
35728                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 171 /* GetAccessor */);
35729             }
35730             if (parseContextualModifier(148 /* SetKeyword */)) {
35731                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SetAccessor */);
35732             }
35733             if (token() === 134 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
35734                 var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
35735                 if (constructorDeclaration) {
35736                     return constructorDeclaration;
35737                 }
35738             }
35739             if (isIndexSignature()) {
35740                 return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
35741             }
35742             // It is very important that we check this *after* checking indexers because
35743             // the [ token can start an index signature or a computed property name
35744             if (ts.tokenIsIdentifierOrKeyword(token()) ||
35745                 token() === 10 /* StringLiteral */ ||
35746                 token() === 8 /* NumericLiteral */ ||
35747                 token() === 41 /* AsteriskToken */ ||
35748                 token() === 22 /* OpenBracketToken */) {
35749                 var isAmbient = ts.some(modifiers, isDeclareModifier);
35750                 if (isAmbient) {
35751                     for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
35752                         var m = _a[_i];
35753                         m.flags |= 8388608 /* Ambient */;
35754                     }
35755                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
35756                 }
35757                 else {
35758                     return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
35759                 }
35760             }
35761             if (decorators || modifiers) {
35762                 // treat this as a property declaration with a missing name.
35763                 var name = createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
35764                 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
35765             }
35766             // 'isClassMemberStart' should have hinted not to attempt parsing.
35767             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
35768         }
35769         function parseClassExpression() {
35770             return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 225 /* ClassExpression */);
35771         }
35772         function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
35773             return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 256 /* ClassDeclaration */);
35774         }
35775         function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
35776             var savedAwaitContext = inAwaitContext();
35777             parseExpected(84 /* ClassKeyword */);
35778             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
35779             var name = parseNameOfClassDeclarationOrExpression();
35780             var typeParameters = parseTypeParameters();
35781             if (ts.some(modifiers, ts.isExportModifier))
35782                 setAwaitContext(/*value*/ true);
35783             var heritageClauses = parseHeritageClauses();
35784             var members;
35785             if (parseExpected(18 /* OpenBraceToken */)) {
35786                 // ClassTail[Yield,Await] : (Modified) See 14.5
35787                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
35788                 members = parseClassMembers();
35789                 parseExpected(19 /* CloseBraceToken */);
35790             }
35791             else {
35792                 members = createMissingList();
35793             }
35794             setAwaitContext(savedAwaitContext);
35795             var node = kind === 256 /* ClassDeclaration */
35796                 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
35797                 : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
35798             return withJSDoc(finishNode(node, pos), hasJSDoc);
35799         }
35800         function parseNameOfClassDeclarationOrExpression() {
35801             // implements is a future reserved word so
35802             // 'class implements' might mean either
35803             // - class expression with omitted name, 'implements' starts heritage clause
35804             // - class with name 'implements'
35805             // 'isImplementsClause' helps to disambiguate between these two cases
35806             return isBindingIdentifier() && !isImplementsClause()
35807                 ? createIdentifier(isBindingIdentifier())
35808                 : undefined;
35809         }
35810         function isImplementsClause() {
35811             return token() === 117 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
35812         }
35813         function parseHeritageClauses() {
35814             // ClassTail[Yield,Await] : (Modified) See 14.5
35815             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
35816             if (isHeritageClause()) {
35817                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
35818             }
35819             return undefined;
35820         }
35821         function parseHeritageClause() {
35822             var pos = getNodePos();
35823             var tok = token();
35824             ts.Debug.assert(tok === 94 /* ExtendsKeyword */ || tok === 117 /* ImplementsKeyword */); // isListElement() should ensure this.
35825             nextToken();
35826             var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
35827             return finishNode(factory.createHeritageClause(tok, types), pos);
35828         }
35829         function parseExpressionWithTypeArguments() {
35830             var pos = getNodePos();
35831             var expression = parseLeftHandSideExpressionOrHigher();
35832             var typeArguments = tryParseTypeArguments();
35833             return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
35834         }
35835         function tryParseTypeArguments() {
35836             return token() === 29 /* LessThanToken */ ?
35837                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
35838         }
35839         function isHeritageClause() {
35840             return token() === 94 /* ExtendsKeyword */ || token() === 117 /* ImplementsKeyword */;
35841         }
35842         function parseClassMembers() {
35843             return parseList(5 /* ClassMembers */, parseClassElement);
35844         }
35845         function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
35846             parseExpected(118 /* InterfaceKeyword */);
35847             var name = parseIdentifier();
35848             var typeParameters = parseTypeParameters();
35849             var heritageClauses = parseHeritageClauses();
35850             var members = parseObjectTypeMembers();
35851             var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
35852             return withJSDoc(finishNode(node, pos), hasJSDoc);
35853         }
35854         function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
35855             parseExpected(151 /* TypeKeyword */);
35856             var name = parseIdentifier();
35857             var typeParameters = parseTypeParameters();
35858             parseExpected(63 /* EqualsToken */);
35859             var type = token() === 138 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
35860             parseSemicolon();
35861             var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
35862             return withJSDoc(finishNode(node, pos), hasJSDoc);
35863         }
35864         // In an ambient declaration, the grammar only allows integer literals as initializers.
35865         // In a non-ambient declaration, the grammar allows uninitialized members only in a
35866         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
35867         // or any time an integer literal initializer is encountered.
35868         function parseEnumMember() {
35869             var pos = getNodePos();
35870             var hasJSDoc = hasPrecedingJSDocComment();
35871             var name = parsePropertyName();
35872             var initializer = allowInAnd(parseInitializer);
35873             return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
35874         }
35875         function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
35876             parseExpected(92 /* EnumKeyword */);
35877             var name = parseIdentifier();
35878             var members;
35879             if (parseExpected(18 /* OpenBraceToken */)) {
35880                 members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
35881                 parseExpected(19 /* CloseBraceToken */);
35882             }
35883             else {
35884                 members = createMissingList();
35885             }
35886             var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
35887             return withJSDoc(finishNode(node, pos), hasJSDoc);
35888         }
35889         function parseModuleBlock() {
35890             var pos = getNodePos();
35891             var statements;
35892             if (parseExpected(18 /* OpenBraceToken */)) {
35893                 statements = parseList(1 /* BlockStatements */, parseStatement);
35894                 parseExpected(19 /* CloseBraceToken */);
35895             }
35896             else {
35897                 statements = createMissingList();
35898             }
35899             return finishNode(factory.createModuleBlock(statements), pos);
35900         }
35901         function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
35902             // If we are parsing a dotted namespace name, we want to
35903             // propagate the 'Namespace' flag across the names if set.
35904             var namespaceFlag = flags & 16 /* Namespace */;
35905             var name = parseIdentifier();
35906             var body = parseOptional(24 /* DotToken */)
35907                 ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
35908                 : parseModuleBlock();
35909             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
35910             return withJSDoc(finishNode(node, pos), hasJSDoc);
35911         }
35912         function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
35913             var flags = 0;
35914             var name;
35915             if (token() === 156 /* GlobalKeyword */) {
35916                 // parse 'global' as name of global scope augmentation
35917                 name = parseIdentifier();
35918                 flags |= 1024 /* GlobalAugmentation */;
35919             }
35920             else {
35921                 name = parseLiteralNode();
35922                 name.text = internIdentifier(name.text);
35923             }
35924             var body;
35925             if (token() === 18 /* OpenBraceToken */) {
35926                 body = parseModuleBlock();
35927             }
35928             else {
35929                 parseSemicolon();
35930             }
35931             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
35932             return withJSDoc(finishNode(node, pos), hasJSDoc);
35933         }
35934         function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
35935             var flags = 0;
35936             if (token() === 156 /* GlobalKeyword */) {
35937                 // global augmentation
35938                 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
35939             }
35940             else if (parseOptional(142 /* NamespaceKeyword */)) {
35941                 flags |= 16 /* Namespace */;
35942             }
35943             else {
35944                 parseExpected(141 /* ModuleKeyword */);
35945                 if (token() === 10 /* StringLiteral */) {
35946                     return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
35947                 }
35948             }
35949             return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
35950         }
35951         function isExternalModuleReference() {
35952             return token() === 145 /* RequireKeyword */ &&
35953                 lookAhead(nextTokenIsOpenParen);
35954         }
35955         function nextTokenIsOpenParen() {
35956             return nextToken() === 20 /* OpenParenToken */;
35957         }
35958         function nextTokenIsOpenBrace() {
35959             return nextToken() === 18 /* OpenBraceToken */;
35960         }
35961         function nextTokenIsSlash() {
35962             return nextToken() === 43 /* SlashToken */;
35963         }
35964         function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
35965             parseExpected(127 /* AsKeyword */);
35966             parseExpected(142 /* NamespaceKeyword */);
35967             var name = parseIdentifier();
35968             parseSemicolon();
35969             var node = factory.createNamespaceExportDeclaration(name);
35970             // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
35971             node.decorators = decorators;
35972             node.modifiers = modifiers;
35973             return withJSDoc(finishNode(node, pos), hasJSDoc);
35974         }
35975         function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
35976             parseExpected(100 /* ImportKeyword */);
35977             var afterImportPos = scanner.getStartPos();
35978             // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
35979             var identifier;
35980             if (isIdentifier()) {
35981                 identifier = parseIdentifier();
35982             }
35983             var isTypeOnly = false;
35984             if (token() !== 155 /* FromKeyword */ &&
35985                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
35986                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
35987                 isTypeOnly = true;
35988                 identifier = isIdentifier() ? parseIdentifier() : undefined;
35989             }
35990             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
35991                 return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
35992             }
35993             // ImportDeclaration:
35994             //  import ImportClause from ModuleSpecifier ;
35995             //  import ModuleSpecifier;
35996             var importClause;
35997             if (identifier || // import id
35998                 token() === 41 /* AsteriskToken */ || // import *
35999                 token() === 18 /* OpenBraceToken */ // import {
36000             ) {
36001                 importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
36002                 parseExpected(155 /* FromKeyword */);
36003             }
36004             var moduleSpecifier = parseModuleSpecifier();
36005             var assertClause;
36006             if (token() === 129 /* AssertKeyword */ && !scanner.hasPrecedingLineBreak()) {
36007                 assertClause = parseAssertClause();
36008             }
36009             parseSemicolon();
36010             var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause);
36011             return withJSDoc(finishNode(node, pos), hasJSDoc);
36012         }
36013         function parseAssertEntry() {
36014             var pos = getNodePos();
36015             var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* StringLiteral */);
36016             parseExpected(58 /* ColonToken */);
36017             var value = parseLiteralLikeNode(10 /* StringLiteral */);
36018             return finishNode(factory.createAssertEntry(name, value), pos);
36019         }
36020         function parseAssertClause() {
36021             var pos = getNodePos();
36022             parseExpected(129 /* AssertKeyword */);
36023             var openBracePosition = scanner.getTokenPos();
36024             if (parseExpected(18 /* OpenBraceToken */)) {
36025                 var multiLine = scanner.hasPrecedingLineBreak();
36026                 var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true);
36027                 if (!parseExpected(19 /* CloseBraceToken */)) {
36028                     var lastError = ts.lastOrUndefined(parseDiagnostics);
36029                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
36030                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
36031                     }
36032                 }
36033                 return finishNode(factory.createAssertClause(elements, multiLine), pos);
36034             }
36035             else {
36036                 var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false);
36037                 return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos);
36038             }
36039         }
36040         function tokenAfterImportDefinitelyProducesImportDeclaration() {
36041             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
36042         }
36043         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
36044             // In `import id ___`, the current token decides whether to produce
36045             // an ImportDeclaration or ImportEqualsDeclaration.
36046             return token() === 27 /* CommaToken */ || token() === 155 /* FromKeyword */;
36047         }
36048         function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
36049             parseExpected(63 /* EqualsToken */);
36050             var moduleReference = parseModuleReference();
36051             parseSemicolon();
36052             var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference);
36053             var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
36054             return finished;
36055         }
36056         function parseImportClause(identifier, pos, isTypeOnly) {
36057             // ImportClause:
36058             //  ImportedDefaultBinding
36059             //  NameSpaceImport
36060             //  NamedImports
36061             //  ImportedDefaultBinding, NameSpaceImport
36062             //  ImportedDefaultBinding, NamedImports
36063             // If there was no default import or if there is comma token after default import
36064             // parse namespace or named imports
36065             var namedBindings;
36066             if (!identifier ||
36067                 parseOptional(27 /* CommaToken */)) {
36068                 namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(268 /* NamedImports */);
36069             }
36070             return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
36071         }
36072         function parseModuleReference() {
36073             return isExternalModuleReference()
36074                 ? parseExternalModuleReference()
36075                 : parseEntityName(/*allowReservedWords*/ false);
36076         }
36077         function parseExternalModuleReference() {
36078             var pos = getNodePos();
36079             parseExpected(145 /* RequireKeyword */);
36080             parseExpected(20 /* OpenParenToken */);
36081             var expression = parseModuleSpecifier();
36082             parseExpected(21 /* CloseParenToken */);
36083             return finishNode(factory.createExternalModuleReference(expression), pos);
36084         }
36085         function parseModuleSpecifier() {
36086             if (token() === 10 /* StringLiteral */) {
36087                 var result = parseLiteralNode();
36088                 result.text = internIdentifier(result.text);
36089                 return result;
36090             }
36091             else {
36092                 // We allow arbitrary expressions here, even though the grammar only allows string
36093                 // literals.  We check to ensure that it is only a string literal later in the grammar
36094                 // check pass.
36095                 return parseExpression();
36096             }
36097         }
36098         function parseNamespaceImport() {
36099             // NameSpaceImport:
36100             //  * as ImportedBinding
36101             var pos = getNodePos();
36102             parseExpected(41 /* AsteriskToken */);
36103             parseExpected(127 /* AsKeyword */);
36104             var name = parseIdentifier();
36105             return finishNode(factory.createNamespaceImport(name), pos);
36106         }
36107         function parseNamedImportsOrExports(kind) {
36108             var pos = getNodePos();
36109             // NamedImports:
36110             //  { }
36111             //  { ImportsList }
36112             //  { ImportsList, }
36113             // ImportsList:
36114             //  ImportSpecifier
36115             //  ImportsList, ImportSpecifier
36116             var node = kind === 268 /* NamedImports */
36117                 ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
36118                 : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
36119             return finishNode(node, pos);
36120         }
36121         function parseExportSpecifier() {
36122             return parseImportOrExportSpecifier(274 /* ExportSpecifier */);
36123         }
36124         function parseImportSpecifier() {
36125             return parseImportOrExportSpecifier(269 /* ImportSpecifier */);
36126         }
36127         function parseImportOrExportSpecifier(kind) {
36128             var pos = getNodePos();
36129             // ImportSpecifier:
36130             //   BindingIdentifier
36131             //   IdentifierName as BindingIdentifier
36132             // ExportSpecifier:
36133             //   IdentifierName
36134             //   IdentifierName as IdentifierName
36135             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
36136             var checkIdentifierStart = scanner.getTokenPos();
36137             var checkIdentifierEnd = scanner.getTextPos();
36138             var isTypeOnly = false;
36139             var propertyName;
36140             var canParseAsKeyword = true;
36141             var name = parseIdentifierName();
36142             if (name.escapedText === "type") {
36143                 // If the first token of an import specifier is 'type', there are a lot of possibilities,
36144                 // especially if we see 'as' afterwards:
36145                 //
36146                 // import { type } from "mod";          - isTypeOnly: false,   name: type
36147                 // import { type as } from "mod";       - isTypeOnly: true,    name: as
36148                 // import { type as as } from "mod";    - isTypeOnly: false,   name: as,    propertyName: type
36149                 // import { type as as as } from "mod"; - isTypeOnly: true,    name: as,    propertyName: as
36150                 if (token() === 127 /* AsKeyword */) {
36151                     // { type as ...? }
36152                     var firstAs = parseIdentifierName();
36153                     if (token() === 127 /* AsKeyword */) {
36154                         // { type as as ...? }
36155                         var secondAs = parseIdentifierName();
36156                         if (ts.tokenIsIdentifierOrKeyword(token())) {
36157                             // { type as as something }
36158                             isTypeOnly = true;
36159                             propertyName = firstAs;
36160                             name = parseNameWithKeywordCheck();
36161                             canParseAsKeyword = false;
36162                         }
36163                         else {
36164                             // { type as as }
36165                             propertyName = name;
36166                             name = secondAs;
36167                             canParseAsKeyword = false;
36168                         }
36169                     }
36170                     else if (ts.tokenIsIdentifierOrKeyword(token())) {
36171                         // { type as something }
36172                         propertyName = name;
36173                         canParseAsKeyword = false;
36174                         name = parseNameWithKeywordCheck();
36175                     }
36176                     else {
36177                         // { type as }
36178                         isTypeOnly = true;
36179                         name = firstAs;
36180                     }
36181                 }
36182                 else if (ts.tokenIsIdentifierOrKeyword(token())) {
36183                     // { type something ...? }
36184                     isTypeOnly = true;
36185                     name = parseNameWithKeywordCheck();
36186                 }
36187             }
36188             if (canParseAsKeyword && token() === 127 /* AsKeyword */) {
36189                 propertyName = name;
36190                 parseExpected(127 /* AsKeyword */);
36191                 name = parseNameWithKeywordCheck();
36192             }
36193             if (kind === 269 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
36194                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
36195             }
36196             var node = kind === 269 /* ImportSpecifier */
36197                 ? factory.createImportSpecifier(isTypeOnly, propertyName, name)
36198                 : factory.createExportSpecifier(isTypeOnly, propertyName, name);
36199             return finishNode(node, pos);
36200             function parseNameWithKeywordCheck() {
36201                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
36202                 checkIdentifierStart = scanner.getTokenPos();
36203                 checkIdentifierEnd = scanner.getTextPos();
36204                 return parseIdentifierName();
36205             }
36206         }
36207         function parseNamespaceExport(pos) {
36208             return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos);
36209         }
36210         function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
36211             var savedAwaitContext = inAwaitContext();
36212             setAwaitContext(/*value*/ true);
36213             var exportClause;
36214             var moduleSpecifier;
36215             var assertClause;
36216             var isTypeOnly = parseOptional(151 /* TypeKeyword */);
36217             var namespaceExportPos = getNodePos();
36218             if (parseOptional(41 /* AsteriskToken */)) {
36219                 if (parseOptional(127 /* AsKeyword */)) {
36220                     exportClause = parseNamespaceExport(namespaceExportPos);
36221                 }
36222                 parseExpected(155 /* FromKeyword */);
36223                 moduleSpecifier = parseModuleSpecifier();
36224             }
36225             else {
36226                 exportClause = parseNamedImportsOrExports(272 /* NamedExports */);
36227                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
36228                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
36229                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
36230                 if (token() === 155 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
36231                     parseExpected(155 /* FromKeyword */);
36232                     moduleSpecifier = parseModuleSpecifier();
36233                 }
36234             }
36235             if (moduleSpecifier && token() === 129 /* AssertKeyword */ && !scanner.hasPrecedingLineBreak()) {
36236                 assertClause = parseAssertClause();
36237             }
36238             parseSemicolon();
36239             setAwaitContext(savedAwaitContext);
36240             var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause);
36241             return withJSDoc(finishNode(node, pos), hasJSDoc);
36242         }
36243         function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
36244             var savedAwaitContext = inAwaitContext();
36245             setAwaitContext(/*value*/ true);
36246             var isExportEquals;
36247             if (parseOptional(63 /* EqualsToken */)) {
36248                 isExportEquals = true;
36249             }
36250             else {
36251                 parseExpected(88 /* DefaultKeyword */);
36252             }
36253             var expression = parseAssignmentExpressionOrHigher();
36254             parseSemicolon();
36255             setAwaitContext(savedAwaitContext);
36256             var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
36257             return withJSDoc(finishNode(node, pos), hasJSDoc);
36258         }
36259         function setExternalModuleIndicator(sourceFile) {
36260             // Try to use the first top-level import/export when available, then
36261             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
36262             sourceFile.externalModuleIndicator =
36263                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
36264                     getImportMetaIfNecessary(sourceFile);
36265         }
36266         function isAnExternalModuleIndicatorNode(node) {
36267             return hasModifierOfKind(node, 93 /* ExportKeyword */)
36268                 || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
36269                 || ts.isImportDeclaration(node)
36270                 || ts.isExportAssignment(node)
36271                 || ts.isExportDeclaration(node) ? node : undefined;
36272         }
36273         function getImportMetaIfNecessary(sourceFile) {
36274             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
36275                 walkTreeForExternalModuleIndicators(sourceFile) :
36276                 undefined;
36277         }
36278         function walkTreeForExternalModuleIndicators(node) {
36279             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
36280         }
36281         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
36282         function hasModifierOfKind(node, kind) {
36283             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
36284         }
36285         function isImportMeta(node) {
36286             return ts.isMetaProperty(node) && node.keywordToken === 100 /* ImportKeyword */ && node.name.escapedText === "meta";
36287         }
36288         var ParsingContext;
36289         (function (ParsingContext) {
36290             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
36291             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
36292             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
36293             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
36294             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
36295             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
36296             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
36297             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
36298             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
36299             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
36300             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
36301             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
36302             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
36303             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
36304             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
36305             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
36306             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
36307             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
36308             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
36309             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
36310             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
36311             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
36312             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
36313             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
36314             ParsingContext[ParsingContext["AssertEntries"] = 24] = "AssertEntries";
36315             ParsingContext[ParsingContext["Count"] = 25] = "Count"; // Number of parsing contexts
36316         })(ParsingContext || (ParsingContext = {}));
36317         var Tristate;
36318         (function (Tristate) {
36319             Tristate[Tristate["False"] = 0] = "False";
36320             Tristate[Tristate["True"] = 1] = "True";
36321             Tristate[Tristate["Unknown"] = 2] = "Unknown";
36322         })(Tristate || (Tristate = {}));
36323         var JSDocParser;
36324         (function (JSDocParser) {
36325             function parseJSDocTypeExpressionForTests(content, start, length) {
36326                 initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
36327                 scanner.setText(content, start, length);
36328                 currentToken = scanner.scan();
36329                 var jsDocTypeExpression = parseJSDocTypeExpression();
36330                 var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
36331                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
36332                 if (jsDocDiagnostics) {
36333                     sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
36334                 }
36335                 clearState();
36336                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
36337             }
36338             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
36339             // Parses out a JSDoc type expression.
36340             function parseJSDocTypeExpression(mayOmitBraces) {
36341                 var pos = getNodePos();
36342                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
36343                 var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
36344                 if (!mayOmitBraces || hasBrace) {
36345                     parseExpectedJSDoc(19 /* CloseBraceToken */);
36346                 }
36347                 var result = factory.createJSDocTypeExpression(type);
36348                 fixupParentReferences(result);
36349                 return finishNode(result, pos);
36350             }
36351             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
36352             function parseJSDocNameReference() {
36353                 var pos = getNodePos();
36354                 var hasBrace = parseOptional(18 /* OpenBraceToken */);
36355                 var p2 = getNodePos();
36356                 var entityName = parseEntityName(/* allowReservedWords*/ false);
36357                 while (token() === 80 /* PrivateIdentifier */) {
36358                     reScanHashToken(); // rescan #id as # id
36359                     nextTokenJSDoc(); // then skip the #
36360                     entityName = finishNode(factory.createJSDocMemberName(entityName, parseIdentifier()), p2);
36361                 }
36362                 if (hasBrace) {
36363                     parseExpectedJSDoc(19 /* CloseBraceToken */);
36364                 }
36365                 var result = factory.createJSDocNameReference(entityName);
36366                 fixupParentReferences(result);
36367                 return finishNode(result, pos);
36368             }
36369             JSDocParser.parseJSDocNameReference = parseJSDocNameReference;
36370             function parseIsolatedJSDocComment(content, start, length) {
36371                 initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
36372                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
36373                 var sourceFile = { languageVariant: 0 /* Standard */, text: content };
36374                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
36375                 clearState();
36376                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
36377             }
36378             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
36379             function parseJSDocComment(parent, start, length) {
36380                 var saveToken = currentToken;
36381                 var saveParseDiagnosticsLength = parseDiagnostics.length;
36382                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
36383                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
36384                 ts.setParent(comment, parent);
36385                 if (contextFlags & 131072 /* JavaScriptFile */) {
36386                     if (!jsDocDiagnostics) {
36387                         jsDocDiagnostics = [];
36388                     }
36389                     jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
36390                 }
36391                 currentToken = saveToken;
36392                 parseDiagnostics.length = saveParseDiagnosticsLength;
36393                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
36394                 return comment;
36395             }
36396             JSDocParser.parseJSDocComment = parseJSDocComment;
36397             var JSDocState;
36398             (function (JSDocState) {
36399                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
36400                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
36401                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
36402                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
36403             })(JSDocState || (JSDocState = {}));
36404             var PropertyLikeParse;
36405             (function (PropertyLikeParse) {
36406                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
36407                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
36408                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
36409             })(PropertyLikeParse || (PropertyLikeParse = {}));
36410             function parseJSDocCommentWorker(start, length) {
36411                 if (start === void 0) { start = 0; }
36412                 var content = sourceText;
36413                 var end = length === undefined ? content.length : start + length;
36414                 length = end - start;
36415                 ts.Debug.assert(start >= 0);
36416                 ts.Debug.assert(start <= end);
36417                 ts.Debug.assert(end <= content.length);
36418                 // Check for /** (JSDoc opening part)
36419                 if (!isJSDocLikeText(content, start)) {
36420                     return undefined;
36421                 }
36422                 var tags;
36423                 var tagsPos;
36424                 var tagsEnd;
36425                 var linkEnd;
36426                 var commentsPos;
36427                 var comments = [];
36428                 var parts = [];
36429                 // + 3 for leading /**, - 5 in total for /** */
36430                 return scanner.scanRange(start + 3, length - 5, function () {
36431                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
36432                     // This is so that /** * @type */ doesn't parse.
36433                     var state = 1 /* SawAsterisk */;
36434                     var margin;
36435                     // + 4 for leading '/** '
36436                     // + 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
36437                     var indent = start - (content.lastIndexOf("\n", start) + 1) + 4;
36438                     function pushComment(text) {
36439                         if (!margin) {
36440                             margin = indent;
36441                         }
36442                         comments.push(text);
36443                         indent += text.length;
36444                     }
36445                     nextTokenJSDoc();
36446                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
36447                         ;
36448                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
36449                         state = 0 /* BeginningOfLine */;
36450                         indent = 0;
36451                     }
36452                     loop: while (true) {
36453                         switch (token()) {
36454                             case 59 /* AtToken */:
36455                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
36456                                     removeTrailingWhitespace(comments);
36457                                     if (!commentsPos)
36458                                         commentsPos = getNodePos();
36459                                     addTag(parseTag(indent));
36460                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
36461                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
36462                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
36463                                     state = 0 /* BeginningOfLine */;
36464                                     margin = undefined;
36465                                 }
36466                                 else {
36467                                     pushComment(scanner.getTokenText());
36468                                 }
36469                                 break;
36470                             case 4 /* NewLineTrivia */:
36471                                 comments.push(scanner.getTokenText());
36472                                 state = 0 /* BeginningOfLine */;
36473                                 indent = 0;
36474                                 break;
36475                             case 41 /* AsteriskToken */:
36476                                 var asterisk = scanner.getTokenText();
36477                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
36478                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
36479                                     state = 2 /* SavingComments */;
36480                                     pushComment(asterisk);
36481                                 }
36482                                 else {
36483                                     // Ignore the first asterisk on a line
36484                                     state = 1 /* SawAsterisk */;
36485                                     indent += asterisk.length;
36486                                 }
36487                                 break;
36488                             case 5 /* WhitespaceTrivia */:
36489                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
36490                                 var whitespace = scanner.getTokenText();
36491                                 if (state === 2 /* SavingComments */) {
36492                                     comments.push(whitespace);
36493                                 }
36494                                 else if (margin !== undefined && indent + whitespace.length > margin) {
36495                                     comments.push(whitespace.slice(margin - indent));
36496                                 }
36497                                 indent += whitespace.length;
36498                                 break;
36499                             case 1 /* EndOfFileToken */:
36500                                 break loop;
36501                             case 18 /* OpenBraceToken */:
36502                                 state = 2 /* SavingComments */;
36503                                 var commentEnd = scanner.getStartPos();
36504                                 var linkStart = scanner.getTextPos() - 1;
36505                                 var link = parseJSDocLink(linkStart);
36506                                 if (link) {
36507                                     if (!linkEnd) {
36508                                         removeLeadingNewlines(comments);
36509                                     }
36510                                     parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd));
36511                                     parts.push(link);
36512                                     comments = [];
36513                                     linkEnd = scanner.getTextPos();
36514                                     break;
36515                                 }
36516                             // fallthrough if it's not a {@link sequence
36517                             default:
36518                                 // Anything else is doc comment text. We just save it. Because it
36519                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
36520                                 // line break.
36521                                 state = 2 /* SavingComments */;
36522                                 pushComment(scanner.getTokenText());
36523                                 break;
36524                         }
36525                         nextTokenJSDoc();
36526                     }
36527                     removeTrailingWhitespace(comments);
36528                     if (parts.length && comments.length) {
36529                         parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos));
36530                     }
36531                     if (parts.length && tags)
36532                         ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set");
36533                     var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
36534                     return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end);
36535                 });
36536                 function removeLeadingNewlines(comments) {
36537                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
36538                         comments.shift();
36539                     }
36540                 }
36541                 function removeTrailingWhitespace(comments) {
36542                     while (comments.length && comments[comments.length - 1].trim() === "") {
36543                         comments.pop();
36544                     }
36545                 }
36546                 function isNextNonwhitespaceTokenEndOfFile() {
36547                     // We must use infinite lookahead, as there could be any number of newlines :(
36548                     while (true) {
36549                         nextTokenJSDoc();
36550                         if (token() === 1 /* EndOfFileToken */) {
36551                             return true;
36552                         }
36553                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
36554                             return false;
36555                         }
36556                     }
36557                 }
36558                 function skipWhitespace() {
36559                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
36560                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
36561                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
36562                         }
36563                     }
36564                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
36565                         nextTokenJSDoc();
36566                     }
36567                 }
36568                 function skipWhitespaceOrAsterisk() {
36569                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
36570                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
36571                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
36572                         }
36573                     }
36574                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
36575                     var seenLineBreak = false;
36576                     var indentText = "";
36577                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
36578                         indentText += scanner.getTokenText();
36579                         if (token() === 4 /* NewLineTrivia */) {
36580                             precedingLineBreak = true;
36581                             seenLineBreak = true;
36582                             indentText = "";
36583                         }
36584                         else if (token() === 41 /* AsteriskToken */) {
36585                             precedingLineBreak = false;
36586                         }
36587                         nextTokenJSDoc();
36588                     }
36589                     return seenLineBreak ? indentText : "";
36590                 }
36591                 function parseTag(margin) {
36592                     ts.Debug.assert(token() === 59 /* AtToken */);
36593                     var start = scanner.getTokenPos();
36594                     nextTokenJSDoc();
36595                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
36596                     var indentText = skipWhitespaceOrAsterisk();
36597                     var tag;
36598                     switch (tagName.escapedText) {
36599                         case "author":
36600                             tag = parseAuthorTag(start, tagName, margin, indentText);
36601                             break;
36602                         case "implements":
36603                             tag = parseImplementsTag(start, tagName, margin, indentText);
36604                             break;
36605                         case "augments":
36606                         case "extends":
36607                             tag = parseAugmentsTag(start, tagName, margin, indentText);
36608                             break;
36609                         case "class":
36610                         case "constructor":
36611                             tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
36612                             break;
36613                         case "public":
36614                             tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
36615                             break;
36616                         case "private":
36617                             tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
36618                             break;
36619                         case "protected":
36620                             tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
36621                             break;
36622                         case "readonly":
36623                             tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
36624                             break;
36625                         case "override":
36626                             tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText);
36627                             break;
36628                         case "deprecated":
36629                             hasDeprecatedTag = true;
36630                             tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
36631                             break;
36632                         case "this":
36633                             tag = parseThisTag(start, tagName, margin, indentText);
36634                             break;
36635                         case "enum":
36636                             tag = parseEnumTag(start, tagName, margin, indentText);
36637                             break;
36638                         case "arg":
36639                         case "argument":
36640                         case "param":
36641                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
36642                         case "return":
36643                         case "returns":
36644                             tag = parseReturnTag(start, tagName, margin, indentText);
36645                             break;
36646                         case "template":
36647                             tag = parseTemplateTag(start, tagName, margin, indentText);
36648                             break;
36649                         case "type":
36650                             tag = parseTypeTag(start, tagName, margin, indentText);
36651                             break;
36652                         case "typedef":
36653                             tag = parseTypedefTag(start, tagName, margin, indentText);
36654                             break;
36655                         case "callback":
36656                             tag = parseCallbackTag(start, tagName, margin, indentText);
36657                             break;
36658                         case "see":
36659                             tag = parseSeeTag(start, tagName, margin, indentText);
36660                             break;
36661                         default:
36662                             tag = parseUnknownTag(start, tagName, margin, indentText);
36663                             break;
36664                     }
36665                     return tag;
36666                 }
36667                 function parseTrailingTagComments(pos, end, margin, indentText) {
36668                     // some tags, like typedef and callback, have already parsed their comments earlier
36669                     if (!indentText) {
36670                         margin += end - pos;
36671                     }
36672                     return parseTagComments(margin, indentText.slice(margin));
36673                 }
36674                 function parseTagComments(indent, initialMargin) {
36675                     var commentsPos = getNodePos();
36676                     var comments = [];
36677                     var parts = [];
36678                     var linkEnd;
36679                     var state = 0 /* BeginningOfLine */;
36680                     var previousWhitespace = true;
36681                     var margin;
36682                     function pushComment(text) {
36683                         if (!margin) {
36684                             margin = indent;
36685                         }
36686                         comments.push(text);
36687                         indent += text.length;
36688                     }
36689                     if (initialMargin !== undefined) {
36690                         // jump straight to saving comments if there is some initial indentation
36691                         if (initialMargin !== "") {
36692                             pushComment(initialMargin);
36693                         }
36694                         state = 1 /* SawAsterisk */;
36695                     }
36696                     var tok = token();
36697                     loop: while (true) {
36698                         switch (tok) {
36699                             case 4 /* NewLineTrivia */:
36700                                 state = 0 /* BeginningOfLine */;
36701                                 // don't use pushComment here because we want to keep the margin unchanged
36702                                 comments.push(scanner.getTokenText());
36703                                 indent = 0;
36704                                 break;
36705                             case 59 /* AtToken */:
36706                                 if (state === 3 /* SavingBackticks */
36707                                     || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) {
36708                                     // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace
36709                                     comments.push(scanner.getTokenText());
36710                                     break;
36711                                 }
36712                                 scanner.setTextPos(scanner.getTextPos() - 1);
36713                             // falls through
36714                             case 1 /* EndOfFileToken */:
36715                                 // Done
36716                                 break loop;
36717                             case 5 /* WhitespaceTrivia */:
36718                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
36719                                     pushComment(scanner.getTokenText());
36720                                 }
36721                                 else {
36722                                     var whitespace = scanner.getTokenText();
36723                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
36724                                     if (margin !== undefined && indent + whitespace.length > margin) {
36725                                         comments.push(whitespace.slice(margin - indent));
36726                                     }
36727                                     indent += whitespace.length;
36728                                 }
36729                                 break;
36730                             case 18 /* OpenBraceToken */:
36731                                 state = 2 /* SavingComments */;
36732                                 var commentEnd = scanner.getStartPos();
36733                                 var linkStart = scanner.getTextPos() - 1;
36734                                 var link = parseJSDocLink(linkStart);
36735                                 if (link) {
36736                                     parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd));
36737                                     parts.push(link);
36738                                     comments = [];
36739                                     linkEnd = scanner.getTextPos();
36740                                 }
36741                                 else {
36742                                     pushComment(scanner.getTokenText());
36743                                 }
36744                                 break;
36745                             case 61 /* BacktickToken */:
36746                                 if (state === 3 /* SavingBackticks */) {
36747                                     state = 2 /* SavingComments */;
36748                                 }
36749                                 else {
36750                                     state = 3 /* SavingBackticks */;
36751                                 }
36752                                 pushComment(scanner.getTokenText());
36753                                 break;
36754                             case 41 /* AsteriskToken */:
36755                                 if (state === 0 /* BeginningOfLine */) {
36756                                     // leading asterisks start recording on the *next* (non-whitespace) token
36757                                     state = 1 /* SawAsterisk */;
36758                                     indent += 1;
36759                                     break;
36760                                 }
36761                             // record the * as a comment
36762                             // falls through
36763                             default:
36764                                 if (state !== 3 /* SavingBackticks */) {
36765                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
36766                                 }
36767                                 pushComment(scanner.getTokenText());
36768                                 break;
36769                         }
36770                         previousWhitespace = token() === 5 /* WhitespaceTrivia */;
36771                         tok = nextTokenJSDoc();
36772                     }
36773                     removeLeadingNewlines(comments);
36774                     removeTrailingWhitespace(comments);
36775                     if (parts.length) {
36776                         if (comments.length) {
36777                             parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos));
36778                         }
36779                         return createNodeArray(parts, commentsPos, scanner.getTextPos());
36780                     }
36781                     else if (comments.length) {
36782                         return comments.join("");
36783                     }
36784                 }
36785                 function isNextJSDocTokenWhitespace() {
36786                     var next = nextTokenJSDoc();
36787                     return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */;
36788                 }
36789                 function parseJSDocLink(start) {
36790                     var linkType = tryParse(parseJSDocLinkPrefix);
36791                     if (!linkType) {
36792                         return undefined;
36793                     }
36794                     nextTokenJSDoc(); // start at token after link, then skip any whitespace
36795                     skipWhitespace();
36796                     // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error
36797                     var p2 = getNodePos();
36798                     var name = ts.tokenIsIdentifierOrKeyword(token())
36799                         ? parseEntityName(/*allowReservedWords*/ true)
36800                         : undefined;
36801                     if (name) {
36802                         while (token() === 80 /* PrivateIdentifier */) {
36803                             reScanHashToken(); // rescan #id as # id
36804                             nextTokenJSDoc(); // then skip the #
36805                             name = finishNode(factory.createJSDocMemberName(name, parseIdentifier()), p2);
36806                         }
36807                     }
36808                     var text = [];
36809                     while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) {
36810                         text.push(scanner.getTokenText());
36811                         nextTokenJSDoc();
36812                     }
36813                     var create = linkType === "link" ? factory.createJSDocLink
36814                         : linkType === "linkcode" ? factory.createJSDocLinkCode
36815                             : factory.createJSDocLinkPlain;
36816                     return finishNode(create(name, text.join("")), start, scanner.getTextPos());
36817                 }
36818                 function parseJSDocLinkPrefix() {
36819                     skipWhitespaceOrAsterisk();
36820                     if (token() === 18 /* OpenBraceToken */
36821                         && nextTokenJSDoc() === 59 /* AtToken */
36822                         && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc())) {
36823                         var kind = scanner.getTokenValue();
36824                         if (kind === "link" || kind === "linkcode" || kind === "linkplain") {
36825                             return kind;
36826                         }
36827                     }
36828                 }
36829                 function parseUnknownTag(start, tagName, indent, indentText) {
36830                     return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
36831                 }
36832                 function addTag(tag) {
36833                     if (!tag) {
36834                         return;
36835                     }
36836                     if (!tags) {
36837                         tags = [tag];
36838                         tagsPos = tag.pos;
36839                     }
36840                     else {
36841                         tags.push(tag);
36842                     }
36843                     tagsEnd = tag.end;
36844                 }
36845                 function tryParseTypeExpression() {
36846                     skipWhitespaceOrAsterisk();
36847                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
36848                 }
36849                 function parseBracketNameInPropertyAndParamTag() {
36850                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
36851                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
36852                     if (isBracketed) {
36853                         skipWhitespace();
36854                     }
36855                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
36856                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
36857                     var name = parseJSDocEntityName();
36858                     if (isBackquoted) {
36859                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
36860                     }
36861                     if (isBracketed) {
36862                         skipWhitespace();
36863                         // May have an optional default, e.g. '[foo = 42]'
36864                         if (parseOptionalToken(63 /* EqualsToken */)) {
36865                             parseExpression();
36866                         }
36867                         parseExpected(23 /* CloseBracketToken */);
36868                     }
36869                     return { name: name, isBracketed: isBracketed };
36870                 }
36871                 function isObjectOrObjectArrayTypeReference(node) {
36872                     switch (node.kind) {
36873                         case 147 /* ObjectKeyword */:
36874                             return true;
36875                         case 182 /* ArrayType */:
36876                             return isObjectOrObjectArrayTypeReference(node.elementType);
36877                         default:
36878                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
36879                     }
36880                 }
36881                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
36882                     var typeExpression = tryParseTypeExpression();
36883                     var isNameFirst = !typeExpression;
36884                     skipWhitespaceOrAsterisk();
36885                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
36886                     var indentText = skipWhitespaceOrAsterisk();
36887                     if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) {
36888                         typeExpression = tryParseTypeExpression();
36889                     }
36890                     var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
36891                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
36892                     if (nestedTypeLiteral) {
36893                         typeExpression = nestedTypeLiteral;
36894                         isNameFirst = true;
36895                     }
36896                     var result = target === 1 /* Property */
36897                         ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
36898                         : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
36899                     return finishNode(result, start);
36900                 }
36901                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
36902                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
36903                         var pos = getNodePos();
36904                         var child = void 0;
36905                         var children = void 0;
36906                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
36907                             if (child.kind === 338 /* JSDocParameterTag */ || child.kind === 345 /* JSDocPropertyTag */) {
36908                                 children = ts.append(children, child);
36909                             }
36910                         }
36911                         if (children) {
36912                             var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 182 /* ArrayType */), pos);
36913                             return finishNode(factory.createJSDocTypeExpression(literal), pos);
36914                         }
36915                     }
36916                 }
36917                 function parseReturnTag(start, tagName, indent, indentText) {
36918                     if (ts.some(tags, ts.isJSDocReturnTag)) {
36919                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
36920                     }
36921                     var typeExpression = tryParseTypeExpression();
36922                     return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
36923                 }
36924                 function parseTypeTag(start, tagName, indent, indentText) {
36925                     if (ts.some(tags, ts.isJSDocTypeTag)) {
36926                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
36927                     }
36928                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
36929                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
36930                     return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start);
36931                 }
36932                 function parseSeeTag(start, tagName, indent, indentText) {
36933                     var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */
36934                         || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; });
36935                     var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference();
36936                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
36937                     return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start);
36938                 }
36939                 function parseAuthorTag(start, tagName, indent, indentText) {
36940                     var commentStart = getNodePos();
36941                     var textOnly = parseAuthorNameAndEmail();
36942                     var commentEnd = scanner.getStartPos();
36943                     var comments = parseTrailingTagComments(start, commentEnd, indent, indentText);
36944                     if (!comments) {
36945                         commentEnd = scanner.getStartPos();
36946                     }
36947                     var allParts = typeof comments !== "string"
36948                         ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly
36949                         : textOnly.text + comments;
36950                     return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start);
36951                 }
36952                 function parseAuthorNameAndEmail() {
36953                     var comments = [];
36954                     var inEmail = false;
36955                     var token = scanner.getToken();
36956                     while (token !== 1 /* EndOfFileToken */ && token !== 4 /* NewLineTrivia */) {
36957                         if (token === 29 /* LessThanToken */) {
36958                             inEmail = true;
36959                         }
36960                         else if (token === 59 /* AtToken */ && !inEmail) {
36961                             break;
36962                         }
36963                         else if (token === 31 /* GreaterThanToken */ && inEmail) {
36964                             comments.push(scanner.getTokenText());
36965                             scanner.setTextPos(scanner.getTokenPos() + 1);
36966                             break;
36967                         }
36968                         comments.push(scanner.getTokenText());
36969                         token = nextTokenJSDoc();
36970                     }
36971                     return factory.createJSDocText(comments.join(""));
36972                 }
36973                 function parseImplementsTag(start, tagName, margin, indentText) {
36974                     var className = parseExpressionWithTypeArgumentsForAugments();
36975                     return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
36976                 }
36977                 function parseAugmentsTag(start, tagName, margin, indentText) {
36978                     var className = parseExpressionWithTypeArgumentsForAugments();
36979                     return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
36980                 }
36981                 function parseExpressionWithTypeArgumentsForAugments() {
36982                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
36983                     var pos = getNodePos();
36984                     var expression = parsePropertyAccessEntityNameExpression();
36985                     var typeArguments = tryParseTypeArguments();
36986                     var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
36987                     var res = finishNode(node, pos);
36988                     if (usedBrace) {
36989                         parseExpected(19 /* CloseBraceToken */);
36990                     }
36991                     return res;
36992                 }
36993                 function parsePropertyAccessEntityNameExpression() {
36994                     var pos = getNodePos();
36995                     var node = parseJSDocIdentifierName();
36996                     while (parseOptional(24 /* DotToken */)) {
36997                         var name = parseJSDocIdentifierName();
36998                         node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
36999                     }
37000                     return node;
37001                 }
37002                 function parseSimpleTag(start, createTag, tagName, margin, indentText) {
37003                     return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
37004                 }
37005                 function parseThisTag(start, tagName, margin, indentText) {
37006                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
37007                     skipWhitespace();
37008                     return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
37009                 }
37010                 function parseEnumTag(start, tagName, margin, indentText) {
37011                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
37012                     skipWhitespace();
37013                     return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start);
37014                 }
37015                 function parseTypedefTag(start, tagName, indent, indentText) {
37016                     var _a;
37017                     var typeExpression = tryParseTypeExpression();
37018                     skipWhitespaceOrAsterisk();
37019                     var fullName = parseJSDocTypeNameWithNamespace();
37020                     skipWhitespace();
37021                     var comment = parseTagComments(indent);
37022                     var end;
37023                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
37024                         var child = void 0;
37025                         var childTypeTag = void 0;
37026                         var jsDocPropertyTags = void 0;
37027                         var hasChildren = false;
37028                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
37029                             hasChildren = true;
37030                             if (child.kind === 341 /* JSDocTypeTag */) {
37031                                 if (childTypeTag) {
37032                                     parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
37033                                     var lastError = ts.lastOrUndefined(parseDiagnostics);
37034                                     if (lastError) {
37035                                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
37036                                     }
37037                                     break;
37038                                 }
37039                                 else {
37040                                     childTypeTag = child;
37041                                 }
37042                             }
37043                             else {
37044                                 jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
37045                             }
37046                         }
37047                         if (hasChildren) {
37048                             var isArrayType = typeExpression && typeExpression.type.kind === 182 /* ArrayType */;
37049                             var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
37050                             typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
37051                                 childTypeTag.typeExpression :
37052                                 finishNode(jsdocTypeLiteral, start);
37053                             end = typeExpression.end;
37054                         }
37055                     }
37056                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
37057                     end = end || comment !== undefined ?
37058                         getNodePos() :
37059                         ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
37060                     if (!comment) {
37061                         comment = parseTrailingTagComments(start, end, indent, indentText);
37062                     }
37063                     var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
37064                     return finishNode(typedefTag, start, end);
37065                 }
37066                 function parseJSDocTypeNameWithNamespace(nested) {
37067                     var pos = scanner.getTokenPos();
37068                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
37069                         return undefined;
37070                     }
37071                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
37072                     if (parseOptional(24 /* DotToken */)) {
37073                         var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
37074                         var jsDocNamespaceNode = factory.createModuleDeclaration(
37075                         /*decorators*/ undefined, 
37076                         /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
37077                         return finishNode(jsDocNamespaceNode, pos);
37078                     }
37079                     if (nested) {
37080                         typeNameOrNamespaceName.isInJSDocNamespace = true;
37081                     }
37082                     return typeNameOrNamespaceName;
37083                 }
37084                 function parseCallbackTagParameters(indent) {
37085                     var pos = getNodePos();
37086                     var child;
37087                     var parameters;
37088                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
37089                         parameters = ts.append(parameters, child);
37090                     }
37091                     return createNodeArray(parameters || [], pos);
37092                 }
37093                 function parseCallbackTag(start, tagName, indent, indentText) {
37094                     var fullName = parseJSDocTypeNameWithNamespace();
37095                     skipWhitespace();
37096                     var comment = parseTagComments(indent);
37097                     var parameters = parseCallbackTagParameters(indent);
37098                     var returnTag = tryParse(function () {
37099                         if (parseOptionalJsdoc(59 /* AtToken */)) {
37100                             var tag = parseTag(indent);
37101                             if (tag && tag.kind === 339 /* JSDocReturnTag */) {
37102                                 return tag;
37103                             }
37104                         }
37105                     });
37106                     var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
37107                     if (!comment) {
37108                         comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
37109                     }
37110                     return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start);
37111                 }
37112                 function escapedTextsEqual(a, b) {
37113                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
37114                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
37115                             a = a.left;
37116                             b = b.left;
37117                         }
37118                         else {
37119                             return false;
37120                         }
37121                     }
37122                     return a.escapedText === b.escapedText;
37123                 }
37124                 function parseChildPropertyTag(indent) {
37125                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
37126                 }
37127                 function parseChildParameterOrPropertyTag(target, indent, name) {
37128                     var canParseTag = true;
37129                     var seenAsterisk = false;
37130                     while (true) {
37131                         switch (nextTokenJSDoc()) {
37132                             case 59 /* AtToken */:
37133                                 if (canParseTag) {
37134                                     var child = tryParseChildTag(target, indent);
37135                                     if (child && (child.kind === 338 /* JSDocParameterTag */ || child.kind === 345 /* JSDocPropertyTag */) &&
37136                                         target !== 4 /* CallbackParameter */ &&
37137                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
37138                                         return false;
37139                                     }
37140                                     return child;
37141                                 }
37142                                 seenAsterisk = false;
37143                                 break;
37144                             case 4 /* NewLineTrivia */:
37145                                 canParseTag = true;
37146                                 seenAsterisk = false;
37147                                 break;
37148                             case 41 /* AsteriskToken */:
37149                                 if (seenAsterisk) {
37150                                     canParseTag = false;
37151                                 }
37152                                 seenAsterisk = true;
37153                                 break;
37154                             case 79 /* Identifier */:
37155                                 canParseTag = false;
37156                                 break;
37157                             case 1 /* EndOfFileToken */:
37158                                 return false;
37159                         }
37160                     }
37161                 }
37162                 function tryParseChildTag(target, indent) {
37163                     ts.Debug.assert(token() === 59 /* AtToken */);
37164                     var start = scanner.getStartPos();
37165                     nextTokenJSDoc();
37166                     var tagName = parseJSDocIdentifierName();
37167                     skipWhitespace();
37168                     var t;
37169                     switch (tagName.escapedText) {
37170                         case "type":
37171                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
37172                         case "prop":
37173                         case "property":
37174                             t = 1 /* Property */;
37175                             break;
37176                         case "arg":
37177                         case "argument":
37178                         case "param":
37179                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
37180                             break;
37181                         default:
37182                             return false;
37183                     }
37184                     if (!(target & t)) {
37185                         return false;
37186                     }
37187                     return parseParameterOrPropertyTag(start, tagName, target, indent);
37188                 }
37189                 function parseTemplateTagTypeParameter() {
37190                     var typeParameterPos = getNodePos();
37191                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
37192                     if (isBracketed) {
37193                         skipWhitespace();
37194                     }
37195                     var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
37196                     var defaultType;
37197                     if (isBracketed) {
37198                         skipWhitespace();
37199                         parseExpected(63 /* EqualsToken */);
37200                         defaultType = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
37201                         parseExpected(23 /* CloseBracketToken */);
37202                     }
37203                     if (ts.nodeIsMissing(name)) {
37204                         return undefined;
37205                     }
37206                     return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, defaultType), typeParameterPos);
37207                 }
37208                 function parseTemplateTagTypeParameters() {
37209                     var pos = getNodePos();
37210                     var typeParameters = [];
37211                     do {
37212                         skipWhitespace();
37213                         var node = parseTemplateTagTypeParameter();
37214                         if (node !== undefined) {
37215                             typeParameters.push(node);
37216                         }
37217                         skipWhitespaceOrAsterisk();
37218                     } while (parseOptionalJsdoc(27 /* CommaToken */));
37219                     return createNodeArray(typeParameters, pos);
37220                 }
37221                 function parseTemplateTag(start, tagName, indent, indentText) {
37222                     // The template tag looks like one of the following:
37223                     //   @template T,U,V
37224                     //   @template {Constraint} T
37225                     //
37226                     // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
37227                     //   > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
37228                     //   > type bound they must be declared on separate lines.
37229                     //
37230                     // TODO: Determine whether we should enforce this in the checker.
37231                     // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
37232                     // TODO: Consider only parsing a single type parameter if there is a constraint.
37233                     var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
37234                     var typeParameters = parseTemplateTagTypeParameters();
37235                     return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
37236                 }
37237                 function parseOptionalJsdoc(t) {
37238                     if (token() === t) {
37239                         nextTokenJSDoc();
37240                         return true;
37241                     }
37242                     return false;
37243                 }
37244                 function parseJSDocEntityName() {
37245                     var entity = parseJSDocIdentifierName();
37246                     if (parseOptional(22 /* OpenBracketToken */)) {
37247                         parseExpected(23 /* CloseBracketToken */);
37248                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
37249                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
37250                         // but it's not worth it to enforce that restriction.
37251                     }
37252                     while (parseOptional(24 /* DotToken */)) {
37253                         var name = parseJSDocIdentifierName();
37254                         if (parseOptional(22 /* OpenBracketToken */)) {
37255                             parseExpected(23 /* CloseBracketToken */);
37256                         }
37257                         entity = createQualifiedName(entity, name);
37258                     }
37259                     return entity;
37260                 }
37261                 function parseJSDocIdentifierName(message) {
37262                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
37263                         return createMissingNode(79 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
37264                     }
37265                     identifierCount++;
37266                     var pos = scanner.getTokenPos();
37267                     var end = scanner.getTextPos();
37268                     var originalKeywordKind = token();
37269                     var text = internIdentifier(scanner.getTokenValue());
37270                     var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
37271                     nextTokenJSDoc();
37272                     return result;
37273                 }
37274             }
37275         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
37276     })(Parser || (Parser = {}));
37277     var IncrementalParser;
37278     (function (IncrementalParser) {
37279         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
37280             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
37281             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
37282             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
37283                 // if the text didn't change, then we can just return our current source file as-is.
37284                 return sourceFile;
37285             }
37286             if (sourceFile.statements.length === 0) {
37287                 // If we don't have any statements in the current source file, then there's no real
37288                 // way to incrementally parse.  So just do a full parse instead.
37289                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
37290             }
37291             // Make sure we're not trying to incrementally update a source file more than once.  Once
37292             // we do an update the original source file is considered unusable from that point onwards.
37293             //
37294             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
37295             // tree and give them new positions and parents.  From that point on, trusting the old
37296             // tree at all is not possible as far too much of it may violate invariants.
37297             var incrementalSourceFile = sourceFile;
37298             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
37299             incrementalSourceFile.hasBeenIncrementallyParsed = true;
37300             Parser.fixupParentReferences(incrementalSourceFile);
37301             var oldText = sourceFile.text;
37302             var syntaxCursor = createSyntaxCursor(sourceFile);
37303             // Make the actual change larger so that we know to reparse anything whose lookahead
37304             // might have intersected the change.
37305             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
37306             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
37307             // Ensure that extending the affected range only moved the start of the change range
37308             // earlier in the file.
37309             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
37310             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
37311             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
37312             // The is the amount the nodes after the edit range need to be adjusted.  It can be
37313             // positive (if the edit added characters), negative (if the edit deleted characters)
37314             // or zero (if this was a pure overwrite with nothing added/removed).
37315             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
37316             // If we added or removed characters during the edit, then we need to go and adjust all
37317             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
37318             // may move backward (if we deleted chars).
37319             //
37320             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
37321             // to reuse are already at the appropriate position in the new text.  That way when we
37322             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
37323             // it very easy to determine if we can reuse a node.  If the node's position is at where
37324             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
37325             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
37326             // us, then we'll need to skip it or crumble it as appropriate
37327             //
37328             // We will also adjust the positions of nodes that intersect the change range as well.
37329             // By doing this, we ensure that all the positions in the old tree are consistent, not
37330             // just the positions of nodes entirely before/after the change range.  By being
37331             // consistent, we can then easily map from positions to nodes in the old tree easily.
37332             //
37333             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
37334             // that we cannot reuse these elements.
37335             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
37336             // Now that we've set up our internal incremental state just proceed and parse the
37337             // source file in the normal fashion.  When possible the parser will retrieve and
37338             // reuse nodes from the old tree.
37339             //
37340             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
37341             // parsing, we will be reusing nodes from the old tree, and placing it into new
37342             // parents.  If we don't set the parents now, we'll end up with an observably
37343             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
37344             // will immediately bail out of walking any subtrees when we can see that their parents
37345             // are already correct.
37346             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
37347             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
37348             result.impliedNodeFormat = sourceFile.impliedNodeFormat;
37349             return result;
37350         }
37351         IncrementalParser.updateSourceFile = updateSourceFile;
37352         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
37353             if (!oldDirectives)
37354                 return newDirectives;
37355             var commentDirectives;
37356             var addedNewlyScannedDirectives = false;
37357             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
37358                 var directive = oldDirectives_1[_i];
37359                 var range = directive.range, type = directive.type;
37360                 // Range before the change
37361                 if (range.end < changeStart) {
37362                     commentDirectives = ts.append(commentDirectives, directive);
37363                 }
37364                 else if (range.pos > changeRangeOldEnd) {
37365                     addNewlyScannedDirectives();
37366                     // Node is entirely past the change range.  We need to move both its pos and
37367                     // end, forward or backward appropriately.
37368                     var updatedDirective = {
37369                         range: { pos: range.pos + delta, end: range.end + delta },
37370                         type: type
37371                     };
37372                     commentDirectives = ts.append(commentDirectives, updatedDirective);
37373                     if (aggressiveChecks) {
37374                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
37375                     }
37376                 }
37377                 // Ignore ranges that fall in change range
37378             }
37379             addNewlyScannedDirectives();
37380             return commentDirectives;
37381             function addNewlyScannedDirectives() {
37382                 if (addedNewlyScannedDirectives)
37383                     return;
37384                 addedNewlyScannedDirectives = true;
37385                 if (!commentDirectives) {
37386                     commentDirectives = newDirectives;
37387                 }
37388                 else if (newDirectives) {
37389                     commentDirectives.push.apply(commentDirectives, newDirectives);
37390                 }
37391             }
37392         }
37393         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
37394             if (isArray) {
37395                 visitArray(element);
37396             }
37397             else {
37398                 visitNode(element);
37399             }
37400             return;
37401             function visitNode(node) {
37402                 var text = "";
37403                 if (aggressiveChecks && shouldCheckNode(node)) {
37404                     text = oldText.substring(node.pos, node.end);
37405                 }
37406                 // Ditch any existing LS children we may have created.  This way we can avoid
37407                 // moving them forward.
37408                 if (node._children) {
37409                     node._children = undefined;
37410                 }
37411                 ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
37412                 if (aggressiveChecks && shouldCheckNode(node)) {
37413                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
37414                 }
37415                 forEachChild(node, visitNode, visitArray);
37416                 if (ts.hasJSDocNodes(node)) {
37417                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
37418                         var jsDocComment = _a[_i];
37419                         visitNode(jsDocComment);
37420                     }
37421                 }
37422                 checkNodePositions(node, aggressiveChecks);
37423             }
37424             function visitArray(array) {
37425                 array._children = undefined;
37426                 ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
37427                 for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
37428                     var node = array_9[_i];
37429                     visitNode(node);
37430                 }
37431             }
37432         }
37433         function shouldCheckNode(node) {
37434             switch (node.kind) {
37435                 case 10 /* StringLiteral */:
37436                 case 8 /* NumericLiteral */:
37437                 case 79 /* Identifier */:
37438                     return true;
37439             }
37440             return false;
37441         }
37442         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
37443             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
37444             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
37445             ts.Debug.assert(element.pos <= element.end);
37446             // We have an element that intersects the change range in some way.  It may have its
37447             // start, or its end (or both) in the changed range.  We want to adjust any part
37448             // that intersects such that the final tree is in a consistent state.  i.e. all
37449             // children have spans within the span of their parent, and all siblings are ordered
37450             // properly.
37451             // We may need to update both the 'pos' and the 'end' of the element.
37452             // If the 'pos' is before the start of the change, then we don't need to touch it.
37453             // If it isn't, then the 'pos' must be inside the change.  How we update it will
37454             // depend if delta is positive or negative. If delta is positive then we have
37455             // something like:
37456             //
37457             //  -------------------AAA-----------------
37458             //  -------------------BBBCCCCCCC-----------------
37459             //
37460             // In this case, we consider any node that started in the change range to still be
37461             // starting at the same position.
37462             //
37463             // however, if the delta is negative, then we instead have something like this:
37464             //
37465             //  -------------------XXXYYYYYYY-----------------
37466             //  -------------------ZZZ-----------------
37467             //
37468             // In this case, any element that started in the 'X' range will keep its position.
37469             // However any element that started after that will have their pos adjusted to be
37470             // at the end of the new range.  i.e. any node that started in the 'Y' range will
37471             // be adjusted to have their start at the end of the 'Z' range.
37472             //
37473             // The element will keep its position if possible.  Or Move backward to the new-end
37474             // if it's in the 'Y' range.
37475             var pos = Math.min(element.pos, changeRangeNewEnd);
37476             // If the 'end' is after the change range, then we always adjust it by the delta
37477             // amount.  However, if the end is in the change range, then how we adjust it
37478             // will depend on if delta is positive or negative.  If delta is positive then we
37479             // have something like:
37480             //
37481             //  -------------------AAA-----------------
37482             //  -------------------BBBCCCCCCC-----------------
37483             //
37484             // In this case, we consider any node that ended inside the change range to keep its
37485             // end position.
37486             //
37487             // however, if the delta is negative, then we instead have something like this:
37488             //
37489             //  -------------------XXXYYYYYYY-----------------
37490             //  -------------------ZZZ-----------------
37491             //
37492             // In this case, any element that ended in the 'X' range will keep its position.
37493             // However any element that ended after that will have their pos adjusted to be
37494             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
37495             // be adjusted to have their end at the end of the 'Z' range.
37496             var end = element.end >= changeRangeOldEnd ?
37497                 // Element ends after the change range.  Always adjust the end pos.
37498                 element.end + delta :
37499                 // Element ends in the change range.  The element will keep its position if
37500                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
37501                 Math.min(element.end, changeRangeNewEnd);
37502             ts.Debug.assert(pos <= end);
37503             if (element.parent) {
37504                 ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
37505                 ts.Debug.assertLessThanOrEqual(end, element.parent.end);
37506             }
37507             ts.setTextRangePosEnd(element, pos, end);
37508         }
37509         function checkNodePositions(node, aggressiveChecks) {
37510             if (aggressiveChecks) {
37511                 var pos_2 = node.pos;
37512                 var visitNode_1 = function (child) {
37513                     ts.Debug.assert(child.pos >= pos_2);
37514                     pos_2 = child.end;
37515                 };
37516                 if (ts.hasJSDocNodes(node)) {
37517                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
37518                         var jsDocComment = _a[_i];
37519                         visitNode_1(jsDocComment);
37520                     }
37521                 }
37522                 forEachChild(node, visitNode_1);
37523                 ts.Debug.assert(pos_2 <= node.end);
37524             }
37525         }
37526         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
37527             visitNode(sourceFile);
37528             return;
37529             function visitNode(child) {
37530                 ts.Debug.assert(child.pos <= child.end);
37531                 if (child.pos > changeRangeOldEnd) {
37532                     // Node is entirely past the change range.  We need to move both its pos and
37533                     // end, forward or backward appropriately.
37534                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
37535                     return;
37536                 }
37537                 // Check if the element intersects the change range.  If it does, then it is not
37538                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
37539                 // be able to use.
37540                 var fullEnd = child.end;
37541                 if (fullEnd >= changeStart) {
37542                     child.intersectsChange = true;
37543                     child._children = undefined;
37544                     // Adjust the pos or end (or both) of the intersecting element accordingly.
37545                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
37546                     forEachChild(child, visitNode, visitArray);
37547                     if (ts.hasJSDocNodes(child)) {
37548                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
37549                             var jsDocComment = _a[_i];
37550                             visitNode(jsDocComment);
37551                         }
37552                     }
37553                     checkNodePositions(child, aggressiveChecks);
37554                     return;
37555                 }
37556                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
37557                 ts.Debug.assert(fullEnd < changeStart);
37558             }
37559             function visitArray(array) {
37560                 ts.Debug.assert(array.pos <= array.end);
37561                 if (array.pos > changeRangeOldEnd) {
37562                     // Array is entirely after the change range.  We need to move it, and move any of
37563                     // its children.
37564                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
37565                     return;
37566                 }
37567                 // Check if the element intersects the change range.  If it does, then it is not
37568                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
37569                 // be able to use.
37570                 var fullEnd = array.end;
37571                 if (fullEnd >= changeStart) {
37572                     array.intersectsChange = true;
37573                     array._children = undefined;
37574                     // Adjust the pos or end (or both) of the intersecting array accordingly.
37575                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
37576                     for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
37577                         var node = array_10[_i];
37578                         visitNode(node);
37579                     }
37580                     return;
37581                 }
37582                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
37583                 ts.Debug.assert(fullEnd < changeStart);
37584             }
37585         }
37586         function extendToAffectedRange(sourceFile, changeRange) {
37587             // Consider the following code:
37588             //      void foo() { /; }
37589             //
37590             // If the text changes with an insertion of / just before the semicolon then we end up with:
37591             //      void foo() { //; }
37592             //
37593             // If we were to just use the changeRange a is, then we would not rescan the { token
37594             // (as it does not intersect the actual original change range).  Because an edit may
37595             // change the token touching it, we actually need to look back *at least* one token so
37596             // that the prior token sees that change.
37597             var maxLookahead = 1;
37598             var start = changeRange.span.start;
37599             // the first iteration aligns us with the change start. subsequent iteration move us to
37600             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
37601             // start of the tree.
37602             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
37603                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
37604                 ts.Debug.assert(nearestNode.pos <= start);
37605                 var position = nearestNode.pos;
37606                 start = Math.max(0, position - 1);
37607             }
37608             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
37609             var finalLength = changeRange.newLength + (changeRange.span.start - start);
37610             return ts.createTextChangeRange(finalSpan, finalLength);
37611         }
37612         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
37613             var bestResult = sourceFile;
37614             var lastNodeEntirelyBeforePosition;
37615             forEachChild(sourceFile, visit);
37616             if (lastNodeEntirelyBeforePosition) {
37617                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
37618                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
37619                     bestResult = lastChildOfLastEntireNodeBeforePosition;
37620                 }
37621             }
37622             return bestResult;
37623             function getLastDescendant(node) {
37624                 while (true) {
37625                     var lastChild = ts.getLastChild(node);
37626                     if (lastChild) {
37627                         node = lastChild;
37628                     }
37629                     else {
37630                         return node;
37631                     }
37632                 }
37633             }
37634             function visit(child) {
37635                 if (ts.nodeIsMissing(child)) {
37636                     // Missing nodes are effectively invisible to us.  We never even consider them
37637                     // When trying to find the nearest node before us.
37638                     return;
37639                 }
37640                 // If the child intersects this position, then this node is currently the nearest
37641                 // node that starts before the position.
37642                 if (child.pos <= position) {
37643                     if (child.pos >= bestResult.pos) {
37644                         // This node starts before the position, and is closer to the position than
37645                         // the previous best node we found.  It is now the new best node.
37646                         bestResult = child;
37647                     }
37648                     // Now, the node may overlap the position, or it may end entirely before the
37649                     // position.  If it overlaps with the position, then either it, or one of its
37650                     // children must be the nearest node before the position.  So we can just
37651                     // recurse into this child to see if we can find something better.
37652                     if (position < child.end) {
37653                         // The nearest node is either this child, or one of the children inside
37654                         // of it.  We've already marked this child as the best so far.  Recurse
37655                         // in case one of the children is better.
37656                         forEachChild(child, visit);
37657                         // Once we look at the children of this node, then there's no need to
37658                         // continue any further.
37659                         return true;
37660                     }
37661                     else {
37662                         ts.Debug.assert(child.end <= position);
37663                         // The child ends entirely before this position.  Say you have the following
37664                         // (where $ is the position)
37665                         //
37666                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
37667                         //
37668                         // We would want to find the nearest preceding node in "complex expr 2".
37669                         // To support that, we keep track of this node, and once we're done searching
37670                         // for a best node, we recurse down this node to see if we can find a good
37671                         // result in it.
37672                         //
37673                         // This approach allows us to quickly skip over nodes that are entirely
37674                         // before the position, while still allowing us to find any nodes in the
37675                         // last one that might be what we want.
37676                         lastNodeEntirelyBeforePosition = child;
37677                     }
37678                 }
37679                 else {
37680                     ts.Debug.assert(child.pos > position);
37681                     // We're now at a node that is entirely past the position we're searching for.
37682                     // This node (and all following nodes) could never contribute to the result,
37683                     // so just skip them by returning 'true' here.
37684                     return true;
37685                 }
37686             }
37687         }
37688         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
37689             var oldText = sourceFile.text;
37690             if (textChangeRange) {
37691                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
37692                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
37693                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
37694                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
37695                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
37696                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
37697                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
37698                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
37699                 }
37700             }
37701         }
37702         function createSyntaxCursor(sourceFile) {
37703             var currentArray = sourceFile.statements;
37704             var currentArrayIndex = 0;
37705             ts.Debug.assert(currentArrayIndex < currentArray.length);
37706             var current = currentArray[currentArrayIndex];
37707             var lastQueriedPosition = -1 /* Value */;
37708             return {
37709                 currentNode: function (position) {
37710                     // Only compute the current node if the position is different than the last time
37711                     // we were asked.  The parser commonly asks for the node at the same position
37712                     // twice.  Once to know if can read an appropriate list element at a certain point,
37713                     // and then to actually read and consume the node.
37714                     if (position !== lastQueriedPosition) {
37715                         // Much of the time the parser will need the very next node in the array that
37716                         // we just returned a node from.So just simply check for that case and move
37717                         // forward in the array instead of searching for the node again.
37718                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
37719                             currentArrayIndex++;
37720                             current = currentArray[currentArrayIndex];
37721                         }
37722                         // If we don't have a node, or the node we have isn't in the right position,
37723                         // then try to find a viable node at the position requested.
37724                         if (!current || current.pos !== position) {
37725                             findHighestListElementThatStartsAtPosition(position);
37726                         }
37727                     }
37728                     // Cache this query so that we don't do any extra work if the parser calls back
37729                     // into us.  Note: this is very common as the parser will make pairs of calls like
37730                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
37731                     // called with 'isListElement', we don't want to redo the work when parseListElement
37732                     // is called immediately after.
37733                     lastQueriedPosition = position;
37734                     // Either we don'd have a node, or we have a node at the position being asked for.
37735                     ts.Debug.assert(!current || current.pos === position);
37736                     return current;
37737                 }
37738             };
37739             // Finds the highest element in the tree we can find that starts at the provided position.
37740             // The element must be a direct child of some node list in the tree.  This way after we
37741             // return it, we can easily return its next sibling in the list.
37742             function findHighestListElementThatStartsAtPosition(position) {
37743                 // Clear out any cached state about the last node we found.
37744                 currentArray = undefined;
37745                 currentArrayIndex = -1 /* Value */;
37746                 current = undefined;
37747                 // Recurse into the source file to find the highest node at this position.
37748                 forEachChild(sourceFile, visitNode, visitArray);
37749                 return;
37750                 function visitNode(node) {
37751                     if (position >= node.pos && position < node.end) {
37752                         // Position was within this node.  Keep searching deeper to find the node.
37753                         forEachChild(node, visitNode, visitArray);
37754                         // don't proceed any further in the search.
37755                         return true;
37756                     }
37757                     // position wasn't in this node, have to keep searching.
37758                     return false;
37759                 }
37760                 function visitArray(array) {
37761                     if (position >= array.pos && position < array.end) {
37762                         // position was in this array.  Search through this array to see if we find a
37763                         // viable element.
37764                         for (var i = 0; i < array.length; i++) {
37765                             var child = array[i];
37766                             if (child) {
37767                                 if (child.pos === position) {
37768                                     // Found the right node.  We're done.
37769                                     currentArray = array;
37770                                     currentArrayIndex = i;
37771                                     current = child;
37772                                     return true;
37773                                 }
37774                                 else {
37775                                     if (child.pos < position && position < child.end) {
37776                                         // Position in somewhere within this child.  Search in it and
37777                                         // stop searching in this array.
37778                                         forEachChild(child, visitNode, visitArray);
37779                                         return true;
37780                                     }
37781                                 }
37782                             }
37783                         }
37784                     }
37785                     // position wasn't in this array, have to keep searching.
37786                     return false;
37787                 }
37788             }
37789         }
37790         IncrementalParser.createSyntaxCursor = createSyntaxCursor;
37791         var InvalidPosition;
37792         (function (InvalidPosition) {
37793             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
37794         })(InvalidPosition || (InvalidPosition = {}));
37795     })(IncrementalParser || (IncrementalParser = {}));
37796     /** @internal */
37797     function isDeclarationFileName(fileName) {
37798         return ts.fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]);
37799     }
37800     ts.isDeclarationFileName = isDeclarationFileName;
37801     /*@internal*/
37802     function processCommentPragmas(context, sourceText) {
37803         var pragmas = [];
37804         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
37805             var range = _a[_i];
37806             var comment = sourceText.substring(range.pos, range.end);
37807             extractPragmas(pragmas, range, comment);
37808         }
37809         context.pragmas = new ts.Map();
37810         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
37811             var pragma = pragmas_1[_b];
37812             if (context.pragmas.has(pragma.name)) {
37813                 var currentValue = context.pragmas.get(pragma.name);
37814                 if (currentValue instanceof Array) {
37815                     currentValue.push(pragma.args);
37816                 }
37817                 else {
37818                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
37819                 }
37820                 continue;
37821             }
37822             context.pragmas.set(pragma.name, pragma.args);
37823         }
37824     }
37825     ts.processCommentPragmas = processCommentPragmas;
37826     /*@internal*/
37827     function processPragmasIntoFields(context, reportDiagnostic) {
37828         context.checkJsDirective = undefined;
37829         context.referencedFiles = [];
37830         context.typeReferenceDirectives = [];
37831         context.libReferenceDirectives = [];
37832         context.amdDependencies = [];
37833         context.hasNoDefaultLib = false;
37834         context.pragmas.forEach(function (entryOrList, key) {
37835             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
37836             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
37837             switch (key) {
37838                 case "reference": {
37839                     var referencedFiles_1 = context.referencedFiles;
37840                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
37841                     var libReferenceDirectives_1 = context.libReferenceDirectives;
37842                     ts.forEach(ts.toArray(entryOrList), function (arg) {
37843                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
37844                         if (arg.arguments["no-default-lib"]) {
37845                             context.hasNoDefaultLib = true;
37846                         }
37847                         else if (types) {
37848                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
37849                         }
37850                         else if (lib) {
37851                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
37852                         }
37853                         else if (path) {
37854                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
37855                         }
37856                         else {
37857                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
37858                         }
37859                     });
37860                     break;
37861                 }
37862                 case "amd-dependency": {
37863                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
37864                     break;
37865                 }
37866                 case "amd-module": {
37867                     if (entryOrList instanceof Array) {
37868                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
37869                             var entry = entryOrList_1[_i];
37870                             if (context.moduleName) {
37871                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
37872                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
37873                             }
37874                             context.moduleName = entry.arguments.name;
37875                         }
37876                     }
37877                     else {
37878                         context.moduleName = entryOrList.arguments.name;
37879                     }
37880                     break;
37881                 }
37882                 case "ts-nocheck":
37883                 case "ts-check": {
37884                     // _last_ of either nocheck or check in a file is the "winner"
37885                     ts.forEach(ts.toArray(entryOrList), function (entry) {
37886                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
37887                             context.checkJsDirective = {
37888                                 enabled: key === "ts-check",
37889                                 end: entry.range.end,
37890                                 pos: entry.range.pos
37891                             };
37892                         }
37893                     });
37894                     break;
37895                 }
37896                 case "jsx":
37897                 case "jsxfrag":
37898                 case "jsximportsource":
37899                 case "jsxruntime":
37900                     return; // Accessed directly
37901                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
37902             }
37903         });
37904     }
37905     ts.processPragmasIntoFields = processPragmasIntoFields;
37906     var namedArgRegExCache = new ts.Map();
37907     function getNamedArgRegEx(name) {
37908         if (namedArgRegExCache.has(name)) {
37909             return namedArgRegExCache.get(name);
37910         }
37911         var result = new RegExp("(\\s".concat(name, "\\s*=\\s*)(?:(?:'([^']*)')|(?:\"([^\"]*)\"))"), "im");
37912         namedArgRegExCache.set(name, result);
37913         return result;
37914     }
37915     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
37916     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
37917     function extractPragmas(pragmas, range, text) {
37918         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
37919         if (tripleSlash) {
37920             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
37921             var pragma = ts.commentPragmas[name];
37922             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
37923                 return;
37924             }
37925             if (pragma.args) {
37926                 var argument = {};
37927                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
37928                     var arg = _a[_i];
37929                     var matcher = getNamedArgRegEx(arg.name);
37930                     var matchResult = matcher.exec(text);
37931                     if (!matchResult && !arg.optional) {
37932                         return; // Missing required argument, don't parse
37933                     }
37934                     else if (matchResult) {
37935                         var value = matchResult[2] || matchResult[3];
37936                         if (arg.captureSpan) {
37937                             var startPos = range.pos + matchResult.index + matchResult[1].length + 1;
37938                             argument[arg.name] = {
37939                                 value: value,
37940                                 pos: startPos,
37941                                 end: startPos + value.length
37942                             };
37943                         }
37944                         else {
37945                             argument[arg.name] = value;
37946                         }
37947                     }
37948                 }
37949                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
37950             }
37951             else {
37952                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
37953             }
37954             return;
37955         }
37956         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
37957         if (singleLine) {
37958             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
37959         }
37960         if (range.kind === 3 /* MultiLineCommentTrivia */) {
37961             var multiLinePragmaRegEx = /@(\S+)(\s+.*)?$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
37962             var multiLineMatch = void 0;
37963             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
37964                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
37965             }
37966         }
37967     }
37968     function addPragmaForMatch(pragmas, range, kind, match) {
37969         if (!match)
37970             return;
37971         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
37972         var pragma = ts.commentPragmas[name];
37973         if (!pragma || !(pragma.kind & kind)) {
37974             return;
37975         }
37976         var args = match[2]; // Split on spaces and match up positionally with definition
37977         var argument = getNamedPragmaArguments(pragma, args);
37978         if (argument === "fail")
37979             return; // Missing required argument, fail to parse it
37980         pragmas.push({ name: name, args: { arguments: argument, range: range } });
37981         return;
37982     }
37983     function getNamedPragmaArguments(pragma, text) {
37984         if (!text)
37985             return {};
37986         if (!pragma.args)
37987             return {};
37988         var args = ts.trimString(text).split(/\s+/);
37989         var argMap = {};
37990         for (var i = 0; i < pragma.args.length; i++) {
37991             var argument = pragma.args[i];
37992             if (!args[i] && !argument.optional) {
37993                 return "fail";
37994             }
37995             if (argument.captureSpan) {
37996                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
37997             }
37998             argMap[argument.name] = args[i];
37999         }
38000         return argMap;
38001     }
38002     /** @internal */
38003     function tagNamesAreEquivalent(lhs, rhs) {
38004         if (lhs.kind !== rhs.kind) {
38005             return false;
38006         }
38007         if (lhs.kind === 79 /* Identifier */) {
38008             return lhs.escapedText === rhs.escapedText;
38009         }
38010         if (lhs.kind === 108 /* ThisKeyword */) {
38011             return true;
38012         }
38013         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
38014         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
38015         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
38016         return lhs.name.escapedText === rhs.name.escapedText &&
38017             tagNamesAreEquivalent(lhs.expression, rhs.expression);
38018     }
38019     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
38020 })(ts || (ts = {}));
38021 var ts;
38022 (function (ts) {
38023     /* @internal */
38024     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" };
38025     var jsxOptionMap = new ts.Map(ts.getEntries({
38026         "preserve": 1 /* Preserve */,
38027         "react-native": 3 /* ReactNative */,
38028         "react": 2 /* React */,
38029         "react-jsx": 4 /* ReactJSX */,
38030         "react-jsxdev": 5 /* ReactJSXDev */,
38031     }));
38032     /* @internal */
38033     ts.inverseJsxOptionMap = new ts.Map(ts.arrayFrom(ts.mapIterator(jsxOptionMap.entries(), function (_a) {
38034         var key = _a[0], value = _a[1];
38035         return ["" + value, key];
38036     })));
38037     // NOTE: The order here is important to default lib ordering as entries will have the same
38038     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
38039     //       order also affects overload resolution when a type declared in one lib is
38040     //       augmented in another lib.
38041     var libEntries = [
38042         // JavaScript only
38043         ["es5", "lib.es5.d.ts"],
38044         ["es6", "lib.es2015.d.ts"],
38045         ["es2015", "lib.es2015.d.ts"],
38046         ["es7", "lib.es2016.d.ts"],
38047         ["es2016", "lib.es2016.d.ts"],
38048         ["es2017", "lib.es2017.d.ts"],
38049         ["es2018", "lib.es2018.d.ts"],
38050         ["es2019", "lib.es2019.d.ts"],
38051         ["es2020", "lib.es2020.d.ts"],
38052         ["es2021", "lib.es2021.d.ts"],
38053         ["esnext", "lib.esnext.d.ts"],
38054         // Host only
38055         ["dom", "lib.dom.d.ts"],
38056         ["dom.iterable", "lib.dom.iterable.d.ts"],
38057         ["webworker", "lib.webworker.d.ts"],
38058         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
38059         ["webworker.iterable", "lib.webworker.iterable.d.ts"],
38060         ["scripthost", "lib.scripthost.d.ts"],
38061         // ES2015 Or ESNext By-feature options
38062         ["es2015.core", "lib.es2015.core.d.ts"],
38063         ["es2015.collection", "lib.es2015.collection.d.ts"],
38064         ["es2015.generator", "lib.es2015.generator.d.ts"],
38065         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
38066         ["es2015.promise", "lib.es2015.promise.d.ts"],
38067         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
38068         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
38069         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
38070         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
38071         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
38072         ["es2017.object", "lib.es2017.object.d.ts"],
38073         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
38074         ["es2017.string", "lib.es2017.string.d.ts"],
38075         ["es2017.intl", "lib.es2017.intl.d.ts"],
38076         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
38077         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
38078         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
38079         ["es2018.intl", "lib.es2018.intl.d.ts"],
38080         ["es2018.promise", "lib.es2018.promise.d.ts"],
38081         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
38082         ["es2019.array", "lib.es2019.array.d.ts"],
38083         ["es2019.object", "lib.es2019.object.d.ts"],
38084         ["es2019.string", "lib.es2019.string.d.ts"],
38085         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
38086         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
38087         ["es2020.promise", "lib.es2020.promise.d.ts"],
38088         ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
38089         ["es2020.string", "lib.es2020.string.d.ts"],
38090         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
38091         ["es2020.intl", "lib.es2020.intl.d.ts"],
38092         ["es2021.promise", "lib.es2021.promise.d.ts"],
38093         ["es2021.string", "lib.es2021.string.d.ts"],
38094         ["es2021.weakref", "lib.es2021.weakref.d.ts"],
38095         ["es2021.intl", "lib.es2021.intl.d.ts"],
38096         ["esnext.array", "lib.es2019.array.d.ts"],
38097         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
38098         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
38099         ["esnext.intl", "lib.esnext.intl.d.ts"],
38100         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
38101         ["esnext.string", "lib.es2021.string.d.ts"],
38102         ["esnext.promise", "lib.es2021.promise.d.ts"],
38103         ["esnext.weakref", "lib.es2021.weakref.d.ts"]
38104     ];
38105     /**
38106      * An array of supported "lib" reference file names used to determine the order for inclusion
38107      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
38108      * overload resolution when a type declared in one lib is extended by another.
38109      */
38110     /* @internal */
38111     ts.libs = libEntries.map(function (entry) { return entry[0]; });
38112     /**
38113      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
38114      * option as well as for resolving lib reference directives.
38115      */
38116     /* @internal */
38117     ts.libMap = new ts.Map(libEntries);
38118     // Watch related options
38119     /* @internal */
38120     ts.optionsForWatch = [
38121         {
38122             name: "watchFile",
38123             type: new ts.Map(ts.getEntries({
38124                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
38125                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
38126                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
38127                 fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling,
38128                 usefsevents: ts.WatchFileKind.UseFsEvents,
38129                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
38130             })),
38131             category: ts.Diagnostics.Watch_and_Build_Modes,
38132             description: ts.Diagnostics.Specify_how_the_TypeScript_watch_mode_works,
38133         },
38134         {
38135             name: "watchDirectory",
38136             type: new ts.Map(ts.getEntries({
38137                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
38138                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
38139                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
38140                 fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling,
38141             })),
38142             category: ts.Diagnostics.Watch_and_Build_Modes,
38143             description: ts.Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality,
38144         },
38145         {
38146             name: "fallbackPolling",
38147             type: new ts.Map(ts.getEntries({
38148                 fixedinterval: ts.PollingWatchKind.FixedInterval,
38149                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
38150                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
38151                 fixedchunksize: ts.PollingWatchKind.FixedChunkSize,
38152             })),
38153             category: ts.Diagnostics.Watch_and_Build_Modes,
38154             description: ts.Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers,
38155         },
38156         {
38157             name: "synchronousWatchDirectory",
38158             type: "boolean",
38159             category: ts.Diagnostics.Watch_and_Build_Modes,
38160             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
38161             defaultValueDescription: "false",
38162         },
38163         {
38164             name: "excludeDirectories",
38165             type: "list",
38166             element: {
38167                 name: "excludeDirectory",
38168                 type: "string",
38169                 isFilePath: true,
38170                 extraValidation: specToDiagnostic
38171             },
38172             category: ts.Diagnostics.Watch_and_Build_Modes,
38173             description: ts.Diagnostics.Remove_a_list_of_directories_from_the_watch_process,
38174         },
38175         {
38176             name: "excludeFiles",
38177             type: "list",
38178             element: {
38179                 name: "excludeFile",
38180                 type: "string",
38181                 isFilePath: true,
38182                 extraValidation: specToDiagnostic
38183             },
38184             category: ts.Diagnostics.Watch_and_Build_Modes,
38185             description: ts.Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing,
38186         },
38187     ];
38188     /* @internal */
38189     ts.commonOptionsWithBuild = [
38190         {
38191             name: "help",
38192             shortName: "h",
38193             type: "boolean",
38194             showInSimplifiedHelpView: true,
38195             category: ts.Diagnostics.Command_line_Options,
38196             description: ts.Diagnostics.Print_this_message,
38197             defaultValueDescription: "false",
38198         },
38199         {
38200             name: "help",
38201             shortName: "?",
38202             type: "boolean",
38203             defaultValueDescription: "false",
38204         },
38205         {
38206             name: "watch",
38207             shortName: "w",
38208             type: "boolean",
38209             showInSimplifiedHelpView: true,
38210             isCommandLineOnly: true,
38211             category: ts.Diagnostics.Command_line_Options,
38212             description: ts.Diagnostics.Watch_input_files,
38213             defaultValueDescription: "false",
38214         },
38215         {
38216             name: "preserveWatchOutput",
38217             type: "boolean",
38218             showInSimplifiedHelpView: false,
38219             category: ts.Diagnostics.Output_Formatting,
38220             description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode,
38221             defaultValueDescription: "false",
38222         },
38223         {
38224             name: "listFiles",
38225             type: "boolean",
38226             category: ts.Diagnostics.Compiler_Diagnostics,
38227             description: ts.Diagnostics.Print_all_of_the_files_read_during_the_compilation,
38228             defaultValueDescription: "false"
38229         },
38230         {
38231             name: "explainFiles",
38232             type: "boolean",
38233             category: ts.Diagnostics.Compiler_Diagnostics,
38234             description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included,
38235             defaultValueDescription: "false",
38236         },
38237         {
38238             name: "listEmittedFiles",
38239             type: "boolean",
38240             category: ts.Diagnostics.Compiler_Diagnostics,
38241             description: ts.Diagnostics.Print_the_names_of_emitted_files_after_a_compilation,
38242             defaultValueDescription: "false"
38243         },
38244         {
38245             name: "pretty",
38246             type: "boolean",
38247             showInSimplifiedHelpView: true,
38248             category: ts.Diagnostics.Output_Formatting,
38249             description: ts.Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read,
38250             defaultValueDescription: "true"
38251         },
38252         {
38253             name: "traceResolution",
38254             type: "boolean",
38255             category: ts.Diagnostics.Compiler_Diagnostics,
38256             description: ts.Diagnostics.Log_paths_used_during_the_moduleResolution_process,
38257             defaultValueDescription: "false"
38258         },
38259         {
38260             name: "diagnostics",
38261             type: "boolean",
38262             category: ts.Diagnostics.Compiler_Diagnostics,
38263             description: ts.Diagnostics.Output_compiler_performance_information_after_building,
38264             defaultValueDescription: "false"
38265         },
38266         {
38267             name: "extendedDiagnostics",
38268             type: "boolean",
38269             category: ts.Diagnostics.Compiler_Diagnostics,
38270             description: ts.Diagnostics.Output_more_detailed_compiler_performance_information_after_building,
38271             defaultValueDescription: "false"
38272         },
38273         {
38274             name: "generateCpuProfile",
38275             type: "string",
38276             isFilePath: true,
38277             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
38278             category: ts.Diagnostics.Compiler_Diagnostics,
38279             description: ts.Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging,
38280             defaultValueDescription: "profile.cpuprofile"
38281         },
38282         {
38283             name: "generateTrace",
38284             type: "string",
38285             isFilePath: true,
38286             isCommandLineOnly: true,
38287             paramType: ts.Diagnostics.DIRECTORY,
38288             category: ts.Diagnostics.Compiler_Diagnostics,
38289             description: ts.Diagnostics.Generates_an_event_trace_and_a_list_of_types
38290         },
38291         {
38292             name: "incremental",
38293             shortName: "i",
38294             type: "boolean",
38295             category: ts.Diagnostics.Projects,
38296             description: ts.Diagnostics.Enable_incremental_compilation,
38297             transpileOptionValue: undefined,
38298             defaultValueDescription: ts.Diagnostics.false_unless_composite_is_set
38299         },
38300         {
38301             name: "assumeChangesOnlyAffectDirectDependencies",
38302             type: "boolean",
38303             affectsSemanticDiagnostics: true,
38304             affectsEmit: true,
38305             category: ts.Diagnostics.Watch_and_Build_Modes,
38306             description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it,
38307             defaultValueDescription: "false",
38308         },
38309         {
38310             name: "locale",
38311             type: "string",
38312             category: ts.Diagnostics.Command_line_Options,
38313             isCommandLineOnly: true,
38314             description: ts.Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit,
38315             defaultValueDescription: ts.Diagnostics.Platform_specific
38316         },
38317     ];
38318     /* @internal */
38319     ts.targetOptionDeclaration = {
38320         name: "target",
38321         shortName: "t",
38322         type: new ts.Map(ts.getEntries({
38323             es3: 0 /* ES3 */,
38324             es5: 1 /* ES5 */,
38325             es6: 2 /* ES2015 */,
38326             es2015: 2 /* ES2015 */,
38327             es2016: 3 /* ES2016 */,
38328             es2017: 4 /* ES2017 */,
38329             es2018: 5 /* ES2018 */,
38330             es2019: 6 /* ES2019 */,
38331             es2020: 7 /* ES2020 */,
38332             es2021: 8 /* ES2021 */,
38333             esnext: 99 /* ESNext */,
38334         })),
38335         affectsSourceFile: true,
38336         affectsModuleResolution: true,
38337         affectsEmit: true,
38338         paramType: ts.Diagnostics.VERSION,
38339         showInSimplifiedHelpView: true,
38340         category: ts.Diagnostics.Language_and_Environment,
38341         description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations,
38342         defaultValueDescription: "ES3"
38343     };
38344     var commandOptionsWithoutBuild = [
38345         // CommandLine only options
38346         {
38347             name: "all",
38348             type: "boolean",
38349             showInSimplifiedHelpView: true,
38350             category: ts.Diagnostics.Command_line_Options,
38351             description: ts.Diagnostics.Show_all_compiler_options,
38352             defaultValueDescription: "false",
38353         },
38354         {
38355             name: "version",
38356             shortName: "v",
38357             type: "boolean",
38358             showInSimplifiedHelpView: true,
38359             category: ts.Diagnostics.Command_line_Options,
38360             description: ts.Diagnostics.Print_the_compiler_s_version,
38361             defaultValueDescription: "false",
38362         },
38363         {
38364             name: "init",
38365             type: "boolean",
38366             showInSimplifiedHelpView: true,
38367             category: ts.Diagnostics.Command_line_Options,
38368             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
38369             defaultValueDescription: "false",
38370         },
38371         {
38372             name: "project",
38373             shortName: "p",
38374             type: "string",
38375             isFilePath: true,
38376             showInSimplifiedHelpView: true,
38377             category: ts.Diagnostics.Command_line_Options,
38378             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
38379             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
38380         },
38381         {
38382             name: "build",
38383             type: "boolean",
38384             shortName: "b",
38385             showInSimplifiedHelpView: true,
38386             category: ts.Diagnostics.Command_line_Options,
38387             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date,
38388             defaultValueDescription: "false",
38389         },
38390         {
38391             name: "showConfig",
38392             type: "boolean",
38393             showInSimplifiedHelpView: true,
38394             category: ts.Diagnostics.Command_line_Options,
38395             isCommandLineOnly: true,
38396             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building,
38397             defaultValueDescription: "false",
38398         },
38399         {
38400             name: "listFilesOnly",
38401             type: "boolean",
38402             category: ts.Diagnostics.Command_line_Options,
38403             affectsSemanticDiagnostics: true,
38404             affectsEmit: true,
38405             isCommandLineOnly: true,
38406             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing,
38407             defaultValueDescription: "false",
38408         },
38409         // Basic
38410         ts.targetOptionDeclaration,
38411         {
38412             name: "module",
38413             shortName: "m",
38414             type: new ts.Map(ts.getEntries({
38415                 none: ts.ModuleKind.None,
38416                 commonjs: ts.ModuleKind.CommonJS,
38417                 amd: ts.ModuleKind.AMD,
38418                 system: ts.ModuleKind.System,
38419                 umd: ts.ModuleKind.UMD,
38420                 es6: ts.ModuleKind.ES2015,
38421                 es2015: ts.ModuleKind.ES2015,
38422                 es2020: ts.ModuleKind.ES2020,
38423                 es2022: ts.ModuleKind.ES2022,
38424                 esnext: ts.ModuleKind.ESNext,
38425                 node12: ts.ModuleKind.Node12,
38426                 nodenext: ts.ModuleKind.NodeNext,
38427             })),
38428             affectsModuleResolution: true,
38429             affectsEmit: true,
38430             paramType: ts.Diagnostics.KIND,
38431             showInSimplifiedHelpView: true,
38432             category: ts.Diagnostics.Modules,
38433             description: ts.Diagnostics.Specify_what_module_code_is_generated,
38434         },
38435         {
38436             name: "lib",
38437             type: "list",
38438             element: {
38439                 name: "lib",
38440                 type: ts.libMap
38441             },
38442             affectsProgramStructure: true,
38443             showInSimplifiedHelpView: true,
38444             category: ts.Diagnostics.Language_and_Environment,
38445             description: ts.Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment,
38446             transpileOptionValue: undefined
38447         },
38448         {
38449             name: "allowJs",
38450             type: "boolean",
38451             affectsModuleResolution: true,
38452             showInSimplifiedHelpView: true,
38453             category: ts.Diagnostics.JavaScript_Support,
38454             description: ts.Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files,
38455             defaultValueDescription: "false"
38456         },
38457         {
38458             name: "checkJs",
38459             type: "boolean",
38460             showInSimplifiedHelpView: true,
38461             category: ts.Diagnostics.JavaScript_Support,
38462             description: ts.Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files,
38463             defaultValueDescription: "false"
38464         },
38465         {
38466             name: "jsx",
38467             type: jsxOptionMap,
38468             affectsSourceFile: true,
38469             affectsEmit: true,
38470             affectsModuleResolution: true,
38471             paramType: ts.Diagnostics.KIND,
38472             showInSimplifiedHelpView: true,
38473             category: ts.Diagnostics.Language_and_Environment,
38474             description: ts.Diagnostics.Specify_what_JSX_code_is_generated,
38475             defaultValueDescription: "undefined"
38476         },
38477         {
38478             name: "declaration",
38479             shortName: "d",
38480             type: "boolean",
38481             affectsEmit: true,
38482             showInSimplifiedHelpView: true,
38483             category: ts.Diagnostics.Emit,
38484             transpileOptionValue: undefined,
38485             description: ts.Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project,
38486             defaultValueDescription: ts.Diagnostics.false_unless_composite_is_set,
38487         },
38488         {
38489             name: "declarationMap",
38490             type: "boolean",
38491             affectsEmit: true,
38492             showInSimplifiedHelpView: true,
38493             category: ts.Diagnostics.Emit,
38494             transpileOptionValue: undefined,
38495             defaultValueDescription: "false",
38496             description: ts.Diagnostics.Create_sourcemaps_for_d_ts_files
38497         },
38498         {
38499             name: "emitDeclarationOnly",
38500             type: "boolean",
38501             affectsEmit: true,
38502             showInSimplifiedHelpView: true,
38503             category: ts.Diagnostics.Emit,
38504             description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files,
38505             transpileOptionValue: undefined,
38506             defaultValueDescription: "false",
38507         },
38508         {
38509             name: "sourceMap",
38510             type: "boolean",
38511             affectsEmit: true,
38512             showInSimplifiedHelpView: true,
38513             category: ts.Diagnostics.Emit,
38514             defaultValueDescription: "false",
38515             description: ts.Diagnostics.Create_source_map_files_for_emitted_JavaScript_files,
38516         },
38517         {
38518             name: "outFile",
38519             type: "string",
38520             affectsEmit: true,
38521             isFilePath: true,
38522             paramType: ts.Diagnostics.FILE,
38523             showInSimplifiedHelpView: true,
38524             category: ts.Diagnostics.Emit,
38525             description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output,
38526             transpileOptionValue: undefined,
38527         },
38528         {
38529             name: "outDir",
38530             type: "string",
38531             affectsEmit: true,
38532             isFilePath: true,
38533             paramType: ts.Diagnostics.DIRECTORY,
38534             showInSimplifiedHelpView: true,
38535             category: ts.Diagnostics.Emit,
38536             description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files,
38537         },
38538         {
38539             name: "rootDir",
38540             type: "string",
38541             affectsEmit: true,
38542             isFilePath: true,
38543             paramType: ts.Diagnostics.LOCATION,
38544             category: ts.Diagnostics.Modules,
38545             description: ts.Diagnostics.Specify_the_root_folder_within_your_source_files,
38546             defaultValueDescription: ts.Diagnostics.Computed_from_the_list_of_input_files
38547         },
38548         {
38549             name: "composite",
38550             type: "boolean",
38551             affectsEmit: true,
38552             isTSConfigOnly: true,
38553             category: ts.Diagnostics.Projects,
38554             transpileOptionValue: undefined,
38555             defaultValueDescription: "false",
38556             description: ts.Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references,
38557         },
38558         {
38559             name: "tsBuildInfoFile",
38560             type: "string",
38561             affectsEmit: true,
38562             isFilePath: true,
38563             paramType: ts.Diagnostics.FILE,
38564             category: ts.Diagnostics.Projects,
38565             transpileOptionValue: undefined,
38566             defaultValueDescription: ".tsbuildinfo",
38567             description: ts.Diagnostics.Specify_the_folder_for_tsbuildinfo_incremental_compilation_files,
38568         },
38569         {
38570             name: "removeComments",
38571             type: "boolean",
38572             affectsEmit: true,
38573             showInSimplifiedHelpView: true,
38574             category: ts.Diagnostics.Emit,
38575             defaultValueDescription: "false",
38576             description: ts.Diagnostics.Disable_emitting_comments,
38577         },
38578         {
38579             name: "noEmit",
38580             type: "boolean",
38581             showInSimplifiedHelpView: true,
38582             category: ts.Diagnostics.Emit,
38583             description: ts.Diagnostics.Disable_emitting_files_from_a_compilation,
38584             transpileOptionValue: undefined,
38585             defaultValueDescription: "false"
38586         },
38587         {
38588             name: "importHelpers",
38589             type: "boolean",
38590             affectsEmit: true,
38591             category: ts.Diagnostics.Emit,
38592             description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file,
38593             defaultValueDescription: "false"
38594         },
38595         {
38596             name: "importsNotUsedAsValues",
38597             type: new ts.Map(ts.getEntries({
38598                 remove: 0 /* Remove */,
38599                 preserve: 1 /* Preserve */,
38600                 error: 2 /* Error */,
38601             })),
38602             affectsEmit: true,
38603             affectsSemanticDiagnostics: true,
38604             category: ts.Diagnostics.Emit,
38605             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
38606         },
38607         {
38608             name: "downlevelIteration",
38609             type: "boolean",
38610             affectsEmit: true,
38611             category: ts.Diagnostics.Emit,
38612             description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration,
38613             defaultValueDescription: "false"
38614         },
38615         {
38616             name: "isolatedModules",
38617             type: "boolean",
38618             category: ts.Diagnostics.Interop_Constraints,
38619             description: ts.Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports,
38620             transpileOptionValue: true,
38621             defaultValueDescription: "false"
38622         },
38623         // Strict Type Checks
38624         {
38625             name: "strict",
38626             type: "boolean",
38627             // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here
38628             // The value of each strictFlag depends on own strictFlag value or this and never accessed directly.
38629             showInSimplifiedHelpView: true,
38630             category: ts.Diagnostics.Type_Checking,
38631             description: ts.Diagnostics.Enable_all_strict_type_checking_options,
38632             defaultValueDescription: "false"
38633         },
38634         {
38635             name: "noImplicitAny",
38636             type: "boolean",
38637             affectsSemanticDiagnostics: true,
38638             strictFlag: true,
38639             category: ts.Diagnostics.Type_Checking,
38640             description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type,
38641             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38642         },
38643         {
38644             name: "strictNullChecks",
38645             type: "boolean",
38646             affectsSemanticDiagnostics: true,
38647             strictFlag: true,
38648             category: ts.Diagnostics.Type_Checking,
38649             description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined,
38650             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38651         },
38652         {
38653             name: "strictFunctionTypes",
38654             type: "boolean",
38655             strictFlag: true,
38656             category: ts.Diagnostics.Type_Checking,
38657             description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible,
38658             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38659         },
38660         {
38661             name: "strictBindCallApply",
38662             type: "boolean",
38663             strictFlag: true,
38664             category: ts.Diagnostics.Type_Checking,
38665             description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function,
38666             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38667         },
38668         {
38669             name: "strictPropertyInitialization",
38670             type: "boolean",
38671             affectsSemanticDiagnostics: true,
38672             strictFlag: true,
38673             category: ts.Diagnostics.Type_Checking,
38674             description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor,
38675             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38676         },
38677         {
38678             name: "noImplicitThis",
38679             type: "boolean",
38680             affectsSemanticDiagnostics: true,
38681             strictFlag: true,
38682             category: ts.Diagnostics.Type_Checking,
38683             description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any,
38684             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38685         },
38686         {
38687             name: "useUnknownInCatchVariables",
38688             type: "boolean",
38689             affectsSemanticDiagnostics: true,
38690             strictFlag: true,
38691             category: ts.Diagnostics.Type_Checking,
38692             description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any,
38693             defaultValueDescription: "false",
38694         },
38695         {
38696             name: "alwaysStrict",
38697             type: "boolean",
38698             affectsSourceFile: true,
38699             strictFlag: true,
38700             category: ts.Diagnostics.Type_Checking,
38701             description: ts.Diagnostics.Ensure_use_strict_is_always_emitted,
38702             defaultValueDescription: ts.Diagnostics.false_unless_strict_is_set
38703         },
38704         // Additional Checks
38705         {
38706             name: "noUnusedLocals",
38707             type: "boolean",
38708             affectsSemanticDiagnostics: true,
38709             category: ts.Diagnostics.Type_Checking,
38710             description: ts.Diagnostics.Enable_error_reporting_when_a_local_variables_aren_t_read,
38711             defaultValueDescription: "false"
38712         },
38713         {
38714             name: "noUnusedParameters",
38715             type: "boolean",
38716             affectsSemanticDiagnostics: true,
38717             category: ts.Diagnostics.Type_Checking,
38718             description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read,
38719             defaultValueDescription: "false"
38720         },
38721         {
38722             name: "exactOptionalPropertyTypes",
38723             type: "boolean",
38724             affectsSemanticDiagnostics: true,
38725             category: ts.Diagnostics.Type_Checking,
38726             description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined,
38727             defaultValueDescription: "false",
38728         },
38729         {
38730             name: "noImplicitReturns",
38731             type: "boolean",
38732             affectsSemanticDiagnostics: true,
38733             category: ts.Diagnostics.Type_Checking,
38734             description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function,
38735             defaultValueDescription: "false"
38736         },
38737         {
38738             name: "noFallthroughCasesInSwitch",
38739             type: "boolean",
38740             affectsBindDiagnostics: true,
38741             affectsSemanticDiagnostics: true,
38742             category: ts.Diagnostics.Type_Checking,
38743             description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements,
38744             defaultValueDescription: "false",
38745         },
38746         {
38747             name: "noUncheckedIndexedAccess",
38748             type: "boolean",
38749             affectsSemanticDiagnostics: true,
38750             category: ts.Diagnostics.Type_Checking,
38751             description: ts.Diagnostics.Include_undefined_in_index_signature_results,
38752             defaultValueDescription: "false",
38753         },
38754         {
38755             name: "noImplicitOverride",
38756             type: "boolean",
38757             affectsSemanticDiagnostics: true,
38758             category: ts.Diagnostics.Type_Checking,
38759             description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier,
38760             defaultValueDescription: "false",
38761         },
38762         {
38763             name: "noPropertyAccessFromIndexSignature",
38764             type: "boolean",
38765             showInSimplifiedHelpView: false,
38766             category: ts.Diagnostics.Type_Checking,
38767             description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type,
38768             defaultValueDescription: "false"
38769         },
38770         // Module Resolution
38771         {
38772             name: "moduleResolution",
38773             type: new ts.Map(ts.getEntries({
38774                 node: ts.ModuleResolutionKind.NodeJs,
38775                 classic: ts.ModuleResolutionKind.Classic,
38776                 node12: ts.ModuleResolutionKind.Node12,
38777                 nodenext: ts.ModuleResolutionKind.NodeNext,
38778             })),
38779             affectsModuleResolution: true,
38780             paramType: ts.Diagnostics.STRATEGY,
38781             category: ts.Diagnostics.Modules,
38782             description: ts.Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier,
38783             defaultValueDescription: ts.Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node
38784         },
38785         {
38786             name: "baseUrl",
38787             type: "string",
38788             affectsModuleResolution: true,
38789             isFilePath: true,
38790             category: ts.Diagnostics.Modules,
38791             description: ts.Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names
38792         },
38793         {
38794             // this option can only be specified in tsconfig.json
38795             // use type = object to copy the value as-is
38796             name: "paths",
38797             type: "object",
38798             affectsModuleResolution: true,
38799             isTSConfigOnly: true,
38800             category: ts.Diagnostics.Modules,
38801             description: ts.Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations,
38802             transpileOptionValue: undefined
38803         },
38804         {
38805             // this option can only be specified in tsconfig.json
38806             // use type = object to copy the value as-is
38807             name: "rootDirs",
38808             type: "list",
38809             isTSConfigOnly: true,
38810             element: {
38811                 name: "rootDirs",
38812                 type: "string",
38813                 isFilePath: true
38814             },
38815             affectsModuleResolution: true,
38816             category: ts.Diagnostics.Modules,
38817             description: ts.Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules,
38818             transpileOptionValue: undefined,
38819             defaultValueDescription: ts.Diagnostics.Computed_from_the_list_of_input_files
38820         },
38821         {
38822             name: "typeRoots",
38823             type: "list",
38824             element: {
38825                 name: "typeRoots",
38826                 type: "string",
38827                 isFilePath: true
38828             },
38829             affectsModuleResolution: true,
38830             category: ts.Diagnostics.Modules,
38831             description: ts.Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types
38832         },
38833         {
38834             name: "types",
38835             type: "list",
38836             element: {
38837                 name: "types",
38838                 type: "string"
38839             },
38840             affectsProgramStructure: true,
38841             showInSimplifiedHelpView: true,
38842             category: ts.Diagnostics.Modules,
38843             description: ts.Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file,
38844             transpileOptionValue: undefined
38845         },
38846         {
38847             name: "allowSyntheticDefaultImports",
38848             type: "boolean",
38849             affectsSemanticDiagnostics: true,
38850             category: ts.Diagnostics.Interop_Constraints,
38851             description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export,
38852             defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop
38853         },
38854         {
38855             name: "esModuleInterop",
38856             type: "boolean",
38857             affectsSemanticDiagnostics: true,
38858             affectsEmit: true,
38859             showInSimplifiedHelpView: true,
38860             category: ts.Diagnostics.Interop_Constraints,
38861             description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility,
38862             defaultValueDescription: "false"
38863         },
38864         {
38865             name: "preserveSymlinks",
38866             type: "boolean",
38867             category: ts.Diagnostics.Interop_Constraints,
38868             description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node,
38869             defaultValueDescription: "false",
38870         },
38871         {
38872             name: "allowUmdGlobalAccess",
38873             type: "boolean",
38874             affectsSemanticDiagnostics: true,
38875             category: ts.Diagnostics.Modules,
38876             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
38877             defaultValueDescription: "false"
38878         },
38879         // Source Maps
38880         {
38881             name: "sourceRoot",
38882             type: "string",
38883             affectsEmit: true,
38884             paramType: ts.Diagnostics.LOCATION,
38885             category: ts.Diagnostics.Emit,
38886             description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code,
38887         },
38888         {
38889             name: "mapRoot",
38890             type: "string",
38891             affectsEmit: true,
38892             paramType: ts.Diagnostics.LOCATION,
38893             category: ts.Diagnostics.Emit,
38894             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
38895         },
38896         {
38897             name: "inlineSourceMap",
38898             type: "boolean",
38899             affectsEmit: true,
38900             category: ts.Diagnostics.Emit,
38901             description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript,
38902             defaultValueDescription: "false"
38903         },
38904         {
38905             name: "inlineSources",
38906             type: "boolean",
38907             affectsEmit: true,
38908             category: ts.Diagnostics.Emit,
38909             description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript,
38910             defaultValueDescription: "false"
38911         },
38912         // Experimental
38913         {
38914             name: "experimentalDecorators",
38915             type: "boolean",
38916             affectsSemanticDiagnostics: true,
38917             category: ts.Diagnostics.Language_and_Environment,
38918             description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators,
38919             defaultValueDescription: "false",
38920         },
38921         {
38922             name: "emitDecoratorMetadata",
38923             type: "boolean",
38924             affectsSemanticDiagnostics: true,
38925             affectsEmit: true,
38926             category: ts.Diagnostics.Language_and_Environment,
38927             description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files,
38928             defaultValueDescription: "false",
38929         },
38930         // Advanced
38931         {
38932             name: "jsxFactory",
38933             type: "string",
38934             category: ts.Diagnostics.Language_and_Environment,
38935             description: ts.Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h,
38936             defaultValueDescription: "`React.createElement`"
38937         },
38938         {
38939             name: "jsxFragmentFactory",
38940             type: "string",
38941             category: ts.Diagnostics.Language_and_Environment,
38942             description: ts.Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment
38943         },
38944         {
38945             name: "jsxImportSource",
38946             type: "string",
38947             affectsSemanticDiagnostics: true,
38948             affectsEmit: true,
38949             affectsModuleResolution: true,
38950             category: ts.Diagnostics.Language_and_Environment,
38951             description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk,
38952             defaultValueDescription: "react"
38953         },
38954         {
38955             name: "resolveJsonModule",
38956             type: "boolean",
38957             affectsModuleResolution: true,
38958             category: ts.Diagnostics.Modules,
38959             description: ts.Diagnostics.Enable_importing_json_files,
38960             defaultValueDescription: "false"
38961         },
38962         {
38963             name: "out",
38964             type: "string",
38965             affectsEmit: true,
38966             isFilePath: false,
38967             // for correct behaviour, please use outFile
38968             category: ts.Diagnostics.Backwards_Compatibility,
38969             paramType: ts.Diagnostics.FILE,
38970             transpileOptionValue: undefined,
38971             description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead,
38972         },
38973         {
38974             name: "reactNamespace",
38975             type: "string",
38976             affectsEmit: true,
38977             category: ts.Diagnostics.Language_and_Environment,
38978             description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit,
38979             defaultValueDescription: "`React`",
38980         },
38981         {
38982             name: "skipDefaultLibCheck",
38983             type: "boolean",
38984             category: ts.Diagnostics.Completeness,
38985             description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript,
38986             defaultValueDescription: "false",
38987         },
38988         {
38989             name: "charset",
38990             type: "string",
38991             category: ts.Diagnostics.Backwards_Compatibility,
38992             description: ts.Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files,
38993             defaultValueDescription: "utf8"
38994         },
38995         {
38996             name: "emitBOM",
38997             type: "boolean",
38998             affectsEmit: true,
38999             category: ts.Diagnostics.Emit,
39000             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files,
39001             defaultValueDescription: "false"
39002         },
39003         {
39004             name: "newLine",
39005             type: new ts.Map(ts.getEntries({
39006                 crlf: 0 /* CarriageReturnLineFeed */,
39007                 lf: 1 /* LineFeed */
39008             })),
39009             affectsEmit: true,
39010             paramType: ts.Diagnostics.NEWLINE,
39011             category: ts.Diagnostics.Emit,
39012             description: ts.Diagnostics.Set_the_newline_character_for_emitting_files,
39013             defaultValueDescription: ts.Diagnostics.Platform_specific
39014         },
39015         {
39016             name: "noErrorTruncation",
39017             type: "boolean",
39018             affectsSemanticDiagnostics: true,
39019             category: ts.Diagnostics.Output_Formatting,
39020             description: ts.Diagnostics.Disable_truncating_types_in_error_messages,
39021             defaultValueDescription: "false"
39022         },
39023         {
39024             name: "noLib",
39025             type: "boolean",
39026             category: ts.Diagnostics.Language_and_Environment,
39027             affectsProgramStructure: true,
39028             description: ts.Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts,
39029             // We are not returning a sourceFile for lib file when asked by the program,
39030             // so pass --noLib to avoid reporting a file not found error.
39031             transpileOptionValue: true,
39032             defaultValueDescription: "false"
39033         },
39034         {
39035             name: "noResolve",
39036             type: "boolean",
39037             affectsModuleResolution: true,
39038             category: ts.Diagnostics.Modules,
39039             description: ts.Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project,
39040             // We are not doing a full typecheck, we are not resolving the whole context,
39041             // so pass --noResolve to avoid reporting missing file errors.
39042             transpileOptionValue: true,
39043             defaultValueDescription: "false"
39044         },
39045         {
39046             name: "stripInternal",
39047             type: "boolean",
39048             affectsEmit: true,
39049             category: ts.Diagnostics.Emit,
39050             description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments,
39051             defaultValueDescription: "false",
39052         },
39053         {
39054             name: "disableSizeLimit",
39055             type: "boolean",
39056             affectsProgramStructure: true,
39057             category: ts.Diagnostics.Editor_Support,
39058             description: ts.Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server,
39059             defaultValueDescription: "false"
39060         },
39061         {
39062             name: "disableSourceOfProjectReferenceRedirect",
39063             type: "boolean",
39064             isTSConfigOnly: true,
39065             category: ts.Diagnostics.Projects,
39066             description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects,
39067             defaultValueDescription: "false",
39068         },
39069         {
39070             name: "disableSolutionSearching",
39071             type: "boolean",
39072             isTSConfigOnly: true,
39073             category: ts.Diagnostics.Projects,
39074             description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing,
39075             defaultValueDescription: "false",
39076         },
39077         {
39078             name: "disableReferencedProjectLoad",
39079             type: "boolean",
39080             isTSConfigOnly: true,
39081             category: ts.Diagnostics.Projects,
39082             description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript,
39083             defaultValueDescription: "false",
39084         },
39085         {
39086             name: "noImplicitUseStrict",
39087             type: "boolean",
39088             affectsSemanticDiagnostics: true,
39089             category: ts.Diagnostics.Backwards_Compatibility,
39090             description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files,
39091             defaultValueDescription: "false"
39092         },
39093         {
39094             name: "noEmitHelpers",
39095             type: "boolean",
39096             affectsEmit: true,
39097             category: ts.Diagnostics.Emit,
39098             description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output,
39099             defaultValueDescription: "false"
39100         },
39101         {
39102             name: "noEmitOnError",
39103             type: "boolean",
39104             affectsEmit: true,
39105             category: ts.Diagnostics.Emit,
39106             transpileOptionValue: undefined,
39107             description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported,
39108             defaultValueDescription: "false"
39109         },
39110         {
39111             name: "preserveConstEnums",
39112             type: "boolean",
39113             affectsEmit: true,
39114             category: ts.Diagnostics.Emit,
39115             description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code,
39116             defaultValueDescription: "false",
39117         },
39118         {
39119             name: "declarationDir",
39120             type: "string",
39121             affectsEmit: true,
39122             isFilePath: true,
39123             paramType: ts.Diagnostics.DIRECTORY,
39124             category: ts.Diagnostics.Emit,
39125             transpileOptionValue: undefined,
39126             description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files,
39127         },
39128         {
39129             name: "skipLibCheck",
39130             type: "boolean",
39131             category: ts.Diagnostics.Completeness,
39132             description: ts.Diagnostics.Skip_type_checking_all_d_ts_files,
39133             defaultValueDescription: "false"
39134         },
39135         {
39136             name: "allowUnusedLabels",
39137             type: "boolean",
39138             affectsBindDiagnostics: true,
39139             affectsSemanticDiagnostics: true,
39140             category: ts.Diagnostics.Type_Checking,
39141             description: ts.Diagnostics.Disable_error_reporting_for_unused_labels,
39142             defaultValueDescription: "undefined"
39143         },
39144         {
39145             name: "allowUnreachableCode",
39146             type: "boolean",
39147             affectsBindDiagnostics: true,
39148             affectsSemanticDiagnostics: true,
39149             category: ts.Diagnostics.Type_Checking,
39150             description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code,
39151             defaultValueDescription: "undefined"
39152         },
39153         {
39154             name: "suppressExcessPropertyErrors",
39155             type: "boolean",
39156             affectsSemanticDiagnostics: true,
39157             category: ts.Diagnostics.Backwards_Compatibility,
39158             description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals,
39159             defaultValueDescription: "false"
39160         },
39161         {
39162             name: "suppressImplicitAnyIndexErrors",
39163             type: "boolean",
39164             affectsSemanticDiagnostics: true,
39165             category: ts.Diagnostics.Backwards_Compatibility,
39166             description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures,
39167             defaultValueDescription: "false"
39168         },
39169         {
39170             name: "forceConsistentCasingInFileNames",
39171             type: "boolean",
39172             affectsModuleResolution: true,
39173             category: ts.Diagnostics.Interop_Constraints,
39174             description: ts.Diagnostics.Ensure_that_casing_is_correct_in_imports,
39175             defaultValueDescription: "false"
39176         },
39177         {
39178             name: "maxNodeModuleJsDepth",
39179             type: "number",
39180             affectsModuleResolution: true,
39181             category: ts.Diagnostics.JavaScript_Support,
39182             description: ts.Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs,
39183             defaultValueDescription: "0"
39184         },
39185         {
39186             name: "noStrictGenericChecks",
39187             type: "boolean",
39188             affectsSemanticDiagnostics: true,
39189             category: ts.Diagnostics.Backwards_Compatibility,
39190             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
39191             defaultValueDescription: "false"
39192         },
39193         {
39194             name: "useDefineForClassFields",
39195             type: "boolean",
39196             affectsSemanticDiagnostics: true,
39197             affectsEmit: true,
39198             category: ts.Diagnostics.Language_and_Environment,
39199             description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields,
39200             defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext
39201         },
39202         {
39203             name: "preserveValueImports",
39204             type: "boolean",
39205             affectsEmit: true,
39206             category: ts.Diagnostics.Emit,
39207             description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed,
39208             defaultValueDescription: "false",
39209         },
39210         {
39211             name: "keyofStringsOnly",
39212             type: "boolean",
39213             category: ts.Diagnostics.Backwards_Compatibility,
39214             description: ts.Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option,
39215             defaultValueDescription: "false"
39216         },
39217         {
39218             // A list of plugins to load in the language service
39219             name: "plugins",
39220             type: "list",
39221             isTSConfigOnly: true,
39222             element: {
39223                 name: "plugin",
39224                 type: "object"
39225             },
39226             description: ts.Diagnostics.List_of_language_service_plugins,
39227             category: ts.Diagnostics.Editor_Support,
39228         },
39229     ];
39230     /* @internal */
39231     ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), commandOptionsWithoutBuild, true);
39232     /* @internal */
39233     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
39234     /* @internal */
39235     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
39236     /* @internal */
39237     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
39238     /* @internal */
39239     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
39240         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
39241     });
39242     /* @internal */
39243     ts.optionsAffectingProgramStructure = ts.optionDeclarations.filter(function (option) { return !!option.affectsProgramStructure; });
39244     /* @internal */
39245     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
39246         return ts.hasProperty(option, "transpileOptionValue");
39247     });
39248     // Build related options
39249     /* @internal */
39250     ts.optionsForBuild = [
39251         {
39252             name: "verbose",
39253             shortName: "v",
39254             category: ts.Diagnostics.Command_line_Options,
39255             description: ts.Diagnostics.Enable_verbose_logging,
39256             type: "boolean",
39257             defaultValueDescription: "false",
39258         },
39259         {
39260             name: "dry",
39261             shortName: "d",
39262             category: ts.Diagnostics.Command_line_Options,
39263             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
39264             type: "boolean",
39265             defaultValueDescription: "false",
39266         },
39267         {
39268             name: "force",
39269             shortName: "f",
39270             category: ts.Diagnostics.Command_line_Options,
39271             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
39272             type: "boolean",
39273             defaultValueDescription: "false",
39274         },
39275         {
39276             name: "clean",
39277             category: ts.Diagnostics.Command_line_Options,
39278             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
39279             type: "boolean",
39280             defaultValueDescription: "false",
39281         }
39282     ];
39283     /* @internal */
39284     ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), ts.optionsForBuild, true);
39285     /* @internal */
39286     ts.typeAcquisitionDeclarations = [
39287         {
39288             /* @deprecated typingOptions.enableAutoDiscovery
39289              * Use typeAcquisition.enable instead.
39290              */
39291             name: "enableAutoDiscovery",
39292             type: "boolean",
39293             defaultValueDescription: "false",
39294         },
39295         {
39296             name: "enable",
39297             type: "boolean",
39298             defaultValueDescription: "false",
39299         },
39300         {
39301             name: "include",
39302             type: "list",
39303             element: {
39304                 name: "include",
39305                 type: "string"
39306             }
39307         },
39308         {
39309             name: "exclude",
39310             type: "list",
39311             element: {
39312                 name: "exclude",
39313                 type: "string"
39314             }
39315         },
39316         {
39317             name: "disableFilenameBasedTypeAcquisition",
39318             type: "boolean",
39319             defaultValueDescription: "false",
39320         },
39321     ];
39322     /*@internal*/
39323     function createOptionNameMap(optionDeclarations) {
39324         var optionsNameMap = new ts.Map();
39325         var shortOptionNames = new ts.Map();
39326         ts.forEach(optionDeclarations, function (option) {
39327             optionsNameMap.set(option.name.toLowerCase(), option);
39328             if (option.shortName) {
39329                 shortOptionNames.set(option.shortName, option.name);
39330             }
39331         });
39332         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
39333     }
39334     ts.createOptionNameMap = createOptionNameMap;
39335     var optionsNameMapCache;
39336     /* @internal */
39337     function getOptionsNameMap() {
39338         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
39339     }
39340     ts.getOptionsNameMap = getOptionsNameMap;
39341     var compilerOptionsAlternateMode = {
39342         diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build,
39343         getOptionsNameMap: getBuildOptionsNameMap
39344     };
39345     /* @internal */
39346     ts.defaultInitCompilerOptions = {
39347         module: ts.ModuleKind.CommonJS,
39348         target: 3 /* ES2016 */,
39349         strict: true,
39350         esModuleInterop: true,
39351         forceConsistentCasingInFileNames: true,
39352         skipLibCheck: true
39353     };
39354     /* @internal */
39355     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
39356         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
39357         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
39358             return {
39359                 enable: typeAcquisition.enableAutoDiscovery,
39360                 include: typeAcquisition.include || [],
39361                 exclude: typeAcquisition.exclude || []
39362             };
39363         }
39364         return typeAcquisition;
39365     }
39366     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
39367     /* @internal */
39368     function createCompilerDiagnosticForInvalidCustomType(opt) {
39369         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
39370     }
39371     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
39372     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
39373         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'".concat(key, "'"); }).join(", ");
39374         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--".concat(opt.name), namesOfType);
39375     }
39376     /* @internal */
39377     function parseCustomTypeOption(opt, value, errors) {
39378         return convertJsonOptionOfCustomType(opt, ts.trimString(value || ""), errors);
39379     }
39380     ts.parseCustomTypeOption = parseCustomTypeOption;
39381     /* @internal */
39382     function parseListTypeOption(opt, value, errors) {
39383         if (value === void 0) { value = ""; }
39384         value = ts.trimString(value);
39385         if (ts.startsWith(value, "-")) {
39386             return undefined;
39387         }
39388         if (value === "") {
39389             return [];
39390         }
39391         var values = value.split(",");
39392         switch (opt.element.type) {
39393             case "number":
39394                 return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, parseInt(v), errors); });
39395             case "string":
39396                 return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, v || "", errors); });
39397             default:
39398                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
39399         }
39400     }
39401     ts.parseListTypeOption = parseListTypeOption;
39402     function getOptionName(option) {
39403         return option.name;
39404     }
39405     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
39406         var _a;
39407         if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) {
39408             return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption);
39409         }
39410         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
39411         return possibleOption ?
39412             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
39413             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
39414     }
39415     /*@internal*/
39416     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
39417         var options = {};
39418         var watchOptions;
39419         var fileNames = [];
39420         var errors = [];
39421         parseStrings(commandLine);
39422         return {
39423             options: options,
39424             watchOptions: watchOptions,
39425             fileNames: fileNames,
39426             errors: errors
39427         };
39428         function parseStrings(args) {
39429             var i = 0;
39430             while (i < args.length) {
39431                 var s = args[i];
39432                 i++;
39433                 if (s.charCodeAt(0) === 64 /* at */) {
39434                     parseResponseFile(s.slice(1));
39435                 }
39436                 else if (s.charCodeAt(0) === 45 /* minus */) {
39437                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
39438                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
39439                     if (opt) {
39440                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
39441                     }
39442                     else {
39443                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
39444                         if (watchOpt) {
39445                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
39446                         }
39447                         else {
39448                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
39449                         }
39450                     }
39451                 }
39452                 else {
39453                     fileNames.push(s);
39454                 }
39455             }
39456         }
39457         function parseResponseFile(fileName) {
39458             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
39459             if (!ts.isString(text)) {
39460                 errors.push(text);
39461                 return;
39462             }
39463             var args = [];
39464             var pos = 0;
39465             while (true) {
39466                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
39467                     pos++;
39468                 if (pos >= text.length)
39469                     break;
39470                 var start = pos;
39471                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
39472                     pos++;
39473                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
39474                         pos++;
39475                     if (pos < text.length) {
39476                         args.push(text.substring(start + 1, pos));
39477                         pos++;
39478                     }
39479                     else {
39480                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
39481                     }
39482                 }
39483                 else {
39484                     while (text.charCodeAt(pos) > 32 /* space */)
39485                         pos++;
39486                     args.push(text.substring(start, pos));
39487                 }
39488             }
39489             parseStrings(args);
39490         }
39491     }
39492     ts.parseCommandLineWorker = parseCommandLineWorker;
39493     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
39494         if (opt.isTSConfigOnly) {
39495             var optValue = args[i];
39496             if (optValue === "null") {
39497                 options[opt.name] = undefined;
39498                 i++;
39499             }
39500             else if (opt.type === "boolean") {
39501                 if (optValue === "false") {
39502                     options[opt.name] = validateJsonOptionValue(opt, /*value*/ false, errors);
39503                     i++;
39504                 }
39505                 else {
39506                     if (optValue === "true")
39507                         i++;
39508                     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));
39509                 }
39510             }
39511             else {
39512                 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));
39513                 if (optValue && !ts.startsWith(optValue, "-"))
39514                     i++;
39515             }
39516         }
39517         else {
39518             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
39519             if (!args[i] && opt.type !== "boolean") {
39520                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
39521             }
39522             if (args[i] !== "null") {
39523                 switch (opt.type) {
39524                     case "number":
39525                         options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
39526                         i++;
39527                         break;
39528                     case "boolean":
39529                         // boolean flag has optional value true, false, others
39530                         var optValue = args[i];
39531                         options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
39532                         // consume next argument as boolean flag value
39533                         if (optValue === "false" || optValue === "true") {
39534                             i++;
39535                         }
39536                         break;
39537                     case "string":
39538                         options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
39539                         i++;
39540                         break;
39541                     case "list":
39542                         var result = parseListTypeOption(opt, args[i], errors);
39543                         options[opt.name] = result || [];
39544                         if (result) {
39545                             i++;
39546                         }
39547                         break;
39548                     // If not a primitive, the possible types are specified in what is effectively a map of options.
39549                     default:
39550                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
39551                         i++;
39552                         break;
39553                 }
39554             }
39555             else {
39556                 options[opt.name] = undefined;
39557                 i++;
39558             }
39559         }
39560         return i;
39561     }
39562     /*@internal*/
39563     ts.compilerOptionsDidYouMeanDiagnostics = {
39564         alternateMode: compilerOptionsAlternateMode,
39565         getOptionsNameMap: getOptionsNameMap,
39566         optionDeclarations: ts.optionDeclarations,
39567         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
39568         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
39569         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
39570     };
39571     function parseCommandLine(commandLine, readFile) {
39572         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
39573     }
39574     ts.parseCommandLine = parseCommandLine;
39575     /** @internal */
39576     function getOptionFromName(optionName, allowShort) {
39577         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
39578     }
39579     ts.getOptionFromName = getOptionFromName;
39580     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
39581         if (allowShort === void 0) { allowShort = false; }
39582         optionName = optionName.toLowerCase();
39583         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
39584         // Try to translate short option names to their full equivalents.
39585         if (allowShort) {
39586             var short = shortOptionNames.get(optionName);
39587             if (short !== undefined) {
39588                 optionName = short;
39589             }
39590         }
39591         return optionsNameMap.get(optionName);
39592     }
39593     var buildOptionsNameMapCache;
39594     function getBuildOptionsNameMap() {
39595         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
39596     }
39597     var buildOptionsAlternateMode = {
39598         diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build,
39599         getOptionsNameMap: getOptionsNameMap
39600     };
39601     var buildOptionsDidYouMeanDiagnostics = {
39602         alternateMode: buildOptionsAlternateMode,
39603         getOptionsNameMap: getBuildOptionsNameMap,
39604         optionDeclarations: ts.buildOpts,
39605         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
39606         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
39607         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
39608     };
39609     /*@internal*/
39610     function parseBuildCommand(args) {
39611         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
39612         var buildOptions = options;
39613         if (projects.length === 0) {
39614             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
39615             projects.push(".");
39616         }
39617         // Nonsensical combinations
39618         if (buildOptions.clean && buildOptions.force) {
39619             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
39620         }
39621         if (buildOptions.clean && buildOptions.verbose) {
39622             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
39623         }
39624         if (buildOptions.clean && buildOptions.watch) {
39625             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
39626         }
39627         if (buildOptions.watch && buildOptions.dry) {
39628             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
39629         }
39630         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
39631     }
39632     ts.parseBuildCommand = parseBuildCommand;
39633     /* @internal */
39634     function getDiagnosticText(_message) {
39635         var _args = [];
39636         for (var _i = 1; _i < arguments.length; _i++) {
39637             _args[_i - 1] = arguments[_i];
39638         }
39639         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
39640         return diagnostic.messageText;
39641     }
39642     ts.getDiagnosticText = getDiagnosticText;
39643     /**
39644      * Reads the config file, reports errors if any and exits if the config file cannot be found
39645      */
39646     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
39647         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
39648         if (!ts.isString(configFileText)) {
39649             host.onUnRecoverableConfigFileDiagnostic(configFileText);
39650             return undefined;
39651         }
39652         var result = ts.parseJsonText(configFileName, configFileText);
39653         var cwd = host.getCurrentDirectory();
39654         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
39655         result.resolvedPath = result.path;
39656         result.originalFileName = result.fileName;
39657         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
39658         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
39659     }
39660     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
39661     /**
39662      * Read tsconfig.json file
39663      * @param fileName The path to the config file
39664      */
39665     function readConfigFile(fileName, readFile) {
39666         var textOrDiagnostic = tryReadFile(fileName, readFile);
39667         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
39668     }
39669     ts.readConfigFile = readConfigFile;
39670     /**
39671      * Parse the text of the tsconfig.json file
39672      * @param fileName The path to the config file
39673      * @param jsonText The text of the config file
39674      */
39675     function parseConfigFileTextToJson(fileName, jsonText) {
39676         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
39677         return {
39678             config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined),
39679             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
39680         };
39681     }
39682     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
39683     /**
39684      * Read tsconfig.json file
39685      * @param fileName The path to the config file
39686      */
39687     function readJsonConfigFile(fileName, readFile) {
39688         var textOrDiagnostic = tryReadFile(fileName, readFile);
39689         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { fileName: fileName, parseDiagnostics: [textOrDiagnostic] };
39690     }
39691     ts.readJsonConfigFile = readJsonConfigFile;
39692     /*@internal*/
39693     function tryReadFile(fileName, readFile) {
39694         var text;
39695         try {
39696             text = readFile(fileName);
39697         }
39698         catch (e) {
39699             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
39700         }
39701         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
39702     }
39703     ts.tryReadFile = tryReadFile;
39704     function commandLineOptionsToMap(options) {
39705         return ts.arrayToMap(options, getOptionName);
39706     }
39707     var typeAcquisitionDidYouMeanDiagnostics = {
39708         optionDeclarations: ts.typeAcquisitionDeclarations,
39709         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
39710         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
39711     };
39712     var watchOptionsNameMapCache;
39713     function getWatchOptionsNameMap() {
39714         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
39715     }
39716     var watchOptionsDidYouMeanDiagnostics = {
39717         getOptionsNameMap: getWatchOptionsNameMap,
39718         optionDeclarations: ts.optionsForWatch,
39719         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
39720         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
39721         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
39722     };
39723     var commandLineCompilerOptionsMapCache;
39724     function getCommandLineCompilerOptionsMap() {
39725         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
39726     }
39727     var commandLineWatchOptionsMapCache;
39728     function getCommandLineWatchOptionsMap() {
39729         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
39730     }
39731     var commandLineTypeAcquisitionMapCache;
39732     function getCommandLineTypeAcquisitionMap() {
39733         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
39734     }
39735     var _tsconfigRootOptions;
39736     function getTsconfigRootOptionsMap() {
39737         if (_tsconfigRootOptions === undefined) {
39738             _tsconfigRootOptions = {
39739                 name: undefined,
39740                 type: "object",
39741                 elementOptions: commandLineOptionsToMap([
39742                     {
39743                         name: "compilerOptions",
39744                         type: "object",
39745                         elementOptions: getCommandLineCompilerOptionsMap(),
39746                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
39747                     },
39748                     {
39749                         name: "watchOptions",
39750                         type: "object",
39751                         elementOptions: getCommandLineWatchOptionsMap(),
39752                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
39753                     },
39754                     {
39755                         name: "typingOptions",
39756                         type: "object",
39757                         elementOptions: getCommandLineTypeAcquisitionMap(),
39758                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
39759                     },
39760                     {
39761                         name: "typeAcquisition",
39762                         type: "object",
39763                         elementOptions: getCommandLineTypeAcquisitionMap(),
39764                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
39765                     },
39766                     {
39767                         name: "extends",
39768                         type: "string",
39769                         category: ts.Diagnostics.File_Management,
39770                     },
39771                     {
39772                         name: "references",
39773                         type: "list",
39774                         element: {
39775                             name: "references",
39776                             type: "object"
39777                         },
39778                         category: ts.Diagnostics.Projects,
39779                     },
39780                     {
39781                         name: "files",
39782                         type: "list",
39783                         element: {
39784                             name: "files",
39785                             type: "string"
39786                         },
39787                         category: ts.Diagnostics.File_Management,
39788                     },
39789                     {
39790                         name: "include",
39791                         type: "list",
39792                         element: {
39793                             name: "include",
39794                             type: "string"
39795                         },
39796                         category: ts.Diagnostics.File_Management,
39797                         defaultValueDescription: ts.Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk
39798                     },
39799                     {
39800                         name: "exclude",
39801                         type: "list",
39802                         element: {
39803                             name: "exclude",
39804                             type: "string"
39805                         },
39806                         category: ts.Diagnostics.File_Management,
39807                         defaultValueDescription: ts.Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified
39808                     },
39809                     ts.compileOnSaveCommandLineOption
39810                 ])
39811             };
39812         }
39813         return _tsconfigRootOptions;
39814     }
39815     function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) {
39816         var _a;
39817         var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression;
39818         var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined;
39819         if (rootExpression && rootExpression.kind !== 204 /* ObjectLiteralExpression */) {
39820             errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json"));
39821             // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by
39822             // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that
39823             // array is a well-formed configuration object, made into an array element by stray characters.
39824             if (ts.isArrayLiteralExpression(rootExpression)) {
39825                 var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression);
39826                 if (firstObject) {
39827                     return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator);
39828                 }
39829             }
39830             return {};
39831         }
39832         return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator);
39833     }
39834     /**
39835      * Convert the json syntax tree into the json value
39836      */
39837     function convertToObject(sourceFile, errors) {
39838         var _a;
39839         return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
39840     }
39841     ts.convertToObject = convertToObject;
39842     /**
39843      * Convert the json syntax tree into the json value and report errors
39844      * This returns the json value (apart from checking errors) only if returnValue provided is true.
39845      * Otherwise it just checks the errors and returns undefined
39846      */
39847     /*@internal*/
39848     function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
39849         if (!rootExpression) {
39850             return returnValue ? {} : undefined;
39851         }
39852         return convertPropertyValueToJson(rootExpression, knownRootOptions);
39853         function isRootOptionMap(knownOptions) {
39854             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
39855         }
39856         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
39857             var result = returnValue ? {} : undefined;
39858             var _loop_4 = function (element) {
39859                 if (element.kind !== 294 /* PropertyAssignment */) {
39860                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
39861                     return "continue";
39862                 }
39863                 if (element.questionToken) {
39864                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
39865                 }
39866                 if (!isDoubleQuotedString(element.name)) {
39867                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
39868                 }
39869                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
39870                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
39871                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
39872                 if (keyText && extraKeyDiagnostics && !option) {
39873                     if (knownOptions) {
39874                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
39875                     }
39876                     else {
39877                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
39878                     }
39879                 }
39880                 var value = convertPropertyValueToJson(element.initializer, option);
39881                 if (typeof keyText !== "undefined") {
39882                     if (returnValue) {
39883                         result[keyText] = value;
39884                     }
39885                     // Notify key value set, if user asked for it
39886                     if (jsonConversionNotifier &&
39887                         // Current callbacks are only on known parent option or if we are setting values in the root
39888                         (parentOption || isRootOptionMap(knownOptions))) {
39889                         var isValidOptionValue = isCompilerOptionsValue(option, value);
39890                         if (parentOption) {
39891                             if (isValidOptionValue) {
39892                                 // Notify option set in the parent if its a valid option value
39893                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
39894                             }
39895                         }
39896                         else if (isRootOptionMap(knownOptions)) {
39897                             if (isValidOptionValue) {
39898                                 // Notify about the valid root key value being set
39899                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
39900                             }
39901                             else if (!option) {
39902                                 // Notify about the unknown root key value being set
39903                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
39904                             }
39905                         }
39906                     }
39907                 }
39908             };
39909             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
39910                 var element = _a[_i];
39911                 _loop_4(element);
39912             }
39913             return result;
39914         }
39915         function convertArrayLiteralExpressionToJson(elements, elementOption) {
39916             if (!returnValue) {
39917                 elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
39918                 return undefined;
39919             }
39920             // Filter out invalid values
39921             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
39922         }
39923         function convertPropertyValueToJson(valueExpression, option) {
39924             var invalidReported;
39925             switch (valueExpression.kind) {
39926                 case 110 /* TrueKeyword */:
39927                     reportInvalidOptionValue(option && option.type !== "boolean");
39928                     return validateValue(/*value*/ true);
39929                 case 95 /* FalseKeyword */:
39930                     reportInvalidOptionValue(option && option.type !== "boolean");
39931                     return validateValue(/*value*/ false);
39932                 case 104 /* NullKeyword */:
39933                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
39934                     return validateValue(/*value*/ null); // eslint-disable-line no-null/no-null
39935                 case 10 /* StringLiteral */:
39936                     if (!isDoubleQuotedString(valueExpression)) {
39937                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
39938                     }
39939                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
39940                     var text = valueExpression.text;
39941                     if (option && !ts.isString(option.type)) {
39942                         var customOption = option;
39943                         // Validate custom option type
39944                         if (!customOption.type.has(text.toLowerCase())) {
39945                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
39946                             invalidReported = true;
39947                         }
39948                     }
39949                     return validateValue(text);
39950                 case 8 /* NumericLiteral */:
39951                     reportInvalidOptionValue(option && option.type !== "number");
39952                     return validateValue(Number(valueExpression.text));
39953                 case 218 /* PrefixUnaryExpression */:
39954                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
39955                         break; // not valid JSON syntax
39956                     }
39957                     reportInvalidOptionValue(option && option.type !== "number");
39958                     return validateValue(-Number(valueExpression.operand.text));
39959                 case 204 /* ObjectLiteralExpression */:
39960                     reportInvalidOptionValue(option && option.type !== "object");
39961                     var objectLiteralExpression = valueExpression;
39962                     // Currently having element option declaration in the tsconfig with type "object"
39963                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
39964                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
39965                     // that satifies it and need it to modify options set in them (for normalizing file paths)
39966                     // vs what we set in the json
39967                     // If need arises, we can modify this interface and callbacks as needed
39968                     if (option) {
39969                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
39970                         return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName));
39971                     }
39972                     else {
39973                         return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
39974                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined));
39975                     }
39976                 case 203 /* ArrayLiteralExpression */:
39977                     reportInvalidOptionValue(option && option.type !== "list");
39978                     return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element));
39979             }
39980             // Not in expected format
39981             if (option) {
39982                 reportInvalidOptionValue(/*isError*/ true);
39983             }
39984             else {
39985                 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));
39986             }
39987             return undefined;
39988             function validateValue(value) {
39989                 var _a;
39990                 if (!invalidReported) {
39991                     var diagnostic = (_a = option === null || option === void 0 ? void 0 : option.extraValidation) === null || _a === void 0 ? void 0 : _a.call(option, value);
39992                     if (diagnostic) {
39993                         errors.push(ts.createDiagnosticForNodeInSourceFile.apply(void 0, __spreadArray([sourceFile, valueExpression], diagnostic, false)));
39994                         return undefined;
39995                     }
39996                 }
39997                 return value;
39998             }
39999             function reportInvalidOptionValue(isError) {
40000                 if (isError) {
40001                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
40002                     invalidReported = true;
40003                 }
40004             }
40005         }
40006         function isDoubleQuotedString(node) {
40007             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
40008         }
40009     }
40010     ts.convertToObjectWorker = convertToObjectWorker;
40011     function getCompilerOptionValueTypeString(option) {
40012         return option.type === "list" ?
40013             "Array" :
40014             ts.isString(option.type) ? option.type : "string";
40015     }
40016     function isCompilerOptionsValue(option, value) {
40017         if (option) {
40018             if (isNullOrUndefined(value))
40019                 return true; // All options are undefinable/nullable
40020             if (option.type === "list") {
40021                 return ts.isArray(value);
40022             }
40023             var expectedType = ts.isString(option.type) ? option.type : "string";
40024             return typeof value === expectedType;
40025         }
40026         return false;
40027     }
40028     /**
40029      * Generate an uncommented, complete tsconfig for use with "--showConfig"
40030      * @param configParseResult options to be generated into tsconfig.json
40031      * @param configFileName name of the parsed config file - output paths will be generated relative to this
40032      * @param host provides current directory and case sensitivity services
40033      */
40034     /** @internal */
40035     function convertToTSConfig(configParseResult, configFileName, host) {
40036         var _a, _b, _c;
40037         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
40038         var files = ts.map(ts.filter(configParseResult.fileNames, !((_b = (_a = configParseResult.options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs) ? ts.returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
40039         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
40040         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
40041         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 }, (((_c = configParseResult.options.configFile) === null || _c === void 0 ? void 0 : _c.configFileSpecs) ? {
40042             include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
40043             exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
40044         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
40045         return config;
40046     }
40047     ts.convertToTSConfig = convertToTSConfig;
40048     function optionMapToObject(optionMap) {
40049         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
40050             var _a;
40051             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
40052         }, {}));
40053     }
40054     function filterSameAsDefaultInclude(specs) {
40055         if (!ts.length(specs))
40056             return undefined;
40057         if (ts.length(specs) !== 1)
40058             return specs;
40059         if (specs[0] === "**/*")
40060             return undefined;
40061         return specs;
40062     }
40063     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
40064         if (!includeSpecs)
40065             return ts.returnTrue;
40066         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
40067         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
40068         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
40069         if (includeRe) {
40070             if (excludeRe) {
40071                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
40072             }
40073             return function (path) { return !includeRe.test(path); };
40074         }
40075         if (excludeRe) {
40076             return function (path) { return excludeRe.test(path); };
40077         }
40078         return ts.returnTrue;
40079     }
40080     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
40081         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
40082             // this is of a type CommandLineOptionOfPrimitiveType
40083             return undefined;
40084         }
40085         else if (optionDefinition.type === "list") {
40086             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
40087         }
40088         else {
40089             return optionDefinition.type;
40090         }
40091     }
40092     function getNameOfCompilerOptionValue(value, customTypeMap) {
40093         // There is a typeMap associated with this command-line option so use it to map value back to its name
40094         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
40095             if (mapValue === value) {
40096                 return key;
40097             }
40098         });
40099     }
40100     function serializeCompilerOptions(options, pathOptions) {
40101         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
40102     }
40103     function serializeWatchOptions(options) {
40104         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
40105     }
40106     function serializeOptionBaseObject(options, _a, pathOptions) {
40107         var optionsNameMap = _a.optionsNameMap;
40108         var result = new ts.Map();
40109         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
40110         var _loop_5 = function (name) {
40111             if (ts.hasProperty(options, name)) {
40112                 // tsconfig only options cannot be specified via command line,
40113                 // so we can assume that only types that can appear here string | number | boolean
40114                 if (optionsNameMap.has(name) && (optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options || optionsNameMap.get(name).category === ts.Diagnostics.Output_Formatting)) {
40115                     return "continue";
40116                 }
40117                 var value = options[name];
40118                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
40119                 if (optionDefinition) {
40120                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
40121                     if (!customTypeMap_1) {
40122                         // There is no map associated with this compiler option then use the value as-is
40123                         // This is the case if the value is expect to be string, number, boolean or list of string
40124                         if (pathOptions && optionDefinition.isFilePath) {
40125                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
40126                         }
40127                         else {
40128                             result.set(name, value);
40129                         }
40130                     }
40131                     else {
40132                         if (optionDefinition.type === "list") {
40133                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
40134                         }
40135                         else {
40136                             // There is a typeMap associated with this command-line option so use it to map value back to its name
40137                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
40138                         }
40139                     }
40140                 }
40141             }
40142         };
40143         for (var name in options) {
40144             _loop_5(name);
40145         }
40146         return result;
40147     }
40148     /**
40149      * Generate a list of the compiler options whose value is not the default.
40150      * @param options compilerOptions to be evaluated.
40151     /** @internal */
40152     function getCompilerOptionsDiffValue(options, newLine) {
40153         var compilerOptionsMap = getSerializedCompilerOption(options);
40154         return getOverwrittenDefaultOptions();
40155         function makePadding(paddingLength) {
40156             return Array(paddingLength + 1).join(" ");
40157         }
40158         function getOverwrittenDefaultOptions() {
40159             var result = [];
40160             var tab = makePadding(2);
40161             commandOptionsWithoutBuild.forEach(function (cmd) {
40162                 if (!compilerOptionsMap.has(cmd.name)) {
40163                     return;
40164                 }
40165                 var newValue = compilerOptionsMap.get(cmd.name);
40166                 var defaultValue = getDefaultValueForOption(cmd);
40167                 if (newValue !== defaultValue) {
40168                     result.push("".concat(tab).concat(cmd.name, ": ").concat(newValue));
40169                 }
40170                 else if (ts.hasProperty(ts.defaultInitCompilerOptions, cmd.name)) {
40171                     result.push("".concat(tab).concat(cmd.name, ": ").concat(defaultValue));
40172                 }
40173             });
40174             return result.join(newLine) + newLine;
40175         }
40176     }
40177     ts.getCompilerOptionsDiffValue = getCompilerOptionsDiffValue;
40178     /**
40179      * Get the compiler options to be written into the tsconfig.json.
40180      * @param options commandlineOptions to be included in the compileOptions.
40181      */
40182     function getSerializedCompilerOption(options) {
40183         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
40184         return serializeCompilerOptions(compilerOptions);
40185     }
40186     /**
40187      * Generate tsconfig configuration when running command line "--init"
40188      * @param options commandlineOptions to be generated into tsconfig.json
40189      * @param fileNames array of filenames to be generated into tsconfig.json
40190      */
40191     /* @internal */
40192     function generateTSConfig(options, fileNames, newLine) {
40193         var compilerOptionsMap = getSerializedCompilerOption(options);
40194         return writeConfigurations();
40195         function makePadding(paddingLength) {
40196             return Array(paddingLength + 1).join(" ");
40197         }
40198         function isAllowedOptionForOutput(_a) {
40199             var category = _a.category, name = _a.name, isCommandLineOnly = _a.isCommandLineOnly;
40200             // Skip options which do not have a category or have categories which are more niche
40201             var categoriesToSkip = [ts.Diagnostics.Command_line_Options, ts.Diagnostics.Editor_Support, ts.Diagnostics.Compiler_Diagnostics, ts.Diagnostics.Backwards_Compatibility, ts.Diagnostics.Watch_and_Build_Modes, ts.Diagnostics.Output_Formatting];
40202             return !isCommandLineOnly && category !== undefined && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name));
40203         }
40204         function writeConfigurations() {
40205             // Filter applicable options to place in the file
40206             var categorizedOptions = ts.createMultiMap();
40207             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
40208                 var option = optionDeclarations_1[_i];
40209                 var category = option.category;
40210                 if (isAllowedOptionForOutput(option)) {
40211                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
40212                 }
40213             }
40214             // Serialize all options and their descriptions
40215             var marginLength = 0;
40216             var seenKnownKeys = 0;
40217             var entries = [];
40218             categorizedOptions.forEach(function (options, category) {
40219                 if (entries.length !== 0) {
40220                     entries.push({ value: "" });
40221                 }
40222                 entries.push({ value: "/* ".concat(category, " */") });
40223                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
40224                     var option = options_1[_i];
40225                     var optionName = void 0;
40226                     if (compilerOptionsMap.has(option.name)) {
40227                         optionName = "\"".concat(option.name, "\": ").concat(JSON.stringify(compilerOptionsMap.get(option.name))).concat((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
40228                     }
40229                     else {
40230                         optionName = "// \"".concat(option.name, "\": ").concat(JSON.stringify(getDefaultValueForOption(option)), ",");
40231                     }
40232                     entries.push({
40233                         value: optionName,
40234                         description: "/* ".concat(option.description && ts.getLocaleSpecificMessage(option.description) || option.name, " */")
40235                     });
40236                     marginLength = Math.max(optionName.length, marginLength);
40237                 }
40238             });
40239             // Write the output
40240             var tab = makePadding(2);
40241             var result = [];
40242             result.push("{");
40243             result.push("".concat(tab, "\"compilerOptions\": {"));
40244             result.push("".concat(tab).concat(tab, "/* ").concat(ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file), " */"));
40245             result.push("");
40246             // Print out each row, aligning all the descriptions on the same column.
40247             for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
40248                 var entry = entries_2[_a];
40249                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
40250                 result.push(value && "".concat(tab).concat(tab).concat(value).concat(description && (makePadding(marginLength - value.length + 2) + description)));
40251             }
40252             if (fileNames.length) {
40253                 result.push("".concat(tab, "},"));
40254                 result.push("".concat(tab, "\"files\": ["));
40255                 for (var i = 0; i < fileNames.length; i++) {
40256                     result.push("".concat(tab).concat(tab).concat(JSON.stringify(fileNames[i])).concat(i === fileNames.length - 1 ? "" : ","));
40257                 }
40258                 result.push("".concat(tab, "]"));
40259             }
40260             else {
40261                 result.push("".concat(tab, "}"));
40262             }
40263             result.push("}");
40264             return result.join(newLine) + newLine;
40265         }
40266     }
40267     ts.generateTSConfig = generateTSConfig;
40268     /* @internal */
40269     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
40270         var result = {};
40271         var optionsNameMap = getOptionsNameMap().optionsNameMap;
40272         for (var name in options) {
40273             if (ts.hasProperty(options, name)) {
40274                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
40275             }
40276         }
40277         if (result.configFilePath) {
40278             result.configFilePath = toAbsolutePath(result.configFilePath);
40279         }
40280         return result;
40281     }
40282     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
40283     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
40284         if (option && !isNullOrUndefined(value)) {
40285             if (option.type === "list") {
40286                 var values = value;
40287                 if (option.element.isFilePath && values.length) {
40288                     return values.map(toAbsolutePath);
40289                 }
40290             }
40291             else if (option.isFilePath) {
40292                 return toAbsolutePath(value);
40293             }
40294         }
40295         return value;
40296     }
40297     /**
40298      * Parse the contents of a config file (tsconfig.json).
40299      * @param json The contents of the config file to parse
40300      * @param host Instance of ParseConfigHost used to enumerate files in folder.
40301      * @param basePath A root directory to resolve relative path entries in the config
40302      *    file to. e.g. outDir
40303      */
40304     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
40305         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
40306     }
40307     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
40308     /**
40309      * Parse the contents of a config file (tsconfig.json).
40310      * @param jsonNode The contents of the config file to parse
40311      * @param host Instance of ParseConfigHost used to enumerate files in folder.
40312      * @param basePath A root directory to resolve relative path entries in the config
40313      *    file to. e.g. outDir
40314      */
40315     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
40316         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
40317     }
40318     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
40319     /*@internal*/
40320     function setConfigFileInOptions(options, configFile) {
40321         if (configFile) {
40322             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
40323         }
40324     }
40325     ts.setConfigFileInOptions = setConfigFileInOptions;
40326     function isNullOrUndefined(x) {
40327         return x === undefined || x === null; // eslint-disable-line no-null/no-null
40328     }
40329     function directoryOfCombinedPath(fileName, basePath) {
40330         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
40331         // until consistent casing errors are reported
40332         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
40333     }
40334     /**
40335      * Parse the contents of a config file from json or json source file (tsconfig.json).
40336      * @param json The contents of the config file to parse
40337      * @param sourceFile sourceFile corresponding to the Json
40338      * @param host Instance of ParseConfigHost used to enumerate files in folder.
40339      * @param basePath A root directory to resolve relative path entries in the config
40340      *    file to. e.g. outDir
40341      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
40342      */
40343     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
40344         if (existingOptions === void 0) { existingOptions = {}; }
40345         if (resolutionStack === void 0) { resolutionStack = []; }
40346         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
40347         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
40348         var errors = [];
40349         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
40350         var raw = parsedConfig.raw;
40351         var options = ts.extend(existingOptions, parsedConfig.options || {});
40352         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
40353             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
40354             parsedConfig.watchOptions || existingWatchOptions;
40355         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
40356         var configFileSpecs = getConfigFileSpecs();
40357         if (sourceFile)
40358             sourceFile.configFileSpecs = configFileSpecs;
40359         setConfigFileInOptions(options, sourceFile);
40360         var basePathForFileNames = ts.normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
40361         return {
40362             options: options,
40363             watchOptions: watchOptions,
40364             fileNames: getFileNames(basePathForFileNames),
40365             projectReferences: getProjectReferences(basePathForFileNames),
40366             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
40367             raw: raw,
40368             errors: errors,
40369             // Wildcard directories (provided as part of a wildcard path) are stored in a
40370             // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
40371             // or a recursive directory. This information is used by filesystem watchers to monitor for
40372             // new entries in these paths.
40373             wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
40374             compileOnSave: !!raw.compileOnSave,
40375         };
40376         function getConfigFileSpecs() {
40377             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
40378             var filesSpecs = toPropValue(getSpecsFromRaw("files"));
40379             if (filesSpecs) {
40380                 var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
40381                 var hasExtends = ts.hasProperty(raw, "extends");
40382                 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
40383                     if (sourceFile) {
40384                         var fileName = configFileName || "tsconfig.json";
40385                         var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
40386                         var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
40387                         var error = nodeValue
40388                             ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
40389                             : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
40390                         errors.push(error);
40391                     }
40392                     else {
40393                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
40394                     }
40395                 }
40396             }
40397             var includeSpecs = toPropValue(getSpecsFromRaw("include"));
40398             var excludeOfRaw = getSpecsFromRaw("exclude");
40399             var excludeSpecs = toPropValue(excludeOfRaw);
40400             if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
40401                 var outDir = raw.compilerOptions.outDir;
40402                 var declarationDir = raw.compilerOptions.declarationDir;
40403                 if (outDir || declarationDir) {
40404                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
40405                 }
40406             }
40407             if (filesSpecs === undefined && includeSpecs === undefined) {
40408                 includeSpecs = ["**/*"];
40409             }
40410             var validatedIncludeSpecs, validatedExcludeSpecs;
40411             // The exclude spec list is converted into a regular expression, which allows us to quickly
40412             // test whether a file or directory should be excluded before recursively traversing the
40413             // file system.
40414             if (includeSpecs) {
40415                 validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*disallowTrailingRecursion*/ true, sourceFile, "include");
40416             }
40417             if (excludeSpecs) {
40418                 validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ false, sourceFile, "exclude");
40419             }
40420             return {
40421                 filesSpecs: filesSpecs,
40422                 includeSpecs: includeSpecs,
40423                 excludeSpecs: excludeSpecs,
40424                 validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
40425                 validatedIncludeSpecs: validatedIncludeSpecs,
40426                 validatedExcludeSpecs: validatedExcludeSpecs,
40427                 pathPatterns: undefined, // Initialized on first use
40428             };
40429         }
40430         function getFileNames(basePath) {
40431             var fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions);
40432             if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
40433                 errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
40434             }
40435             return fileNames;
40436         }
40437         function getProjectReferences(basePath) {
40438             var projectReferences;
40439             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
40440             if (ts.isArray(referencesOfRaw)) {
40441                 for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
40442                     var ref = referencesOfRaw_1[_i];
40443                     if (typeof ref.path !== "string") {
40444                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
40445                     }
40446                     else {
40447                         (projectReferences || (projectReferences = [])).push({
40448                             path: ts.getNormalizedAbsolutePath(ref.path, basePath),
40449                             originalPath: ref.path,
40450                             prepend: ref.prepend,
40451                             circular: ref.circular
40452                         });
40453                     }
40454                 }
40455             }
40456             return projectReferences;
40457         }
40458         function toPropValue(specResult) {
40459             return ts.isArray(specResult) ? specResult : undefined;
40460         }
40461         function getSpecsFromRaw(prop) {
40462             return getPropFromRaw(prop, ts.isString, "string");
40463         }
40464         function getPropFromRaw(prop, validateElement, elementTypeName) {
40465             if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
40466                 if (ts.isArray(raw[prop])) {
40467                     var result = raw[prop];
40468                     if (!sourceFile && !ts.every(result, validateElement)) {
40469                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
40470                     }
40471                     return result;
40472                 }
40473                 else {
40474                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
40475                     return "not-array";
40476                 }
40477             }
40478             return "no-prop";
40479         }
40480         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
40481             if (!sourceFile) {
40482                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
40483             }
40484         }
40485     }
40486     function isErrorNoInputFiles(error) {
40487         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
40488     }
40489     function getErrorForNoInputFiles(_a, configFileName) {
40490         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
40491         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 || []));
40492     }
40493     function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
40494         return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
40495     }
40496     /*@internal*/
40497     function canJsonReportNoInputFiles(raw) {
40498         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
40499     }
40500     ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
40501     /*@internal*/
40502     function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
40503         var existingErrors = configParseDiagnostics.length;
40504         if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
40505             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
40506         }
40507         else {
40508             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
40509         }
40510         return existingErrors !== configParseDiagnostics.length;
40511     }
40512     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
40513     function isSuccessfulParsedTsconfig(value) {
40514         return !!value.options;
40515     }
40516     /**
40517      * This *just* extracts options/include/exclude/files out of a config file.
40518      * It does *not* resolve the included files.
40519      */
40520     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
40521         var _a;
40522         basePath = ts.normalizeSlashes(basePath);
40523         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
40524         if (resolutionStack.indexOf(resolvedPath) >= 0) {
40525             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArray(__spreadArray([], resolutionStack, true), [resolvedPath], false).join(" -> ")));
40526             return { raw: json || convertToObject(sourceFile, errors) };
40527         }
40528         var ownConfig = json ?
40529             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
40530             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
40531         if ((_a = ownConfig.options) === null || _a === void 0 ? void 0 : _a.paths) {
40532             // If we end up needing to resolve relative paths from 'paths' relative to
40533             // the config file location, we'll need to know where that config file was.
40534             // Since 'paths' can be inherited from an extended config in another directory,
40535             // we wouldn't know which directory to use unless we store it here.
40536             ownConfig.options.pathsBasePath = basePath;
40537         }
40538         if (ownConfig.extendedConfigPath) {
40539             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
40540             resolutionStack = resolutionStack.concat([resolvedPath]);
40541             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache);
40542             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
40543                 var baseRaw_1 = extendedConfig.raw;
40544                 var raw_1 = ownConfig.raw;
40545                 var relativeDifference_1;
40546                 var setPropertyInRawIfNotUndefined = function (propertyName) {
40547                     if (!raw_1[propertyName] && baseRaw_1[propertyName]) {
40548                         raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); });
40549                     }
40550                 };
40551                 setPropertyInRawIfNotUndefined("include");
40552                 setPropertyInRawIfNotUndefined("exclude");
40553                 setPropertyInRawIfNotUndefined("files");
40554                 if (raw_1.compileOnSave === undefined) {
40555                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
40556                 }
40557                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
40558                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
40559                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
40560                     ownConfig.watchOptions || extendedConfig.watchOptions;
40561                 // TODO extend type typeAcquisition
40562             }
40563         }
40564         return ownConfig;
40565     }
40566     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
40567         if (ts.hasProperty(json, "excludes")) {
40568             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
40569         }
40570         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
40571         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
40572         // It should be removed in future releases - use typeAcquisition instead.
40573         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
40574         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
40575         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
40576         var extendedConfigPath;
40577         if (json.extends) {
40578             if (!ts.isString(json.extends)) {
40579                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
40580             }
40581             else {
40582                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
40583                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
40584             }
40585         }
40586         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
40587     }
40588     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
40589         var options = getDefaultCompilerOptions(configFileName);
40590         var typeAcquisition, typingOptionstypeAcquisition;
40591         var watchOptions;
40592         var extendedConfigPath;
40593         var rootCompilerOptions;
40594         var optionsIterator = {
40595             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
40596                 var currentOption;
40597                 switch (parentOption) {
40598                     case "compilerOptions":
40599                         currentOption = options;
40600                         break;
40601                     case "watchOptions":
40602                         currentOption = (watchOptions || (watchOptions = {}));
40603                         break;
40604                     case "typeAcquisition":
40605                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
40606                         break;
40607                     case "typingOptions":
40608                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
40609                         break;
40610                     default:
40611                         ts.Debug.fail("Unknown option");
40612                 }
40613                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
40614             },
40615             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
40616                 switch (key) {
40617                     case "extends":
40618                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
40619                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
40620                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
40621                         });
40622                         return;
40623                 }
40624             },
40625             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
40626                 if (key === "excludes") {
40627                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
40628                 }
40629                 if (ts.find(commandOptionsWithoutBuild, function (opt) { return opt.name === key; })) {
40630                     rootCompilerOptions = ts.append(rootCompilerOptions, keyNode);
40631                 }
40632             }
40633         };
40634         var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator);
40635         if (!typeAcquisition) {
40636             if (typingOptionstypeAcquisition) {
40637                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
40638                     {
40639                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
40640                         include: typingOptionstypeAcquisition.include,
40641                         exclude: typingOptionstypeAcquisition.exclude
40642                     } :
40643                     typingOptionstypeAcquisition;
40644             }
40645             else {
40646                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
40647             }
40648         }
40649         if (rootCompilerOptions && json && json.compilerOptions === undefined) {
40650             errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], ts.Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, ts.getTextOfPropertyName(rootCompilerOptions[0])));
40651         }
40652         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
40653     }
40654     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
40655         extendedConfig = ts.normalizeSlashes(extendedConfig);
40656         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
40657             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
40658             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
40659                 extendedConfigPath = "".concat(extendedConfigPath, ".json");
40660                 if (!host.fileExists(extendedConfigPath)) {
40661                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
40662                     return undefined;
40663                 }
40664             }
40665             return extendedConfigPath;
40666         }
40667         // If the path isn't a rooted or relative path, resolve like a module
40668         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
40669         if (resolved.resolvedModule) {
40670             return resolved.resolvedModule.resolvedFileName;
40671         }
40672         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
40673         return undefined;
40674     }
40675     function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) {
40676         var _a;
40677         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
40678         var value;
40679         var extendedResult;
40680         var extendedConfig;
40681         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
40682             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
40683         }
40684         else {
40685             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
40686             if (!extendedResult.parseDiagnostics.length) {
40687                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
40688             }
40689             if (extendedConfigCache) {
40690                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
40691             }
40692         }
40693         if (sourceFile) {
40694             sourceFile.extendedSourceFiles = [extendedResult.fileName];
40695             if (extendedResult.extendedSourceFiles) {
40696                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
40697             }
40698         }
40699         if (extendedResult.parseDiagnostics.length) {
40700             errors.push.apply(errors, extendedResult.parseDiagnostics);
40701             return undefined;
40702         }
40703         return extendedConfig;
40704     }
40705     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
40706         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
40707             return false;
40708         }
40709         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
40710         return typeof result === "boolean" && result;
40711     }
40712     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
40713         var errors = [];
40714         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
40715         return { options: options, errors: errors };
40716     }
40717     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
40718     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
40719         var errors = [];
40720         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
40721         return { options: options, errors: errors };
40722     }
40723     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
40724     function getDefaultCompilerOptions(configFileName) {
40725         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
40726             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
40727             : {};
40728         return options;
40729     }
40730     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
40731         var options = getDefaultCompilerOptions(configFileName);
40732         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
40733         if (configFileName) {
40734             options.configFilePath = ts.normalizeSlashes(configFileName);
40735         }
40736         return options;
40737     }
40738     function getDefaultTypeAcquisition(configFileName) {
40739         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
40740     }
40741     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
40742         var options = getDefaultTypeAcquisition(configFileName);
40743         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
40744         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
40745         return options;
40746     }
40747     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
40748         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
40749     }
40750     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
40751         if (!jsonOptions) {
40752             return;
40753         }
40754         for (var id in jsonOptions) {
40755             var opt = optionsNameMap.get(id);
40756             if (opt) {
40757                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
40758             }
40759             else {
40760                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
40761             }
40762         }
40763         return defaultOptions;
40764     }
40765     /*@internal*/
40766     function convertJsonOption(opt, value, basePath, errors) {
40767         if (isCompilerOptionsValue(opt, value)) {
40768             var optType = opt.type;
40769             if (optType === "list" && ts.isArray(value)) {
40770                 return convertJsonOptionOfListType(opt, value, basePath, errors);
40771             }
40772             else if (!ts.isString(optType)) {
40773                 return convertJsonOptionOfCustomType(opt, value, errors);
40774             }
40775             var validatedValue = validateJsonOptionValue(opt, value, errors);
40776             return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
40777         }
40778         else {
40779             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
40780         }
40781     }
40782     ts.convertJsonOption = convertJsonOption;
40783     function normalizeOptionValue(option, basePath, value) {
40784         if (isNullOrUndefined(value))
40785             return undefined;
40786         if (option.type === "list") {
40787             var listOption_1 = option;
40788             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
40789                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
40790             }
40791             return value;
40792         }
40793         else if (!ts.isString(option.type)) {
40794             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
40795         }
40796         return normalizeNonListOptionValue(option, basePath, value);
40797     }
40798     function normalizeNonListOptionValue(option, basePath, value) {
40799         if (option.isFilePath) {
40800             value = ts.getNormalizedAbsolutePath(value, basePath);
40801             if (value === "") {
40802                 value = ".";
40803             }
40804         }
40805         return value;
40806     }
40807     function validateJsonOptionValue(opt, value, errors) {
40808         var _a;
40809         if (isNullOrUndefined(value))
40810             return undefined;
40811         var d = (_a = opt.extraValidation) === null || _a === void 0 ? void 0 : _a.call(opt, value);
40812         if (!d)
40813             return value;
40814         errors.push(ts.createCompilerDiagnostic.apply(void 0, d));
40815         return undefined;
40816     }
40817     function convertJsonOptionOfCustomType(opt, value, errors) {
40818         if (isNullOrUndefined(value))
40819             return undefined;
40820         var key = value.toLowerCase();
40821         var val = opt.type.get(key);
40822         if (val !== undefined) {
40823             return validateJsonOptionValue(opt, val, errors);
40824         }
40825         else {
40826             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
40827         }
40828     }
40829     function convertJsonOptionOfListType(option, values, basePath, errors) {
40830         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
40831     }
40832     /**
40833      * Tests for a path that ends in a recursive directory wildcard.
40834      * Matches **, \**, **\, and \**\, but not a**b.
40835      *
40836      * NOTE: used \ in place of / above to avoid issues with multiline comments.
40837      *
40838      * Breakdown:
40839      *  (^|\/)      # matches either the beginning of the string or a directory separator.
40840      *  \*\*        # matches the recursive directory wildcard "**".
40841      *  \/?$        # matches an optional trailing directory separator at the end of the string.
40842      */
40843     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
40844     /**
40845      * Matches the portion of a wildcard path that does not contain wildcards.
40846      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
40847      *
40848      * NOTE: used \ in place of / above to avoid issues with multiline comments.
40849      *
40850      * Breakdown:
40851      *  ^                   # matches the beginning of the string
40852      *  [^*?]*              # matches any number of non-wildcard characters
40853      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
40854      *                      # a path component that contains at least one wildcard character (* or ?).
40855      */
40856     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
40857     /**
40858      * Gets the file names from the provided config file specs that contain, files, include, exclude and
40859      * other properties needed to resolve the file names
40860      * @param configFileSpecs The config file specs extracted with file names to include, wildcards to include/exclude and other details
40861      * @param basePath The base path for any relative file specifications.
40862      * @param options Compiler options.
40863      * @param host The host used to resolve files and directories.
40864      * @param extraFileExtensions optionaly file extra file extension information from host
40865      */
40866     /* @internal */
40867     function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions) {
40868         if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
40869         basePath = ts.normalizePath(basePath);
40870         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
40871         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
40872         // file map with a possibly case insensitive key. We use this map later when when including
40873         // wildcard paths.
40874         var literalFileMap = new ts.Map();
40875         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
40876         // file map with a possibly case insensitive key. We use this map to store paths matched
40877         // via wildcard, and to handle extension priority.
40878         var wildcardFileMap = new ts.Map();
40879         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
40880         // file map with a possibly case insensitive key. We use this map to store paths matched
40881         // via wildcard of *.json kind
40882         var wildCardJsonFileMap = new ts.Map();
40883         var validatedFilesSpec = configFileSpecs.validatedFilesSpec, validatedIncludeSpecs = configFileSpecs.validatedIncludeSpecs, validatedExcludeSpecs = configFileSpecs.validatedExcludeSpecs;
40884         // Rather than re-query this for each file and filespec, we query the supported extensions
40885         // once and store it on the expansion context.
40886         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
40887         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
40888         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
40889         // remove a literal file.
40890         if (validatedFilesSpec) {
40891             for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
40892                 var fileName = validatedFilesSpec_1[_i];
40893                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
40894                 literalFileMap.set(keyMapper(file), file);
40895             }
40896         }
40897         var jsonOnlyIncludeRegexes;
40898         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
40899             var _loop_6 = function (file) {
40900                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
40901                     // Valid only if *.json specified
40902                     if (!jsonOnlyIncludeRegexes) {
40903                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
40904                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^".concat(pattern, "$"); });
40905                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
40906                     }
40907                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
40908                     if (includeIndex !== -1) {
40909                         var key_1 = keyMapper(file);
40910                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
40911                             wildCardJsonFileMap.set(key_1, file);
40912                         }
40913                     }
40914                     return "continue";
40915                 }
40916                 // If we have already included a literal or wildcard path with a
40917                 // higher priority extension, we should skip this file.
40918                 //
40919                 // This handles cases where we may encounter both <file>.ts and
40920                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
40921                 // directory when they are compilation outputs.
40922                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
40923                     return "continue";
40924                 }
40925                 // We may have included a wildcard path with a lower priority
40926                 // extension due to the user-defined order of entries in the
40927                 // "include" array. If there is a lower priority extension in the
40928                 // same directory, we should remove it.
40929                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
40930                 var key = keyMapper(file);
40931                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
40932                     wildcardFileMap.set(key, file);
40933                 }
40934             };
40935             for (var _a = 0, _b = host.readDirectory(basePath, ts.flatten(supportedExtensionsWithJsonIfResolveJsonModule), validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
40936                 var file = _b[_a];
40937                 _loop_6(file);
40938             }
40939         }
40940         var literalFiles = ts.arrayFrom(literalFileMap.values());
40941         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
40942         return literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values()));
40943     }
40944     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
40945     /* @internal */
40946     function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
40947         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
40948         if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
40949             return false;
40950         basePath = ts.normalizePath(basePath);
40951         var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
40952         if (validatedFilesSpec) {
40953             for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
40954                 var fileName = validatedFilesSpec_2[_i];
40955                 if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
40956                     return false;
40957             }
40958         }
40959         return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath);
40960     }
40961     ts.isExcludedFile = isExcludedFile;
40962     function invalidDotDotAfterRecursiveWildcard(s) {
40963         // We used to use the regex /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/ to check for this case, but
40964         // in v8, that has polynomial performance because the recursive wildcard match - **/ -
40965         // can be matched in many arbitrary positions when multiple are present, resulting
40966         // in bad backtracking (and we don't care which is matched - just that some /.. segment
40967         // comes after some **/ segment).
40968         var wildcardIndex = ts.startsWith(s, "**/") ? 0 : s.indexOf("/**/");
40969         if (wildcardIndex === -1) {
40970             return false;
40971         }
40972         var lastDotIndex = ts.endsWith(s, "/..") ? s.length : s.lastIndexOf("/../");
40973         return lastDotIndex > wildcardIndex;
40974     }
40975     /* @internal */
40976     function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) {
40977         return matchesExcludeWorker(pathToCheck, ts.filter(excludeSpecs, function (spec) { return !invalidDotDotAfterRecursiveWildcard(spec); }), useCaseSensitiveFileNames, currentDirectory);
40978     }
40979     ts.matchesExclude = matchesExclude;
40980     function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) {
40981         var excludePattern = ts.getRegularExpressionForWildcard(excludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
40982         var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
40983         if (!excludeRegex)
40984             return false;
40985         if (excludeRegex.test(pathToCheck))
40986             return true;
40987         return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
40988     }
40989     function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
40990         return specs.filter(function (spec) {
40991             if (!ts.isString(spec))
40992                 return false;
40993             var diag = specToDiagnostic(spec, disallowTrailingRecursion);
40994             if (diag !== undefined) {
40995                 errors.push(createDiagnostic.apply(void 0, diag));
40996             }
40997             return diag === undefined;
40998         });
40999         function createDiagnostic(message, spec) {
41000             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
41001             return element ?
41002                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
41003                 ts.createCompilerDiagnostic(message, spec);
41004         }
41005     }
41006     function specToDiagnostic(spec, disallowTrailingRecursion) {
41007         if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
41008             return [ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
41009         }
41010         else if (invalidDotDotAfterRecursiveWildcard(spec)) {
41011             return [ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
41012         }
41013     }
41014     /**
41015      * Gets directories in a set of include patterns that should be watched for changes.
41016      */
41017     function getWildcardDirectories(_a, path, useCaseSensitiveFileNames) {
41018         var include = _a.validatedIncludeSpecs, exclude = _a.validatedExcludeSpecs;
41019         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
41020         // of the pattern:
41021         //
41022         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
41023         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
41024         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
41025         //
41026         // We watch a directory without recursion if it contains a wildcard in the file segment of
41027         // the pattern:
41028         //
41029         //  /a/b/*      - Watch /a/b directly to catch any new file
41030         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
41031         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
41032         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
41033         var wildcardDirectories = {};
41034         if (include !== undefined) {
41035             var recursiveKeys = [];
41036             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
41037                 var file = include_1[_i];
41038                 var spec = ts.normalizePath(ts.combinePaths(path, file));
41039                 if (excludeRegex && excludeRegex.test(spec)) {
41040                     continue;
41041                 }
41042                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
41043                 if (match) {
41044                     var key = match.key, flags = match.flags;
41045                     var existingFlags = wildcardDirectories[key];
41046                     if (existingFlags === undefined || existingFlags < flags) {
41047                         wildcardDirectories[key] = flags;
41048                         if (flags === 1 /* Recursive */) {
41049                             recursiveKeys.push(key);
41050                         }
41051                     }
41052                 }
41053             }
41054             // Remove any subpaths under an existing recursively watched directory.
41055             for (var key in wildcardDirectories) {
41056                 if (ts.hasProperty(wildcardDirectories, key)) {
41057                     for (var _b = 0, recursiveKeys_1 = recursiveKeys; _b < recursiveKeys_1.length; _b++) {
41058                         var recursiveKey = recursiveKeys_1[_b];
41059                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
41060                             delete wildcardDirectories[key];
41061                         }
41062                     }
41063                 }
41064             }
41065         }
41066         return wildcardDirectories;
41067     }
41068     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
41069         var match = wildcardDirectoryPattern.exec(spec);
41070         if (match) {
41071             // We check this with a few `indexOf` calls because 3 `indexOf`/`lastIndexOf` calls is
41072             // less algorithmically complex (roughly O(3n) worst-case) than the regex we used to use,
41073             // \/[^/]*?[*?][^/]*\/ which was polynominal in v8, since arbitrary sequences of wildcard
41074             // characters could match any of the central patterns, resulting in bad backtracking.
41075             var questionWildcardIndex = spec.indexOf("?");
41076             var starWildcardIndex = spec.indexOf("*");
41077             var lastDirectorySeperatorIndex = spec.lastIndexOf(ts.directorySeparator);
41078             return {
41079                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
41080                 flags: (questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex)
41081                     || (starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex)
41082                     ? 1 /* Recursive */ : 0 /* None */
41083             };
41084         }
41085         if (ts.isImplicitGlob(spec)) {
41086             return {
41087                 key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec),
41088                 flags: 1 /* Recursive */
41089             };
41090         }
41091         return undefined;
41092     }
41093     /**
41094      * Determines whether a literal or wildcard file has already been included that has a higher
41095      * extension priority.
41096      *
41097      * @param file The path to the file.
41098      */
41099     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
41100         var extensionGroup = ts.forEach(extensions, function (group) { return ts.fileExtensionIsOneOf(file, group) ? group : undefined; });
41101         if (!extensionGroup) {
41102             return false;
41103         }
41104         for (var _i = 0, extensionGroup_1 = extensionGroup; _i < extensionGroup_1.length; _i++) {
41105             var ext = extensionGroup_1[_i];
41106             if (ts.fileExtensionIs(file, ext)) {
41107                 return false;
41108             }
41109             var higherPriorityPath = keyMapper(ts.changeExtension(file, ext));
41110             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
41111                 if (ext === ".d.ts" /* Dts */ && (ts.fileExtensionIs(file, ".js" /* Js */) || ts.fileExtensionIs(file, ".jsx" /* Jsx */))) {
41112                     // LEGACY BEHAVIOR: An off-by-one bug somewhere in the extension priority system for wildcard module loading allowed declaration
41113                     // files to be loaded alongside their js(x) counterparts. We regard this as generally undesirable, but retain the behavior to
41114                     // prevent breakage.
41115                     continue;
41116                 }
41117                 return true;
41118             }
41119         }
41120         return false;
41121     }
41122     /**
41123      * Removes files included via wildcard expansion with a lower extension priority that have
41124      * already been included.
41125      *
41126      * @param file The path to the file.
41127      */
41128     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
41129         var extensionGroup = ts.forEach(extensions, function (group) { return ts.fileExtensionIsOneOf(file, group) ? group : undefined; });
41130         if (!extensionGroup) {
41131             return;
41132         }
41133         for (var i = extensionGroup.length - 1; i >= 0; i--) {
41134             var ext = extensionGroup[i];
41135             if (ts.fileExtensionIs(file, ext)) {
41136                 return;
41137             }
41138             var lowerPriorityPath = keyMapper(ts.changeExtension(file, ext));
41139             wildcardFiles.delete(lowerPriorityPath);
41140         }
41141     }
41142     /**
41143      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
41144      * Also converts enum values back to strings.
41145      */
41146     /* @internal */
41147     function convertCompilerOptionsForTelemetry(opts) {
41148         var out = {};
41149         for (var key in opts) {
41150             if (opts.hasOwnProperty(key)) {
41151                 var type = getOptionFromName(key);
41152                 if (type !== undefined) { // Ignore unknown options
41153                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
41154                 }
41155             }
41156         }
41157         return out;
41158     }
41159     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
41160     function getOptionValueWithEmptyStrings(value, option) {
41161         switch (option.type) {
41162             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
41163                 return "";
41164             case "string": // Could be any arbitrary string -- use empty string instead.
41165                 return "";
41166             case "number": // Allow numbers, but be sure to check it's actually a number.
41167                 return typeof value === "number" ? value : "";
41168             case "boolean":
41169                 return typeof value === "boolean" ? value : "";
41170             case "list":
41171                 var elementType_1 = option.element;
41172                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
41173             default:
41174                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
41175                     if (optionEnumValue === value) {
41176                         return optionStringValue;
41177                     }
41178                 }); // TODO: GH#18217
41179         }
41180     }
41181     function getDefaultValueForOption(option) {
41182         switch (option.type) {
41183             case "number":
41184                 return 1;
41185             case "boolean":
41186                 return true;
41187             case "string":
41188                 return option.isFilePath ? "./" : "";
41189             case "list":
41190                 return [];
41191             case "object":
41192                 return {};
41193             default:
41194                 var iterResult = option.type.keys().next();
41195                 if (!iterResult.done)
41196                     return iterResult.value;
41197                 return ts.Debug.fail("Expected 'option.type' to have entries.");
41198         }
41199     }
41200 })(ts || (ts = {}));
41201 var ts;
41202 (function (ts) {
41203     function trace(host) {
41204         host.trace(ts.formatMessage.apply(undefined, arguments));
41205     }
41206     ts.trace = trace;
41207     /* @internal */
41208     function isTraceEnabled(compilerOptions, host) {
41209         return !!compilerOptions.traceResolution && host.trace !== undefined;
41210     }
41211     ts.isTraceEnabled = isTraceEnabled;
41212     function withPackageId(packageInfo, r) {
41213         var packageId;
41214         if (r && packageInfo) {
41215             var packageJsonContent = packageInfo.packageJsonContent;
41216             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
41217                 packageId = {
41218                     name: packageJsonContent.name,
41219                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
41220                     version: packageJsonContent.version
41221                 };
41222             }
41223         }
41224         return r && { path: r.path, extension: r.ext, packageId: packageId };
41225     }
41226     function noPackageId(r) {
41227         return withPackageId(/*packageInfo*/ undefined, r);
41228     }
41229     function removeIgnoredPackageId(r) {
41230         if (r) {
41231             ts.Debug.assert(r.packageId === undefined);
41232             return { path: r.path, ext: r.extension };
41233         }
41234     }
41235     /**
41236      * Kinds of file that we are currently looking for.
41237      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
41238      */
41239     var Extensions;
41240     (function (Extensions) {
41241         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
41242         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
41243         Extensions[Extensions["Json"] = 2] = "Json";
41244         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
41245         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
41246     })(Extensions || (Extensions = {}));
41247     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
41248     function resolvedTypeScriptOnly(resolved) {
41249         if (!resolved) {
41250             return undefined;
41251         }
41252         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
41253         return { fileName: resolved.path, packageId: resolved.packageId };
41254     }
41255     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
41256         var _a;
41257         if (resultFromCache) {
41258             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
41259             return resultFromCache;
41260         }
41261         return {
41262             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
41263             failedLookupLocations: failedLookupLocations
41264         };
41265     }
41266     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
41267         if (!ts.hasProperty(jsonContent, fieldName)) {
41268             if (state.traceEnabled) {
41269                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
41270             }
41271             return;
41272         }
41273         var value = jsonContent[fieldName];
41274         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
41275             if (state.traceEnabled) {
41276                 // eslint-disable-next-line no-null/no-null
41277                 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);
41278             }
41279             return;
41280         }
41281         return value;
41282     }
41283     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
41284         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
41285         if (fileName === undefined) {
41286             return;
41287         }
41288         if (!fileName) {
41289             if (state.traceEnabled) {
41290                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
41291             }
41292             return;
41293         }
41294         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
41295         if (state.traceEnabled) {
41296             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
41297         }
41298         return path;
41299     }
41300     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
41301         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
41302             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
41303     }
41304     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
41305         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
41306     }
41307     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
41308         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
41309     }
41310     function readPackageJsonTypesVersionsField(jsonContent, state) {
41311         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
41312         if (typesVersions === undefined)
41313             return;
41314         if (state.traceEnabled) {
41315             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
41316         }
41317         return typesVersions;
41318     }
41319     function readPackageJsonTypesVersionPaths(jsonContent, state) {
41320         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
41321         if (typesVersions === undefined)
41322             return;
41323         if (state.traceEnabled) {
41324             for (var key in typesVersions) {
41325                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
41326                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
41327                 }
41328             }
41329         }
41330         var result = getPackageJsonTypesVersionsPaths(typesVersions);
41331         if (!result) {
41332             if (state.traceEnabled) {
41333                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
41334             }
41335             return;
41336         }
41337         var bestVersionKey = result.version, bestVersionPaths = result.paths;
41338         if (typeof bestVersionPaths !== "object") {
41339             if (state.traceEnabled) {
41340                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['".concat(bestVersionKey, "']"), "object", typeof bestVersionPaths);
41341             }
41342             return;
41343         }
41344         return result;
41345     }
41346     var typeScriptVersion;
41347     /* @internal */
41348     function getPackageJsonTypesVersionsPaths(typesVersions) {
41349         if (!typeScriptVersion)
41350             typeScriptVersion = new ts.Version(ts.version);
41351         for (var key in typesVersions) {
41352             if (!ts.hasProperty(typesVersions, key))
41353                 continue;
41354             var keyRange = ts.VersionRange.tryParse(key);
41355             if (keyRange === undefined) {
41356                 continue;
41357             }
41358             // return the first entry whose range matches the current compiler version.
41359             if (keyRange.test(typeScriptVersion)) {
41360                 return { version: key, paths: typesVersions[key] };
41361             }
41362         }
41363     }
41364     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
41365     function getEffectiveTypeRoots(options, host) {
41366         if (options.typeRoots) {
41367             return options.typeRoots;
41368         }
41369         var currentDirectory;
41370         if (options.configFilePath) {
41371             currentDirectory = ts.getDirectoryPath(options.configFilePath);
41372         }
41373         else if (host.getCurrentDirectory) {
41374             currentDirectory = host.getCurrentDirectory();
41375         }
41376         if (currentDirectory !== undefined) {
41377             return getDefaultTypeRoots(currentDirectory, host);
41378         }
41379     }
41380     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
41381     /**
41382      * Returns the path to every node_modules/@types directory from some ancestor directory.
41383      * Returns undefined if there are none.
41384      */
41385     function getDefaultTypeRoots(currentDirectory, host) {
41386         if (!host.directoryExists) {
41387             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
41388             // And if it doesn't exist, tough.
41389         }
41390         var typeRoots;
41391         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
41392             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
41393             if (host.directoryExists(atTypes)) {
41394                 (typeRoots || (typeRoots = [])).push(atTypes);
41395             }
41396             return undefined;
41397         });
41398         return typeRoots;
41399     }
41400     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
41401     function arePathsEqual(path1, path2, host) {
41402         var useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
41403         return ts.comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */;
41404     }
41405     /**
41406      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
41407      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
41408      * is assumed to be the same as root directory of the project.
41409      */
41410     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) {
41411         var traceEnabled = isTraceEnabled(options, host);
41412         if (redirectedReference) {
41413             options = redirectedReference.commandLine.options;
41414         }
41415         var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined;
41416         var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined;
41417         var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName, /*mode*/ undefined);
41418         if (result) {
41419             if (traceEnabled) {
41420                 trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
41421                 if (redirectedReference)
41422                     trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
41423                 trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory);
41424                 traceResult(result);
41425             }
41426             return result;
41427         }
41428         var typeRoots = getEffectiveTypeRoots(options, host);
41429         if (traceEnabled) {
41430             if (containingFile === undefined) {
41431                 if (typeRoots === undefined) {
41432                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
41433                 }
41434                 else {
41435                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
41436                 }
41437             }
41438             else {
41439                 if (typeRoots === undefined) {
41440                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
41441                 }
41442                 else {
41443                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
41444                 }
41445             }
41446             if (redirectedReference) {
41447                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
41448             }
41449         }
41450         var failedLookupLocations = [];
41451         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.AllFeatures, conditions: ["node", "require", "types"] };
41452         var resolved = primaryLookup();
41453         var primary = true;
41454         if (!resolved) {
41455             resolved = secondaryLookup();
41456             primary = false;
41457         }
41458         var resolvedTypeReferenceDirective;
41459         if (resolved) {
41460             var fileName = resolved.fileName, packageId = resolved.packageId;
41461             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
41462             resolvedTypeReferenceDirective = {
41463                 primary: primary,
41464                 resolvedFileName: resolvedFileName,
41465                 originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName,
41466                 packageId: packageId,
41467                 isExternalLibraryImport: pathContainsNodeModules(fileName),
41468             };
41469         }
41470         result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
41471         perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ undefined, result);
41472         if (traceEnabled)
41473             traceResult(result);
41474         return result;
41475         function traceResult(result) {
41476             var _a;
41477             if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) {
41478                 trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
41479             }
41480             else if (result.resolvedTypeReferenceDirective.packageId) {
41481                 trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary);
41482             }
41483             else {
41484                 trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary);
41485             }
41486         }
41487         function primaryLookup() {
41488             // Check primary library paths
41489             if (typeRoots && typeRoots.length) {
41490                 if (traceEnabled) {
41491                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
41492                 }
41493                 return ts.firstDefined(typeRoots, function (typeRoot) {
41494                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
41495                     var candidateDirectory = ts.getDirectoryPath(candidate);
41496                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
41497                     if (!directoryExists && traceEnabled) {
41498                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
41499                     }
41500                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
41501                 });
41502             }
41503             else {
41504                 if (traceEnabled) {
41505                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
41506                 }
41507             }
41508         }
41509         function secondaryLookup() {
41510             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
41511             if (initialLocationForSecondaryLookup !== undefined) {
41512                 // check secondary locations
41513                 if (traceEnabled) {
41514                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
41515                 }
41516                 var result_4;
41517                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
41518                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
41519                     result_4 = searchResult && searchResult.value;
41520                 }
41521                 else {
41522                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
41523                     result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
41524                 }
41525                 return resolvedTypeScriptOnly(result_4);
41526             }
41527             else {
41528                 if (traceEnabled) {
41529                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
41530                 }
41531             }
41532         }
41533     }
41534     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
41535     /**
41536      * Given a set of options, returns the set of type directive names
41537      *   that should be included for this program automatically.
41538      * This list could either come from the config file,
41539      *   or from enumerating the types root + initial secondary types lookup location.
41540      * More type directives might appear in the program later as a result of loading actual source files;
41541      *   this list is only the set of defaults that are implicitly included.
41542      */
41543     function getAutomaticTypeDirectiveNames(options, host) {
41544         // Use explicit type list from tsconfig.json
41545         if (options.types) {
41546             return options.types;
41547         }
41548         // Walk the primary type lookup locations
41549         var result = [];
41550         if (host.directoryExists && host.getDirectories) {
41551             var typeRoots = getEffectiveTypeRoots(options, host);
41552             if (typeRoots) {
41553                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
41554                     var root = typeRoots_1[_i];
41555                     if (host.directoryExists(root)) {
41556                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
41557                             var typeDirectivePath = _b[_a];
41558                             var normalized = ts.normalizePath(typeDirectivePath);
41559                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
41560                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
41561                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
41562                             // eslint-disable-next-line no-null/no-null
41563                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
41564                             if (!isNotNeededPackage) {
41565                                 var baseFileName = ts.getBaseFileName(normalized);
41566                                 // At this stage, skip results with leading dot.
41567                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
41568                                     // Return just the type directive names
41569                                     result.push(baseFileName);
41570                                 }
41571                             }
41572                         }
41573                     }
41574                 }
41575             }
41576         }
41577         return result;
41578     }
41579     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
41580     /*@internal*/
41581     function createCacheWithRedirects(options) {
41582         var ownMap = new ts.Map();
41583         var redirectsMap = new ts.Map();
41584         return {
41585             getOwnMap: getOwnMap,
41586             redirectsMap: redirectsMap,
41587             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
41588             clear: clear,
41589             setOwnOptions: setOwnOptions,
41590             setOwnMap: setOwnMap
41591         };
41592         function getOwnMap() {
41593             return ownMap;
41594         }
41595         function setOwnOptions(newOptions) {
41596             options = newOptions;
41597         }
41598         function setOwnMap(newOwnMap) {
41599             ownMap = newOwnMap;
41600         }
41601         function getOrCreateMapOfCacheRedirects(redirectedReference) {
41602             if (!redirectedReference) {
41603                 return ownMap;
41604             }
41605             var path = redirectedReference.sourceFile.path;
41606             var redirects = redirectsMap.get(path);
41607             if (!redirects) {
41608                 // Reuse map if redirected reference map uses same resolution
41609                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
41610                 redirectsMap.set(path, redirects);
41611             }
41612             return redirects;
41613         }
41614         function clear() {
41615             ownMap.clear();
41616             redirectsMap.clear();
41617         }
41618     }
41619     ts.createCacheWithRedirects = createCacheWithRedirects;
41620     function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) {
41621         var cache;
41622         return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries };
41623         function getPackageJsonInfo(packageJsonPath) {
41624             return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
41625         }
41626         function setPackageJsonInfo(packageJsonPath, info) {
41627             (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info);
41628         }
41629         function clear() {
41630             cache = undefined;
41631         }
41632         function entries() {
41633             var iter = cache === null || cache === void 0 ? void 0 : cache.entries();
41634             return iter ? ts.arrayFrom(iter) : [];
41635         }
41636     }
41637     function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
41638         var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
41639         var result = cache.get(key);
41640         if (!result) {
41641             result = create();
41642             cache.set(key, result);
41643         }
41644         return result;
41645     }
41646     function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) {
41647         if (!options.configFile)
41648             return;
41649         if (directoryToModuleNameMap.redirectsMap.size === 0) {
41650             // The own map will be for projectCompilerOptions
41651             ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0);
41652             ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0);
41653             ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0);
41654             directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap());
41655             moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap());
41656         }
41657         else {
41658             // Set correct own map
41659             ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0);
41660             var ref = {
41661                 sourceFile: options.configFile,
41662                 commandLine: { options: options }
41663             };
41664             directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
41665             moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
41666         }
41667         directoryToModuleNameMap.setOwnOptions(options);
41668         moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options);
41669     }
41670     function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) {
41671         return {
41672             getOrCreateCacheForDirectory: getOrCreateCacheForDirectory,
41673             clear: clear,
41674             update: update,
41675         };
41676         function clear() {
41677             directoryToModuleNameMap.clear();
41678         }
41679         function update(options) {
41680             updateRedirectsMap(options, directoryToModuleNameMap);
41681         }
41682         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
41683             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
41684             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return createModeAwareCache(); });
41685         }
41686     }
41687     /* @internal */
41688     function createModeAwareCache() {
41689         var underlying = new ts.Map();
41690         var memoizedReverseKeys = new ts.Map();
41691         var cache = {
41692             get: function (specifier, mode) {
41693                 return underlying.get(getUnderlyingCacheKey(specifier, mode));
41694             },
41695             set: function (specifier, mode, value) {
41696                 underlying.set(getUnderlyingCacheKey(specifier, mode), value);
41697                 return cache;
41698             },
41699             delete: function (specifier, mode) {
41700                 underlying.delete(getUnderlyingCacheKey(specifier, mode));
41701                 return cache;
41702             },
41703             has: function (specifier, mode) {
41704                 return underlying.has(getUnderlyingCacheKey(specifier, mode));
41705             },
41706             forEach: function (cb) {
41707                 return underlying.forEach(function (elem, key) {
41708                     var _a = memoizedReverseKeys.get(key), specifier = _a[0], mode = _a[1];
41709                     return cb(elem, specifier, mode);
41710                 });
41711             },
41712             size: function () {
41713                 return underlying.size;
41714             }
41715         };
41716         return cache;
41717         function getUnderlyingCacheKey(specifier, mode) {
41718             var result = mode === undefined ? specifier : "".concat(mode, "|").concat(specifier);
41719             memoizedReverseKeys.set(result, [specifier, mode]);
41720             return result;
41721         }
41722     }
41723     ts.createModeAwareCache = createModeAwareCache;
41724     /* @internal */
41725     function zipToModeAwareCache(file, keys, values) {
41726         ts.Debug.assert(keys.length === values.length);
41727         var map = createModeAwareCache();
41728         for (var i = 0; i < keys.length; ++i) {
41729             map.set(keys[i], ts.getModeForResolutionAtIndex(file, i), values[i]);
41730         }
41731         return map;
41732     }
41733     ts.zipToModeAwareCache = zipToModeAwareCache;
41734     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) {
41735         var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options)));
41736         moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options));
41737         var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName);
41738         return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } });
41739         function clear() {
41740             preDirectoryResolutionCache.clear();
41741             moduleNameToDirectoryMap.clear();
41742             packageJsonInfoCache.clear();
41743         }
41744         function update(options) {
41745             updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap);
41746         }
41747         function getOrCreateCacheForModuleName(nonRelativeModuleName, mode, redirectedReference) {
41748             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
41749             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, mode === undefined ? nonRelativeModuleName : "".concat(mode, "|").concat(nonRelativeModuleName), createPerModuleNameCache);
41750         }
41751         function createPerModuleNameCache() {
41752             var directoryPathMap = new ts.Map();
41753             return { get: get, set: set };
41754             function get(directory) {
41755                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
41756             }
41757             /**
41758              * At first this function add entry directory -> module resolution result to the table.
41759              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
41760              * and for every parent folder in set it adds entry: parent -> module resolution. .
41761              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
41762              * Set of parent folders that should have the same result will be:
41763              * [
41764              *     /a/b/c/d, /a/b/c, /a/b
41765              * ]
41766              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
41767              */
41768             function set(directory, result) {
41769                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
41770                 // if entry is already in cache do nothing
41771                 if (directoryPathMap.has(path)) {
41772                     return;
41773                 }
41774                 directoryPathMap.set(path, result);
41775                 var resolvedFileName = result.resolvedModule &&
41776                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
41777                 // find common prefix between directory and resolved file name
41778                 // this common prefix should be the shortest path that has the same resolution
41779                 // directory: /a/b/c/d/e
41780                 // resolvedFileName: /a/b/foo.d.ts
41781                 // commonPrefix: /a/b
41782                 // for failed lookups cache the result for every directory up to root
41783                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
41784                 var current = path;
41785                 while (current !== commonPrefix) {
41786                     var parent = ts.getDirectoryPath(current);
41787                     if (parent === current || directoryPathMap.has(parent)) {
41788                         break;
41789                     }
41790                     directoryPathMap.set(parent, result);
41791                     current = parent;
41792                 }
41793             }
41794             function getCommonPrefix(directory, resolution) {
41795                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
41796                 // find first position where directory and resolution differs
41797                 var i = 0;
41798                 var limit = Math.min(directory.length, resolutionDirectory.length);
41799                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
41800                     i++;
41801                 }
41802                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
41803                     return directory;
41804                 }
41805                 var rootLength = ts.getRootLength(directory);
41806                 if (i < rootLength) {
41807                     return undefined;
41808                 }
41809                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
41810                 if (sep === -1) {
41811                     return undefined;
41812                 }
41813                 return directory.substr(0, Math.max(sep, rootLength));
41814             }
41815         }
41816     }
41817     ts.createModuleResolutionCache = createModuleResolutionCache;
41818     function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) {
41819         var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options)));
41820         packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName));
41821         return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear });
41822         function clear() {
41823             preDirectoryResolutionCache.clear();
41824             packageJsonInfoCache.clear();
41825         }
41826     }
41827     ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache;
41828     function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) {
41829         var containingDirectory = ts.getDirectoryPath(containingFile);
41830         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
41831         if (!perFolderCache)
41832             return undefined;
41833         return perFolderCache.get(moduleName, mode);
41834     }
41835     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
41836     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
41837         var traceEnabled = isTraceEnabled(compilerOptions, host);
41838         if (redirectedReference) {
41839             compilerOptions = redirectedReference.commandLine.options;
41840         }
41841         if (traceEnabled) {
41842             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
41843             if (redirectedReference) {
41844                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
41845             }
41846         }
41847         var containingDirectory = ts.getDirectoryPath(containingFile);
41848         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
41849         var result = perFolderCache && perFolderCache.get(moduleName, resolutionMode);
41850         if (result) {
41851             if (traceEnabled) {
41852                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
41853             }
41854         }
41855         else {
41856             var moduleResolution = compilerOptions.moduleResolution;
41857             if (moduleResolution === undefined) {
41858                 switch (ts.getEmitModuleKind(compilerOptions)) {
41859                     case ts.ModuleKind.CommonJS:
41860                         moduleResolution = ts.ModuleResolutionKind.NodeJs;
41861                         break;
41862                     case ts.ModuleKind.Node12:
41863                         moduleResolution = ts.ModuleResolutionKind.Node12;
41864                         break;
41865                     case ts.ModuleKind.NodeNext:
41866                         moduleResolution = ts.ModuleResolutionKind.NodeNext;
41867                         break;
41868                     default:
41869                         moduleResolution = ts.ModuleResolutionKind.Classic;
41870                         break;
41871                 }
41872                 if (traceEnabled) {
41873                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
41874                 }
41875             }
41876             else {
41877                 if (traceEnabled) {
41878                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
41879                 }
41880             }
41881             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
41882             switch (moduleResolution) {
41883                 case ts.ModuleResolutionKind.Node12:
41884                     result = node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
41885                     break;
41886                 case ts.ModuleResolutionKind.NodeNext:
41887                     result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
41888                     break;
41889                 case ts.ModuleResolutionKind.NodeJs:
41890                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
41891                     break;
41892                 case ts.ModuleResolutionKind.Classic:
41893                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
41894                     break;
41895                 default:
41896                     return ts.Debug.fail("Unexpected moduleResolution: ".concat(moduleResolution));
41897             }
41898             if (result && result.resolvedModule)
41899                 ts.perfLogger.logInfoEvent("Module \"".concat(moduleName, "\" resolved to \"").concat(result.resolvedModule.resolvedFileName, "\""));
41900             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
41901             if (perFolderCache) {
41902                 perFolderCache.set(moduleName, resolutionMode, result);
41903                 if (!ts.isExternalModuleNameRelative(moduleName)) {
41904                     // put result in per-module name cache
41905                     cache.getOrCreateCacheForModuleName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result);
41906                 }
41907             }
41908         }
41909         if (traceEnabled) {
41910             if (result.resolvedModule) {
41911                 if (result.resolvedModule.packageId) {
41912                     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));
41913                 }
41914                 else {
41915                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
41916                 }
41917             }
41918             else {
41919                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
41920             }
41921         }
41922         return result;
41923     }
41924     ts.resolveModuleName = resolveModuleName;
41925     /**
41926      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
41927      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
41928      * can be resolved successfully by TypeScript compiler and runtime module loader.
41929      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
41930      * fallback to standard resolution routine.
41931      *
41932      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
41933      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
41934      * be '/a/b/c/d'
41935      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
41936      * will be resolved based on the content of the module name.
41937      * Structure of 'paths' compiler options
41938      * 'paths': {
41939      *    pattern-1: [...substitutions],
41940      *    pattern-2: [...substitutions],
41941      *    ...
41942      *    pattern-n: [...substitutions]
41943      * }
41944      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
41945      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
41946      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
41947      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
41948      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
41949      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
41950      * from the candidate location.
41951      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
41952      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
41953      * will be converted to absolute using baseUrl.
41954      * For example:
41955      * baseUrl: /a/b/c
41956      * "paths": {
41957      *     // match all module names
41958      *     "*": [
41959      *         "*",        // use matched name as is,
41960      *                     // <matched name> will be looked as /a/b/c/<matched name>
41961      *
41962      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
41963      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
41964      *     ],
41965      *     // match module names that start with 'components/'
41966      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
41967      *                                              // it is rooted so it will be final candidate location
41968      * }
41969      *
41970      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
41971      * they were in the same location. For example lets say there are two files
41972      * '/local/src/content/file1.ts'
41973      * '/shared/components/contracts/src/content/protocols/file2.ts'
41974      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
41975      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
41976      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
41977      * root dirs were merged together.
41978      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
41979      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
41980      * '/local/src/content/protocols/file2' and try to load it - failure.
41981      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
41982      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
41983      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
41984      */
41985     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
41986         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
41987         if (resolved)
41988             return resolved.value;
41989         if (!ts.isExternalModuleNameRelative(moduleName)) {
41990             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
41991         }
41992         else {
41993             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
41994         }
41995     }
41996     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
41997         var _a;
41998         var _b = state.compilerOptions, baseUrl = _b.baseUrl, paths = _b.paths, configFile = _b.configFile;
41999         if (paths && !ts.pathIsRelative(moduleName)) {
42000             if (state.traceEnabled) {
42001                 if (baseUrl) {
42002                     trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
42003                 }
42004                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
42005             }
42006             var baseDirectory = ts.getPathsBasePath(state.compilerOptions, state.host); // Always defined when 'paths' is defined
42007             var pathPatterns = (configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) ? (_a = configFile.configFileSpecs).pathPatterns || (_a.pathPatterns = ts.tryParsePatterns(paths)) : undefined;
42008             return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, /*onlyRecordFailures*/ false, state);
42009         }
42010     }
42011     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
42012         if (!state.compilerOptions.rootDirs) {
42013             return undefined;
42014         }
42015         if (state.traceEnabled) {
42016             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
42017         }
42018         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
42019         var matchedRootDir;
42020         var matchedNormalizedPrefix;
42021         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
42022             var rootDir = _a[_i];
42023             // rootDirs are expected to be absolute
42024             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
42025             // using location of tsconfig.json as base location
42026             var normalizedRoot = ts.normalizePath(rootDir);
42027             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
42028                 normalizedRoot += ts.directorySeparator;
42029             }
42030             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
42031                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
42032             if (state.traceEnabled) {
42033                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
42034             }
42035             if (isLongestMatchingPrefix) {
42036                 matchedNormalizedPrefix = normalizedRoot;
42037                 matchedRootDir = rootDir;
42038             }
42039         }
42040         if (matchedNormalizedPrefix) {
42041             if (state.traceEnabled) {
42042                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
42043             }
42044             var suffix = candidate.substr(matchedNormalizedPrefix.length);
42045             // first - try to load from a initial location
42046             if (state.traceEnabled) {
42047                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
42048             }
42049             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
42050             if (resolvedFileName) {
42051                 return resolvedFileName;
42052             }
42053             if (state.traceEnabled) {
42054                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
42055             }
42056             // then try to resolve using remaining entries in rootDirs
42057             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
42058                 var rootDir = _c[_b];
42059                 if (rootDir === matchedRootDir) {
42060                     // skip the initially matched entry
42061                     continue;
42062                 }
42063                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
42064                 if (state.traceEnabled) {
42065                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
42066                 }
42067                 var baseDirectory = ts.getDirectoryPath(candidate_1);
42068                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
42069                 if (resolvedFileName_1) {
42070                     return resolvedFileName_1;
42071                 }
42072             }
42073             if (state.traceEnabled) {
42074                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
42075             }
42076         }
42077         return undefined;
42078     }
42079     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
42080         var baseUrl = state.compilerOptions.baseUrl;
42081         if (!baseUrl) {
42082             return undefined;
42083         }
42084         if (state.traceEnabled) {
42085             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
42086         }
42087         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
42088         if (state.traceEnabled) {
42089             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
42090         }
42091         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
42092     }
42093     /**
42094      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
42095      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
42096      * Throws an error if the module can't be resolved.
42097      */
42098     /* @internal */
42099     function resolveJSModule(moduleName, initialDir, host) {
42100         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
42101         if (!resolvedModule) {
42102             throw new Error("Could not resolve JS module '".concat(moduleName, "' starting at '").concat(initialDir, "'. Looked in: ").concat(failedLookupLocations.join(", ")));
42103         }
42104         return resolvedModule.resolvedFileName;
42105     }
42106     ts.resolveJSModule = resolveJSModule;
42107     /* @internal */
42108     function tryResolveJSModule(moduleName, initialDir, host) {
42109         return tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
42110     }
42111     ts.tryResolveJSModule = tryResolveJSModule;
42112     /* @internal */
42113     var NodeResolutionFeatures;
42114     (function (NodeResolutionFeatures) {
42115         NodeResolutionFeatures[NodeResolutionFeatures["None"] = 0] = "None";
42116         // resolving `#local` names in your own package.json
42117         NodeResolutionFeatures[NodeResolutionFeatures["Imports"] = 2] = "Imports";
42118         // resolving `your-own-name` from your own package.json
42119         NodeResolutionFeatures[NodeResolutionFeatures["SelfName"] = 4] = "SelfName";
42120         // respecting the `.exports` member of packages' package.json files and its (conditional) mappings of export names
42121         NodeResolutionFeatures[NodeResolutionFeatures["Exports"] = 8] = "Exports";
42122         // allowing `*` in the LHS of an export to be followed by more content, eg `"./whatever/*.js"`
42123         // not currently backported to node 12 - https://github.com/nodejs/Release/issues/690
42124         NodeResolutionFeatures[NodeResolutionFeatures["ExportsPatternTrailers"] = 16] = "ExportsPatternTrailers";
42125         NodeResolutionFeatures[NodeResolutionFeatures["AllFeatures"] = 30] = "AllFeatures";
42126         NodeResolutionFeatures[NodeResolutionFeatures["EsmMode"] = 32] = "EsmMode";
42127     })(NodeResolutionFeatures || (NodeResolutionFeatures = {}));
42128     function node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
42129         return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Imports | NodeResolutionFeatures.SelfName | NodeResolutionFeatures.Exports, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
42130     }
42131     function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
42132         return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.AllFeatures, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
42133     }
42134     function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
42135         var containingDirectory = ts.getDirectoryPath(containingFile);
42136         // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features
42137         var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0;
42138         return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference);
42139     }
42140     var jsOnlyExtensions = [Extensions.JavaScript];
42141     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
42142     var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false);
42143     var tsconfigExtensions = [Extensions.TSConfig];
42144     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
42145         return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
42146     }
42147     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
42148         return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
42149     }
42150     ts.nodeModuleNameResolver = nodeModuleNameResolver;
42151     function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
42152         var _a, _b;
42153         var traceEnabled = isTraceEnabled(compilerOptions, host);
42154         var failedLookupLocations = [];
42155         // conditions are only used by the node12/nodenext resolver - there's no priority order in the list,
42156         //it's essentially a set (priority is determined by object insertion order in the object we look at).
42157         var state = {
42158             compilerOptions: compilerOptions,
42159             host: host,
42160             traceEnabled: traceEnabled,
42161             failedLookupLocations: failedLookupLocations,
42162             packageJsonInfoCache: cache,
42163             features: features,
42164             conditions: features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]
42165         };
42166         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
42167         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);
42168         function tryResolve(extensions) {
42169             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
42170             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
42171             if (resolved) {
42172                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
42173             }
42174             if (!ts.isExternalModuleNameRelative(moduleName)) {
42175                 var resolved_1;
42176                 if (features & NodeResolutionFeatures.Imports && ts.startsWith(moduleName, "#")) {
42177                     resolved_1 = loadModuleFromImports(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
42178                 }
42179                 if (!resolved_1 && features & NodeResolutionFeatures.SelfName) {
42180                     resolved_1 = loadModuleFromSelfNameReference(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
42181                 }
42182                 if (!resolved_1) {
42183                     if (traceEnabled) {
42184                         trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
42185                     }
42186                     resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
42187                 }
42188                 if (!resolved_1)
42189                     return undefined;
42190                 var resolvedValue = resolved_1.value;
42191                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
42192                     var path = realPath(resolvedValue.path, host, traceEnabled);
42193                     var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path;
42194                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
42195                 }
42196                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
42197                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
42198             }
42199             else {
42200                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
42201                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
42202                 // Treat explicit "node_modules" import as an external library import.
42203                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
42204             }
42205         }
42206     }
42207     function realPath(path, host, traceEnabled) {
42208         if (!host.realpath) {
42209             return path;
42210         }
42211         var real = ts.normalizePath(host.realpath(path));
42212         if (traceEnabled) {
42213             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
42214         }
42215         ts.Debug.assert(host.fileExists(real), "".concat(path, " linked to nonexistent file ").concat(real));
42216         return real;
42217     }
42218     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
42219         if (state.traceEnabled) {
42220             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
42221         }
42222         if (!ts.hasTrailingDirectorySeparator(candidate)) {
42223             if (!onlyRecordFailures) {
42224                 var parentOfCandidate = ts.getDirectoryPath(candidate);
42225                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
42226                     if (state.traceEnabled) {
42227                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
42228                     }
42229                     onlyRecordFailures = true;
42230                 }
42231             }
42232             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
42233             if (resolvedFromFile) {
42234                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined;
42235                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
42236                 return withPackageId(packageInfo, resolvedFromFile);
42237             }
42238         }
42239         if (!onlyRecordFailures) {
42240             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
42241             if (!candidateExists) {
42242                 if (state.traceEnabled) {
42243                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
42244                 }
42245                 onlyRecordFailures = true;
42246             }
42247         }
42248         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
42249     }
42250     /*@internal*/
42251     ts.nodeModulesPathPart = "/node_modules/";
42252     /*@internal*/
42253     function pathContainsNodeModules(path) {
42254         return ts.stringContains(path, ts.nodeModulesPathPart);
42255     }
42256     ts.pathContainsNodeModules = pathContainsNodeModules;
42257     /**
42258      * This will be called on the successfully resolved path from `loadModuleFromFile`.
42259      * (Not needed for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
42260      *
42261      * packageDirectory is the directory of the package itself.
42262      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
42263      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
42264      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
42265      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
42266      */
42267     /* @internal */
42268     function parseNodeModuleFromPath(resolved) {
42269         var path = ts.normalizePath(resolved);
42270         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
42271         if (idx === -1) {
42272             return undefined;
42273         }
42274         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
42275         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
42276         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
42277             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
42278         }
42279         return path.slice(0, indexAfterPackageName);
42280     }
42281     ts.parseNodeModuleFromPath = parseNodeModuleFromPath;
42282     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
42283         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
42284         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
42285     }
42286     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
42287         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
42288     }
42289     /**
42290      * @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
42291      * 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.
42292      */
42293     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
42294         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
42295             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
42296             var extension = extensionLess ? candidate.substring(extensionLess.length) : "";
42297             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, extension, onlyRecordFailures, state);
42298         }
42299         // esm mode resolutions don't include automatic extension lookup (without additional flags, at least)
42300         if (!(state.features & NodeResolutionFeatures.EsmMode)) {
42301             // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
42302             var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, "", onlyRecordFailures, state);
42303             if (resolvedByAddingExtension) {
42304                 return resolvedByAddingExtension;
42305             }
42306         }
42307         return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
42308     }
42309     function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) {
42310         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
42311         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
42312         if (ts.hasJSFileExtension(candidate) || (ts.fileExtensionIs(candidate, ".json" /* Json */) && state.compilerOptions.resolveJsonModule)) {
42313             var extensionless = ts.removeFileExtension(candidate);
42314             var extension = candidate.substring(extensionless.length);
42315             if (state.traceEnabled) {
42316                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
42317             }
42318             return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state);
42319         }
42320     }
42321     function loadJSOrExactTSFileName(extensions, candidate, onlyRecordFailures, state) {
42322         if ((extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) && ts.fileExtensionIsOneOf(candidate, [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */])) {
42323             var result = tryFile(candidate, onlyRecordFailures, state);
42324             return result !== undefined ? { path: candidate, ext: ts.forEach([".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */], function (e) { return ts.fileExtensionIs(candidate, e) ? e : undefined; }) } : undefined;
42325         }
42326         return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
42327     }
42328     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
42329     function tryAddingExtensions(candidate, extensions, originalExtension, onlyRecordFailures, state) {
42330         if (!onlyRecordFailures) {
42331             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
42332             var directory = ts.getDirectoryPath(candidate);
42333             if (directory) {
42334                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
42335             }
42336         }
42337         switch (extensions) {
42338             case Extensions.DtsOnly:
42339                 switch (originalExtension) {
42340                     case ".mjs" /* Mjs */:
42341                     case ".mts" /* Mts */:
42342                     case ".d.mts" /* Dmts */:
42343                         return tryExtension(".d.mts" /* Dmts */);
42344                     case ".cjs" /* Cjs */:
42345                     case ".cts" /* Cts */:
42346                     case ".d.cts" /* Dcts */:
42347                         return tryExtension(".d.cts" /* Dcts */);
42348                     case ".json" /* Json */:
42349                         candidate += ".json" /* Json */;
42350                         return tryExtension(".d.ts" /* Dts */);
42351                     default: return tryExtension(".d.ts" /* Dts */);
42352                 }
42353             case Extensions.TypeScript:
42354                 switch (originalExtension) {
42355                     case ".mjs" /* Mjs */:
42356                     case ".mts" /* Mts */:
42357                     case ".d.mts" /* Dmts */:
42358                         return tryExtension(".mts" /* Mts */) || tryExtension(".d.mts" /* Dmts */);
42359                     case ".cjs" /* Cjs */:
42360                     case ".cts" /* Cts */:
42361                     case ".d.cts" /* Dcts */:
42362                         return tryExtension(".cts" /* Cts */) || tryExtension(".d.cts" /* Dcts */);
42363                     case ".json" /* Json */:
42364                         candidate += ".json" /* Json */;
42365                         return tryExtension(".d.ts" /* Dts */);
42366                     default:
42367                         return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
42368                 }
42369             case Extensions.JavaScript:
42370                 switch (originalExtension) {
42371                     case ".mjs" /* Mjs */:
42372                     case ".mts" /* Mts */:
42373                     case ".d.mts" /* Dmts */:
42374                         return tryExtension(".mjs" /* Mjs */);
42375                     case ".cjs" /* Cjs */:
42376                     case ".cts" /* Cts */:
42377                     case ".d.cts" /* Dcts */:
42378                         return tryExtension(".cjs" /* Cjs */);
42379                     case ".json" /* Json */:
42380                         return tryExtension(".json" /* Json */);
42381                     default:
42382                         return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
42383                 }
42384             case Extensions.TSConfig:
42385             case Extensions.Json:
42386                 return tryExtension(".json" /* Json */);
42387         }
42388         function tryExtension(ext) {
42389             var path = tryFile(candidate + ext, onlyRecordFailures, state);
42390             return path === undefined ? undefined : { path: path, ext: ext };
42391         }
42392     }
42393     /** Return the file if it exists. */
42394     function tryFile(fileName, onlyRecordFailures, state) {
42395         if (!onlyRecordFailures) {
42396             if (state.host.fileExists(fileName)) {
42397                 if (state.traceEnabled) {
42398                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
42399                 }
42400                 return fileName;
42401             }
42402             else {
42403                 if (state.traceEnabled) {
42404                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
42405                 }
42406             }
42407         }
42408         state.failedLookupLocations.push(fileName);
42409         return undefined;
42410     }
42411     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
42412         if (considerPackageJson === void 0) { considerPackageJson = true; }
42413         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
42414         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
42415         var versionPaths = packageInfo && packageInfo.versionPaths;
42416         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
42417     }
42418     /**
42419      * A function for locating the package.json scope for a given path
42420      */
42421     /*@internal*/
42422     function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) {
42423         var state = {
42424             host: host,
42425             compilerOptions: options,
42426             traceEnabled: isTraceEnabled(options, host),
42427             failedLookupLocations: [],
42428             packageJsonInfoCache: packageJsonInfoCache,
42429             features: 0,
42430             conditions: [],
42431         };
42432         var parts = ts.getPathComponents(fileName);
42433         parts.pop();
42434         while (parts.length > 0) {
42435             var pkg = getPackageJsonInfo(ts.getPathFromPathComponents(parts), /*onlyRecordFailures*/ false, state);
42436             if (pkg) {
42437                 return pkg;
42438             }
42439             parts.pop();
42440         }
42441         return undefined;
42442     }
42443     ts.getPackageScopeForPath = getPackageScopeForPath;
42444     /*@internal*/
42445     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
42446         var _a, _b, _c;
42447         var host = state.host, traceEnabled = state.traceEnabled;
42448         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
42449         if (onlyRecordFailures) {
42450             state.failedLookupLocations.push(packageJsonPath);
42451             return undefined;
42452         }
42453         var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath);
42454         if (existing !== undefined) {
42455             if (typeof existing !== "boolean") {
42456                 if (traceEnabled)
42457                     trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
42458                 return existing;
42459             }
42460             else {
42461                 if (existing && traceEnabled)
42462                     trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath);
42463                 state.failedLookupLocations.push(packageJsonPath);
42464                 return undefined;
42465             }
42466         }
42467         var directoryExists = ts.directoryProbablyExists(packageDirectory, host);
42468         if (directoryExists && host.fileExists(packageJsonPath)) {
42469             var packageJsonContent = ts.readJson(packageJsonPath, host);
42470             if (traceEnabled) {
42471                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
42472             }
42473             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
42474             var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
42475             (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
42476             return result;
42477         }
42478         else {
42479             if (directoryExists && traceEnabled) {
42480                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
42481             }
42482             (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists);
42483             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
42484             state.failedLookupLocations.push(packageJsonPath);
42485         }
42486     }
42487     ts.getPackageJsonInfo = getPackageJsonInfo;
42488     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
42489         var packageFile;
42490         if (jsonContent) {
42491             switch (extensions) {
42492                 case Extensions.JavaScript:
42493                 case Extensions.Json:
42494                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
42495                     break;
42496                 case Extensions.TypeScript:
42497                     // When resolving typescript modules, try resolving using main field as well
42498                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
42499                     break;
42500                 case Extensions.DtsOnly:
42501                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
42502                     break;
42503                 case Extensions.TSConfig:
42504                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
42505                     break;
42506                 default:
42507                     return ts.Debug.assertNever(extensions);
42508             }
42509         }
42510         var loader = function (extensions, candidate, onlyRecordFailures, state) {
42511             var fromFile = tryFile(candidate, onlyRecordFailures, state);
42512             if (fromFile) {
42513                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
42514                 if (resolved) {
42515                     return noPackageId(resolved);
42516                 }
42517                 if (state.traceEnabled) {
42518                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
42519                 }
42520             }
42521             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
42522             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
42523             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
42524             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
42525         };
42526         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
42527         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
42528         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
42529         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
42530             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
42531             if (state.traceEnabled) {
42532                 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);
42533             }
42534             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, /*pathPatterns*/ undefined, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
42535             if (result) {
42536                 return removeIgnoredPackageId(result.value);
42537             }
42538         }
42539         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
42540         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
42541         if (packageFileResult)
42542             return packageFileResult;
42543         // esm mode resolutions don't do package `index` lookups
42544         if (!(state.features & NodeResolutionFeatures.EsmMode)) {
42545             return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
42546         }
42547     }
42548     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
42549     function resolvedIfExtensionMatches(extensions, path) {
42550         var ext = ts.tryGetExtensionFromPath(path);
42551         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
42552     }
42553     /** True if `extension` is one of the supported `extensions`. */
42554     function extensionIsOk(extensions, extension) {
42555         switch (extensions) {
42556             case Extensions.JavaScript:
42557                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
42558             case Extensions.TSConfig:
42559             case Extensions.Json:
42560                 return extension === ".json" /* Json */;
42561             case Extensions.TypeScript:
42562                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
42563             case Extensions.DtsOnly:
42564                 return extension === ".d.ts" /* Dts */;
42565         }
42566     }
42567     /* @internal */
42568     function parsePackageName(moduleName) {
42569         var idx = moduleName.indexOf(ts.directorySeparator);
42570         if (moduleName[0] === "@") {
42571             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
42572         }
42573         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
42574     }
42575     ts.parsePackageName = parsePackageName;
42576     /* @internal */
42577     function allKeysStartWithDot(obj) {
42578         return ts.every(ts.getOwnKeys(obj), function (k) { return ts.startsWith(k, "."); });
42579     }
42580     ts.allKeysStartWithDot = allKeysStartWithDot;
42581     function noKeyStartsWithDot(obj) {
42582         return !ts.some(ts.getOwnKeys(obj), function (k) { return ts.startsWith(k, "."); });
42583     }
42584     function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
42585         var _a, _b;
42586         var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
42587         var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
42588         var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions);
42589         if (!scope || !scope.packageJsonContent.exports) {
42590             return undefined;
42591         }
42592         if (typeof scope.packageJsonContent.name !== "string") {
42593             return undefined;
42594         }
42595         var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
42596         var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
42597         if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
42598             return undefined;
42599         }
42600         var trailingParts = parts.slice(nameParts.length);
42601         return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
42602     }
42603     function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
42604         if (!scope.packageJsonContent.exports) {
42605             return undefined;
42606         }
42607         if (subpath === ".") {
42608             var mainExport = void 0;
42609             if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
42610                 mainExport = scope.packageJsonContent.exports;
42611             }
42612             else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
42613                 mainExport = scope.packageJsonContent.exports["."];
42614             }
42615             if (mainExport) {
42616                 var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
42617                 return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
42618             }
42619         }
42620         else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
42621             if (typeof scope.packageJsonContent.exports !== "object") {
42622                 if (state.traceEnabled) {
42623                     trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
42624                 }
42625                 return toSearchResult(/*value*/ undefined);
42626             }
42627             var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
42628             if (result) {
42629                 return result;
42630             }
42631         }
42632         if (state.traceEnabled) {
42633             trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
42634         }
42635         return toSearchResult(/*value*/ undefined);
42636     }
42637     function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) {
42638         var _a, _b;
42639         if (moduleName === "#" || ts.startsWith(moduleName, "#/")) {
42640             if (state.traceEnabled) {
42641                 trace(state.host, ts.Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName);
42642             }
42643             return toSearchResult(/*value*/ undefined);
42644         }
42645         var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
42646         var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
42647         var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions);
42648         if (!scope) {
42649             if (state.traceEnabled) {
42650                 trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath);
42651             }
42652             return toSearchResult(/*value*/ undefined);
42653         }
42654         if (!scope.packageJsonContent.imports) {
42655             if (state.traceEnabled) {
42656                 trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
42657             }
42658             return toSearchResult(/*value*/ undefined);
42659         }
42660         var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
42661         if (result) {
42662             return result;
42663         }
42664         if (state.traceEnabled) {
42665             trace(state.host, ts.Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory);
42666         }
42667         return toSearchResult(/*value*/ undefined);
42668     }
42669     function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) {
42670         var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
42671         if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) {
42672             var target = lookupTable[moduleName];
42673             return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false);
42674         }
42675         var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; });
42676         for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) {
42677             var potentialTarget = expandingKeys_1[_i];
42678             if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) {
42679                 var target = lookupTable[potentialTarget];
42680                 var starPos = potentialTarget.indexOf("*");
42681                 var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos));
42682                 return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true);
42683             }
42684             else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) {
42685                 var target = lookupTable[potentialTarget];
42686                 var subpath = moduleName.substring(potentialTarget.length - 1);
42687                 return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true);
42688             }
42689             else if (ts.startsWith(moduleName, potentialTarget)) {
42690                 var target = lookupTable[potentialTarget];
42691                 var subpath = moduleName.substring(potentialTarget.length);
42692                 return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false);
42693             }
42694         }
42695         function matchesPatternWithTrailer(target, name) {
42696             if (ts.endsWith(target, "*"))
42697                 return false; // handled by next case in loop
42698             var starPos = target.indexOf("*");
42699             if (starPos === -1)
42700                 return false; // handled by last case in loop
42701             return ts.startsWith(name, target.substring(0, starPos)) && ts.endsWith(name, target.substring(starPos + 1));
42702         }
42703     }
42704     /**
42705      * Gets the self-recursive function specialized to retrieving the targeted import/export element for the given resolution configuration
42706      */
42707     function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) {
42708         return loadModuleFromTargetImportOrExport;
42709         function loadModuleFromTargetImportOrExport(target, subpath, pattern) {
42710             var _a, _b;
42711             if (typeof target === "string") {
42712                 if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) {
42713                     if (state.traceEnabled) {
42714                         trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42715                     }
42716                     return toSearchResult(/*value*/ undefined);
42717                 }
42718                 if (!ts.startsWith(target, "./")) {
42719                     if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) {
42720                         var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath;
42721                         var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference);
42722                         return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined);
42723                     }
42724                     if (state.traceEnabled) {
42725                         trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42726                     }
42727                     return toSearchResult(/*value*/ undefined);
42728                 }
42729                 var parts = ts.pathIsRelative(target) ? ts.getPathComponents(target).slice(1) : ts.getPathComponents(target);
42730                 var partsAfterFirst = parts.slice(1);
42731                 if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
42732                     if (state.traceEnabled) {
42733                         trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42734                     }
42735                     return toSearchResult(/*value*/ undefined);
42736                 }
42737                 var resolvedTarget = ts.combinePaths(scope.packageDirectory, target);
42738                 // TODO: Assert that `resolvedTarget` is actually within the package directory? That's what the spec says.... but I'm not sure we need
42739                 // to be in the business of validating everyone's import and export map correctness.
42740                 var subpathParts = ts.getPathComponents(subpath);
42741                 if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) {
42742                     if (state.traceEnabled) {
42743                         trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42744                     }
42745                     return toSearchResult(/*value*/ undefined);
42746                 }
42747                 var finalPath = ts.getNormalizedAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
42748                 return toSearchResult(withPackageId(scope, loadJSOrExactTSFileName(extensions, finalPath, /*onlyRecordFailures*/ false, state)));
42749             }
42750             else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null
42751                 if (!Array.isArray(target)) {
42752                     for (var _i = 0, _c = ts.getOwnKeys(target); _i < _c.length; _i++) {
42753                         var key = _c[_i];
42754                         if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) {
42755                             var subTarget = target[key];
42756                             var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern);
42757                             if (result) {
42758                                 return result;
42759                             }
42760                         }
42761                     }
42762                     return undefined;
42763                 }
42764                 else {
42765                     if (!ts.length(target)) {
42766                         if (state.traceEnabled) {
42767                             trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42768                         }
42769                         return toSearchResult(/*value*/ undefined);
42770                     }
42771                     for (var _d = 0, target_1 = target; _d < target_1.length; _d++) {
42772                         var elem = target_1[_d];
42773                         var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern);
42774                         if (result) {
42775                             return result;
42776                         }
42777                     }
42778                 }
42779             }
42780             else if (target === null) { // eslint-disable-line no-null/no-null
42781                 if (state.traceEnabled) {
42782                     trace(state.host, ts.Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName);
42783                 }
42784                 return toSearchResult(/*value*/ undefined);
42785             }
42786             if (state.traceEnabled) {
42787                 trace(state.host, ts.Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
42788             }
42789             return toSearchResult(/*value*/ undefined);
42790         }
42791     }
42792     /* @internal */
42793     function isApplicableVersionedTypesKey(conditions, key) {
42794         if (conditions.indexOf("types") === -1)
42795             return false; // only apply versioned types conditions if the types condition is applied
42796         if (!ts.startsWith(key, "types@"))
42797             return false;
42798         var range = ts.VersionRange.tryParse(key.substring("types@".length));
42799         if (!range)
42800             return false;
42801         return range.test(ts.version);
42802     }
42803     ts.isApplicableVersionedTypesKey = isApplicableVersionedTypesKey;
42804     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
42805         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
42806     }
42807     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
42808         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
42809         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
42810     }
42811     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
42812         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, state.features === 0 ? undefined : state.features & NodeResolutionFeatures.EsmMode ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS, redirectedReference);
42813         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
42814             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
42815                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
42816                 if (resolutionFromCache) {
42817                     return resolutionFromCache;
42818                 }
42819                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference));
42820             }
42821         });
42822     }
42823     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
42824         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
42825         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
42826         if (!nodeModulesFolderExists && state.traceEnabled) {
42827             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
42828         }
42829         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state, cache, redirectedReference);
42830         if (packageResult) {
42831             return packageResult;
42832         }
42833         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
42834             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
42835             var nodeModulesAtTypesExists = nodeModulesFolderExists;
42836             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
42837                 if (state.traceEnabled) {
42838                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
42839                 }
42840                 nodeModulesAtTypesExists = false;
42841             }
42842             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state, cache, redirectedReference);
42843         }
42844     }
42845     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) {
42846         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
42847         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
42848         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
42849         // But only if we're not respecting export maps (if we are, we might redirect around this location)
42850         if (!(state.features & NodeResolutionFeatures.Exports)) {
42851             if (packageInfo) {
42852                 var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
42853                 if (fromFile) {
42854                     return noPackageId(fromFile);
42855                 }
42856                 var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
42857                 return withPackageId(packageInfo, fromDirectory);
42858             }
42859         }
42860         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
42861         var loader = function (extensions, candidate, onlyRecordFailures, state) {
42862             var _a;
42863             // package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
42864             if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
42865                 return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
42866             }
42867             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
42868                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
42869             return withPackageId(packageInfo, pathAndExtension);
42870         };
42871         if (rest !== "") { // If "rest" is empty, we just did this search above.
42872             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
42873             // 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.
42874             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
42875             if (packageInfo && packageInfo.versionPaths) {
42876                 if (state.traceEnabled) {
42877                     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);
42878                 }
42879                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
42880                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
42881                 if (fromPaths) {
42882                     return fromPaths.value;
42883                 }
42884             }
42885         }
42886         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
42887     }
42888     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) {
42889         pathPatterns || (pathPatterns = ts.tryParsePatterns(paths));
42890         var matchedPattern = ts.matchPatternOrExact(pathPatterns, moduleName);
42891         if (matchedPattern) {
42892             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
42893             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
42894             if (state.traceEnabled) {
42895                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
42896             }
42897             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
42898                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
42899                 // When baseUrl is not specified, the command line parser resolves relative paths to the config file location.
42900                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
42901                 if (state.traceEnabled) {
42902                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
42903                 }
42904                 // A path mapping may have an extension, in contrast to an import, which should omit it.
42905                 var extension = ts.tryGetExtensionFromPath(subst);
42906                 if (extension !== undefined) {
42907                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
42908                     if (path_1 !== undefined) {
42909                         return noPackageId({ path: path_1, ext: extension });
42910                     }
42911                 }
42912                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
42913             });
42914             return { value: resolved };
42915         }
42916     }
42917     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
42918     var mangledScopedPackageSeparator = "__";
42919     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
42920     function mangleScopedPackageNameWithTrace(packageName, state) {
42921         var mangled = mangleScopedPackageName(packageName);
42922         if (state.traceEnabled && mangled !== packageName) {
42923             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
42924         }
42925         return mangled;
42926     }
42927     /* @internal */
42928     function getTypesPackageName(packageName) {
42929         return "@types/".concat(mangleScopedPackageName(packageName));
42930     }
42931     ts.getTypesPackageName = getTypesPackageName;
42932     /* @internal */
42933     function mangleScopedPackageName(packageName) {
42934         if (ts.startsWith(packageName, "@")) {
42935             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
42936             if (replaceSlash !== packageName) {
42937                 return replaceSlash.slice(1); // Take off the "@"
42938             }
42939         }
42940         return packageName;
42941     }
42942     ts.mangleScopedPackageName = mangleScopedPackageName;
42943     /* @internal */
42944     function getPackageNameFromTypesPackageName(mangledName) {
42945         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
42946         if (withoutAtTypePrefix !== mangledName) {
42947             return unmangleScopedPackageName(withoutAtTypePrefix);
42948         }
42949         return mangledName;
42950     }
42951     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
42952     /* @internal */
42953     function unmangleScopedPackageName(typesPackageName) {
42954         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
42955             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
42956             typesPackageName;
42957     }
42958     ts.unmangleScopedPackageName = unmangleScopedPackageName;
42959     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
42960         var result = cache && cache.get(containingDirectory);
42961         if (result) {
42962             if (state.traceEnabled) {
42963                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
42964             }
42965             state.resultFromCache = result;
42966             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
42967         }
42968     }
42969     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
42970         var traceEnabled = isTraceEnabled(compilerOptions, host);
42971         var failedLookupLocations = [];
42972         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [] };
42973         var containingDirectory = ts.getDirectoryPath(containingFile);
42974         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
42975         // No originalPath because classic resolution doesn't resolve realPath
42976         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
42977         function tryResolve(extensions) {
42978             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
42979             if (resolvedUsingSettings) {
42980                 return { value: resolvedUsingSettings };
42981             }
42982             if (!ts.isExternalModuleNameRelative(moduleName)) {
42983                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, /*mode*/ undefined, redirectedReference);
42984                 // Climb up parent directories looking for a module.
42985                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
42986                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
42987                     if (resolutionFromCache) {
42988                         return resolutionFromCache;
42989                     }
42990                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
42991                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
42992                 });
42993                 if (resolved_3) {
42994                     return resolved_3;
42995                 }
42996                 if (extensions === Extensions.TypeScript) {
42997                     // If we didn't find the file normally, look it up in @types.
42998                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
42999                 }
43000             }
43001             else {
43002                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
43003                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
43004             }
43005         }
43006     }
43007     ts.classicNameResolver = classicNameResolver;
43008     /**
43009      * A host may load a module from a global cache of typings.
43010      * This is the minumum code needed to expose that functionality; the rest is in the host.
43011      */
43012     /* @internal */
43013     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) {
43014         var traceEnabled = isTraceEnabled(compilerOptions, host);
43015         if (traceEnabled) {
43016             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);
43017         }
43018         var failedLookupLocations = [];
43019         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [] };
43020         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined);
43021         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
43022     }
43023     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
43024     /**
43025      * Wraps value to SearchResult.
43026      * @returns undefined if value is undefined or { value } otherwise
43027      */
43028     function toSearchResult(value) {
43029         return value !== undefined ? { value: value } : undefined;
43030     }
43031 })(ts || (ts = {}));
43032 /* @internal */
43033 var ts;
43034 (function (ts) {
43035     var ModuleInstanceState;
43036     (function (ModuleInstanceState) {
43037         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
43038         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
43039         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
43040     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
43041     function getModuleInstanceState(node, visited) {
43042         if (node.body && !node.body.parent) {
43043             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
43044             ts.setParent(node.body, node);
43045             ts.setParentRecursive(node.body, /*incremental*/ false);
43046         }
43047         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
43048     }
43049     ts.getModuleInstanceState = getModuleInstanceState;
43050     function getModuleInstanceStateCached(node, visited) {
43051         if (visited === void 0) { visited = new ts.Map(); }
43052         var nodeId = ts.getNodeId(node);
43053         if (visited.has(nodeId)) {
43054             return visited.get(nodeId) || 0 /* NonInstantiated */;
43055         }
43056         visited.set(nodeId, undefined);
43057         var result = getModuleInstanceStateWorker(node, visited);
43058         visited.set(nodeId, result);
43059         return result;
43060     }
43061     function getModuleInstanceStateWorker(node, visited) {
43062         // A module is uninstantiated if it contains only
43063         switch (node.kind) {
43064             // 1. interface declarations, type alias declarations
43065             case 257 /* InterfaceDeclaration */:
43066             case 258 /* TypeAliasDeclaration */:
43067                 return 0 /* NonInstantiated */;
43068             // 2. const enum declarations
43069             case 259 /* EnumDeclaration */:
43070                 if (ts.isEnumConst(node)) {
43071                     return 2 /* ConstEnumOnly */;
43072                 }
43073                 break;
43074             // 3. non-exported import declarations
43075             case 265 /* ImportDeclaration */:
43076             case 264 /* ImportEqualsDeclaration */:
43077                 if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
43078                     return 0 /* NonInstantiated */;
43079                 }
43080                 break;
43081             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
43082             case 271 /* ExportDeclaration */:
43083                 var exportDeclaration = node;
43084                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 272 /* NamedExports */) {
43085                     var state = 0 /* NonInstantiated */;
43086                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
43087                         var specifier = _a[_i];
43088                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
43089                         if (specifierState > state) {
43090                             state = specifierState;
43091                         }
43092                         if (state === 1 /* Instantiated */) {
43093                             return state;
43094                         }
43095                     }
43096                     return state;
43097                 }
43098                 break;
43099             // 5. other uninstantiated module declarations.
43100             case 261 /* ModuleBlock */: {
43101                 var state_1 = 0 /* NonInstantiated */;
43102                 ts.forEachChild(node, function (n) {
43103                     var childState = getModuleInstanceStateCached(n, visited);
43104                     switch (childState) {
43105                         case 0 /* NonInstantiated */:
43106                             // child is non-instantiated - continue searching
43107                             return;
43108                         case 2 /* ConstEnumOnly */:
43109                             // child is const enum only - record state and continue searching
43110                             state_1 = 2 /* ConstEnumOnly */;
43111                             return;
43112                         case 1 /* Instantiated */:
43113                             // child is instantiated - record state and stop
43114                             state_1 = 1 /* Instantiated */;
43115                             return true;
43116                         default:
43117                             ts.Debug.assertNever(childState);
43118                     }
43119                 });
43120                 return state_1;
43121             }
43122             case 260 /* ModuleDeclaration */:
43123                 return getModuleInstanceState(node, visited);
43124             case 79 /* Identifier */:
43125                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
43126                 // be considered the same as type alias
43127                 if (node.isInJSDocNamespace) {
43128                     return 0 /* NonInstantiated */;
43129                 }
43130         }
43131         return 1 /* Instantiated */;
43132     }
43133     function getModuleInstanceStateForAliasTarget(specifier, visited) {
43134         var name = specifier.propertyName || specifier.name;
43135         var p = specifier.parent;
43136         while (p) {
43137             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
43138                 var statements = p.statements;
43139                 var found = void 0;
43140                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
43141                     var statement = statements_2[_i];
43142                     if (ts.nodeHasName(statement, name)) {
43143                         if (!statement.parent) {
43144                             ts.setParent(statement, p);
43145                             ts.setParentRecursive(statement, /*incremental*/ false);
43146                         }
43147                         var state = getModuleInstanceStateCached(statement, visited);
43148                         if (found === undefined || state > found) {
43149                             found = state;
43150                         }
43151                         if (found === 1 /* Instantiated */) {
43152                             return found;
43153                         }
43154                     }
43155                 }
43156                 if (found !== undefined) {
43157                     return found;
43158                 }
43159             }
43160             p = p.parent;
43161         }
43162         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
43163     }
43164     var ContainerFlags;
43165     (function (ContainerFlags) {
43166         // The current node is not a container, and no container manipulation should happen before
43167         // recursing into it.
43168         ContainerFlags[ContainerFlags["None"] = 0] = "None";
43169         // The current node is a container.  It should be set as the current container (and block-
43170         // container) before recursing into it.  The current node does not have locals.  Examples:
43171         //
43172         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
43173         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
43174         // The current node is a block-scoped-container.  It should be set as the current block-
43175         // container before recursing into it.  Examples:
43176         //
43177         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
43178         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
43179         // The current node is the container of a control flow path. The current control flow should
43180         // be saved and restored, and a new control flow initialized within the container.
43181         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
43182         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
43183         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
43184         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
43185         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
43186         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethodOrAccessor"] = 128] = "IsObjectLiteralOrClassExpressionMethodOrAccessor";
43187     })(ContainerFlags || (ContainerFlags = {}));
43188     function initFlowNode(node) {
43189         ts.Debug.attachFlowNodeDebugInfo(node);
43190         return node;
43191     }
43192     var binder = createBinder();
43193     function bindSourceFile(file, options) {
43194         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
43195         ts.performance.mark("beforeBind");
43196         ts.perfLogger.logStartBindFile("" + file.fileName);
43197         binder(file, options);
43198         ts.perfLogger.logStopBindFile();
43199         ts.performance.mark("afterBind");
43200         ts.performance.measure("Bind", "beforeBind", "afterBind");
43201         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
43202     }
43203     ts.bindSourceFile = bindSourceFile;
43204     function createBinder() {
43205         var file;
43206         var options;
43207         var languageVersion;
43208         var parent;
43209         var container;
43210         var thisParentContainer; // Container one level up
43211         var blockScopeContainer;
43212         var lastContainer;
43213         var delayedTypeAliases;
43214         var seenThisKeyword;
43215         // state used by control flow analysis
43216         var currentFlow;
43217         var currentBreakTarget;
43218         var currentContinueTarget;
43219         var currentReturnTarget;
43220         var currentTrueTarget;
43221         var currentFalseTarget;
43222         var currentExceptionTarget;
43223         var preSwitchCaseFlow;
43224         var activeLabelList;
43225         var hasExplicitReturn;
43226         // state used for emit helpers
43227         var emitFlags;
43228         // If this file is an external module, then it is automatically in strict-mode according to
43229         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
43230         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
43231         // or if compiler options contain alwaysStrict.
43232         var inStrictMode;
43233         // If we are binding an assignment pattern, we will bind certain expressions differently.
43234         var inAssignmentPattern = false;
43235         var symbolCount = 0;
43236         var Symbol;
43237         var classifiableNames;
43238         var unreachableFlow = { flags: 1 /* Unreachable */ };
43239         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
43240         var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
43241         /**
43242          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
43243          * 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)
43244          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
43245          */
43246         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
43247             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
43248         }
43249         function bindSourceFile(f, opts) {
43250             file = f;
43251             options = opts;
43252             languageVersion = ts.getEmitScriptTarget(options);
43253             inStrictMode = bindInStrictMode(file, opts);
43254             classifiableNames = new ts.Set();
43255             symbolCount = 0;
43256             Symbol = ts.objectAllocator.getSymbolConstructor();
43257             // Attach debugging information if necessary
43258             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
43259             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
43260             if (!file.locals) {
43261                 bind(file);
43262                 file.symbolCount = symbolCount;
43263                 file.classifiableNames = classifiableNames;
43264                 delayedBindJSDocTypedefTag();
43265             }
43266             file = undefined;
43267             options = undefined;
43268             languageVersion = undefined;
43269             parent = undefined;
43270             container = undefined;
43271             thisParentContainer = undefined;
43272             blockScopeContainer = undefined;
43273             lastContainer = undefined;
43274             delayedTypeAliases = undefined;
43275             seenThisKeyword = false;
43276             currentFlow = undefined;
43277             currentBreakTarget = undefined;
43278             currentContinueTarget = undefined;
43279             currentReturnTarget = undefined;
43280             currentTrueTarget = undefined;
43281             currentFalseTarget = undefined;
43282             currentExceptionTarget = undefined;
43283             activeLabelList = undefined;
43284             hasExplicitReturn = false;
43285             inAssignmentPattern = false;
43286             emitFlags = 0 /* None */;
43287         }
43288         return bindSourceFile;
43289         function bindInStrictMode(file, opts) {
43290             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
43291                 // bind in strict mode source files with alwaysStrict option
43292                 return true;
43293             }
43294             else {
43295                 return !!file.externalModuleIndicator;
43296             }
43297         }
43298         function createSymbol(flags, name) {
43299             symbolCount++;
43300             return new Symbol(flags, name);
43301         }
43302         function addDeclarationToSymbol(symbol, node, symbolFlags) {
43303             symbol.flags |= symbolFlags;
43304             node.symbol = symbol;
43305             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
43306             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
43307                 symbol.exports = ts.createSymbolTable();
43308             }
43309             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
43310                 symbol.members = ts.createSymbolTable();
43311             }
43312             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
43313             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
43314                 symbol.constEnumOnlyModule = false;
43315             }
43316             if (symbolFlags & 111551 /* Value */) {
43317                 ts.setValueDeclaration(symbol, node);
43318             }
43319         }
43320         // Should not be called on a declaration with a computed property name,
43321         // unless it is a well known Symbol.
43322         function getDeclarationName(node) {
43323             if (node.kind === 270 /* ExportAssignment */) {
43324                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
43325             }
43326             var name = ts.getNameOfDeclaration(node);
43327             if (name) {
43328                 if (ts.isAmbientModule(node)) {
43329                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
43330                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"".concat(moduleName, "\""));
43331                 }
43332                 if (name.kind === 161 /* ComputedPropertyName */) {
43333                     var nameExpression = name.expression;
43334                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
43335                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
43336                         return ts.escapeLeadingUnderscores(nameExpression.text);
43337                     }
43338                     if (ts.isSignedNumericLiteral(nameExpression)) {
43339                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
43340                     }
43341                     else {
43342                         ts.Debug.fail("Only computed properties with literal names have declaration names");
43343                     }
43344                 }
43345                 if (ts.isPrivateIdentifier(name)) {
43346                     // containingClass exists because private names only allowed inside classes
43347                     var containingClass = ts.getContainingClass(node);
43348                     if (!containingClass) {
43349                         // we can get here in cases where there is already a parse error.
43350                         return undefined;
43351                     }
43352                     var containingClassSymbol = containingClass.symbol;
43353                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
43354                 }
43355                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
43356             }
43357             switch (node.kind) {
43358                 case 170 /* Constructor */:
43359                     return "__constructor" /* Constructor */;
43360                 case 178 /* FunctionType */:
43361                 case 173 /* CallSignature */:
43362                 case 321 /* JSDocSignature */:
43363                     return "__call" /* Call */;
43364                 case 179 /* ConstructorType */:
43365                 case 174 /* ConstructSignature */:
43366                     return "__new" /* New */;
43367                 case 175 /* IndexSignature */:
43368                     return "__index" /* Index */;
43369                 case 271 /* ExportDeclaration */:
43370                     return "__export" /* ExportStar */;
43371                 case 303 /* SourceFile */:
43372                     // json file should behave as
43373                     // module.exports = ...
43374                     return "export=" /* ExportEquals */;
43375                 case 220 /* BinaryExpression */:
43376                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
43377                         // module.exports = ...
43378                         return "export=" /* ExportEquals */;
43379                     }
43380                     ts.Debug.fail("Unknown binary declaration kind");
43381                     break;
43382                 case 315 /* JSDocFunctionType */:
43383                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
43384                 case 163 /* Parameter */:
43385                     // Parameters with names are handled at the top of this function.  Parameters
43386                     // without names can only come from JSDocFunctionTypes.
43387                     ts.Debug.assert(node.parent.kind === 315 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); });
43388                     var functionType = node.parent;
43389                     var index = functionType.parameters.indexOf(node);
43390                     return "arg" + index;
43391             }
43392         }
43393         function getDisplayName(node) {
43394             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
43395         }
43396         /**
43397          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
43398          * @param symbolTable - The symbol table which node will be added to.
43399          * @param parent - node's parent declaration.
43400          * @param node - The declaration to be added to the symbol table
43401          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
43402          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
43403          */
43404         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod, isComputedName) {
43405             ts.Debug.assert(isComputedName || !ts.hasDynamicName(node));
43406             var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
43407             // The exported symbol for an export default function/class node is always named "default"
43408             var name = isComputedName ? "__computed" /* Computed */
43409                 : isDefaultExport && parent ? "default" /* Default */
43410                     : getDeclarationName(node);
43411             var symbol;
43412             if (name === undefined) {
43413                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
43414             }
43415             else {
43416                 // Check and see if the symbol table already has a symbol with this name.  If not,
43417                 // create a new symbol with this name and add it to the table.  Note that we don't
43418                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
43419                 // with the 'excludes' flags we pass in.
43420                 //
43421                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
43422                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
43423                 // the same symbol table.  If we have a conflict, report the issue on each
43424                 // declaration we have for this symbol, and then create a new symbol for this
43425                 // declaration.
43426                 //
43427                 // Note that when properties declared in Javascript constructors
43428                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
43429                 // Always. This allows the common Javascript pattern of overwriting a prototype method
43430                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
43431                 //
43432                 // If we created a new symbol, either because we didn't have a symbol with this name
43433                 // in the symbol table, or we conflicted with an existing symbol, then just add this
43434                 // node as the sole declaration of the new symbol.
43435                 //
43436                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
43437                 // you have multiple 'vars' with the same name in the same container).  In this case
43438                 // just add this node into the declarations list of the symbol.
43439                 symbol = symbolTable.get(name);
43440                 if (includes & 2885600 /* Classifiable */) {
43441                     classifiableNames.add(name);
43442                 }
43443                 if (!symbol) {
43444                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
43445                     if (isReplaceableByMethod)
43446                         symbol.isReplaceableByMethod = true;
43447                 }
43448                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
43449                     // A symbol already exists, so don't add this as a declaration.
43450                     return symbol;
43451                 }
43452                 else if (symbol.flags & excludes) {
43453                     if (symbol.isReplaceableByMethod) {
43454                         // Javascript constructor-declared symbols can be discarded in favor of
43455                         // prototype symbols like methods.
43456                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
43457                     }
43458                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
43459                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
43460                         if (ts.isNamedDeclaration(node)) {
43461                             ts.setParent(node.name, node);
43462                         }
43463                         // Report errors every position with duplicate declaration
43464                         // Report errors on previous encountered declarations
43465                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
43466                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
43467                             : ts.Diagnostics.Duplicate_identifier_0;
43468                         var messageNeedsName_1 = true;
43469                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
43470                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
43471                             messageNeedsName_1 = false;
43472                         }
43473                         var multipleDefaultExports_1 = false;
43474                         if (ts.length(symbol.declarations)) {
43475                             // If the current node is a default export of some sort, then check if
43476                             // there are any other default exports that we need to error on.
43477                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
43478                             if (isDefaultExport) {
43479                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
43480                                 messageNeedsName_1 = false;
43481                                 multipleDefaultExports_1 = true;
43482                             }
43483                             else {
43484                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
43485                                 // Error on multiple export default in the following case:
43486                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
43487                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
43488                                 if (symbol.declarations && symbol.declarations.length &&
43489                                     (node.kind === 270 /* ExportAssignment */ && !node.isExportEquals)) {
43490                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
43491                                     messageNeedsName_1 = false;
43492                                     multipleDefaultExports_1 = true;
43493                                 }
43494                             }
43495                         }
43496                         var relatedInformation_1 = [];
43497                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
43498                             // export type T; - may have meant export type { T }?
43499                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { ".concat(ts.unescapeLeadingUnderscores(node.name.escapedText), " }")));
43500                         }
43501                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
43502                         ts.forEach(symbol.declarations, function (declaration, index) {
43503                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
43504                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
43505                             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);
43506                             if (multipleDefaultExports_1) {
43507                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
43508                             }
43509                         });
43510                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
43511                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInformation_1, false)));
43512                         symbol = createSymbol(0 /* None */, name);
43513                     }
43514                 }
43515             }
43516             addDeclarationToSymbol(symbol, node, includes);
43517             if (symbol.parent) {
43518                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
43519             }
43520             else {
43521                 symbol.parent = parent;
43522             }
43523             return symbol;
43524         }
43525         function declareModuleMember(node, symbolFlags, symbolExcludes) {
43526             var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node);
43527             if (symbolFlags & 2097152 /* Alias */) {
43528                 if (node.kind === 274 /* ExportSpecifier */ || (node.kind === 264 /* ImportEqualsDeclaration */ && hasExportModifier)) {
43529                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
43530                 }
43531                 else {
43532                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
43533                 }
43534             }
43535             else {
43536                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
43537                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
43538                 //
43539                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
43540                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
43541                 //      with the same name in the same container.
43542                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
43543                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
43544                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
43545                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
43546                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
43547                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
43548                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
43549                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
43550                 if (ts.isJSDocTypeAlias(node))
43551                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
43552                 if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) {
43553                     if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
43554                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
43555                     }
43556                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
43557                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
43558                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
43559                     node.localSymbol = local;
43560                     return local;
43561                 }
43562                 else {
43563                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
43564                 }
43565             }
43566         }
43567         function jsdocTreatAsExported(node) {
43568             if (node.parent && ts.isModuleDeclaration(node)) {
43569                 node = node.parent;
43570             }
43571             if (!ts.isJSDocTypeAlias(node))
43572                 return false;
43573             // jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
43574             // 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
43575             if (!ts.isJSDocEnumTag(node) && !!node.fullName)
43576                 return true;
43577             // 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
43578             var declName = ts.getNameOfDeclaration(node);
43579             if (!declName)
43580                 return false;
43581             if (ts.isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent))
43582                 return true;
43583             if (ts.isDeclaration(declName.parent) && ts.getCombinedModifierFlags(declName.parent) & 1 /* Export */)
43584                 return true;
43585             // This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
43586             // already have calculated and branched on most of this.
43587             return false;
43588         }
43589         // All container nodes are kept on a linked list in declaration order. This list is used by
43590         // the getLocalNameOfContainer function in the type checker to validate that the local name
43591         // used for a container is unique.
43592         function bindContainer(node, containerFlags) {
43593             // Before we recurse into a node's children, we first save the existing parent, container
43594             // and block-container.  Then after we pop out of processing the children, we restore
43595             // these saved values.
43596             var saveContainer = container;
43597             var saveThisParentContainer = thisParentContainer;
43598             var savedBlockScopeContainer = blockScopeContainer;
43599             // Depending on what kind of node this is, we may have to adjust the current container
43600             // and block-container.   If the current node is a container, then it is automatically
43601             // considered the current block-container as well.  Also, for containers that we know
43602             // may contain locals, we eagerly initialize the .locals field. We do this because
43603             // it's highly likely that the .locals will be needed to place some child in (for example,
43604             // a parameter, or variable declaration).
43605             //
43606             // However, we do not proactively create the .locals for block-containers because it's
43607             // totally normal and common for block-containers to never actually have a block-scoped
43608             // variable in them.  We don't want to end up allocating an object for every 'block' we
43609             // run into when most of them won't be necessary.
43610             //
43611             // Finally, if this is a block-container, then we clear out any existing .locals object
43612             // it may contain within it.  This happens in incremental scenarios.  Because we can be
43613             // reusing a node from a previous compilation, that node may have had 'locals' created
43614             // for it.  We must clear this so we don't accidentally move any stale data forward from
43615             // a previous compilation.
43616             if (containerFlags & 1 /* IsContainer */) {
43617                 if (node.kind !== 213 /* ArrowFunction */) {
43618                     thisParentContainer = container;
43619                 }
43620                 container = blockScopeContainer = node;
43621                 if (containerFlags & 32 /* HasLocals */) {
43622                     container.locals = ts.createSymbolTable();
43623                 }
43624                 addToContainerChain(container);
43625             }
43626             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
43627                 blockScopeContainer = node;
43628                 blockScopeContainer.locals = undefined;
43629             }
43630             if (containerFlags & 4 /* IsControlFlowContainer */) {
43631                 var saveCurrentFlow = currentFlow;
43632                 var saveBreakTarget = currentBreakTarget;
43633                 var saveContinueTarget = currentContinueTarget;
43634                 var saveReturnTarget = currentReturnTarget;
43635                 var saveExceptionTarget = currentExceptionTarget;
43636                 var saveActiveLabelList = activeLabelList;
43637                 var saveHasExplicitReturn = hasExplicitReturn;
43638                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
43639                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
43640                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
43641                 // similarly to break statements that exit to a label just past the statement body.
43642                 if (!isIIFE) {
43643                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
43644                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) {
43645                         currentFlow.node = node;
43646                     }
43647                 }
43648                 // We create a return control flow graph for IIFEs and constructors. For constructors
43649                 // we use the return control flow graph in strict property initialization checks.
43650                 currentReturnTarget = isIIFE || node.kind === 170 /* Constructor */ || node.kind === 169 /* ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 255 /* FunctionDeclaration */ || node.kind === 212 /* FunctionExpression */)) ? createBranchLabel() : undefined;
43651                 currentExceptionTarget = undefined;
43652                 currentBreakTarget = undefined;
43653                 currentContinueTarget = undefined;
43654                 activeLabelList = undefined;
43655                 hasExplicitReturn = false;
43656                 bindChildren(node);
43657                 // Reset all reachability check related flags on node (for incremental scenarios)
43658                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
43659                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
43660                     node.flags |= 256 /* HasImplicitReturn */;
43661                     if (hasExplicitReturn)
43662                         node.flags |= 512 /* HasExplicitReturn */;
43663                     node.endFlowNode = currentFlow;
43664                 }
43665                 if (node.kind === 303 /* SourceFile */) {
43666                     node.flags |= emitFlags;
43667                     node.endFlowNode = currentFlow;
43668                 }
43669                 if (currentReturnTarget) {
43670                     addAntecedent(currentReturnTarget, currentFlow);
43671                     currentFlow = finishFlowLabel(currentReturnTarget);
43672                     if (node.kind === 170 /* Constructor */ || node.kind === 169 /* ClassStaticBlockDeclaration */ || (ts.isInJSFile(node) && (node.kind === 255 /* FunctionDeclaration */ || node.kind === 212 /* FunctionExpression */))) {
43673                         node.returnFlowNode = currentFlow;
43674                     }
43675                 }
43676                 if (!isIIFE) {
43677                     currentFlow = saveCurrentFlow;
43678                 }
43679                 currentBreakTarget = saveBreakTarget;
43680                 currentContinueTarget = saveContinueTarget;
43681                 currentReturnTarget = saveReturnTarget;
43682                 currentExceptionTarget = saveExceptionTarget;
43683                 activeLabelList = saveActiveLabelList;
43684                 hasExplicitReturn = saveHasExplicitReturn;
43685             }
43686             else if (containerFlags & 64 /* IsInterface */) {
43687                 seenThisKeyword = false;
43688                 bindChildren(node);
43689                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
43690             }
43691             else {
43692                 bindChildren(node);
43693             }
43694             container = saveContainer;
43695             thisParentContainer = saveThisParentContainer;
43696             blockScopeContainer = savedBlockScopeContainer;
43697         }
43698         function bindEachFunctionsFirst(nodes) {
43699             bindEach(nodes, function (n) { return n.kind === 255 /* FunctionDeclaration */ ? bind(n) : undefined; });
43700             bindEach(nodes, function (n) { return n.kind !== 255 /* FunctionDeclaration */ ? bind(n) : undefined; });
43701         }
43702         function bindEach(nodes, bindFunction) {
43703             if (bindFunction === void 0) { bindFunction = bind; }
43704             if (nodes === undefined) {
43705                 return;
43706             }
43707             ts.forEach(nodes, bindFunction);
43708         }
43709         function bindEachChild(node) {
43710             ts.forEachChild(node, bind, bindEach);
43711         }
43712         function bindChildren(node) {
43713             var saveInAssignmentPattern = inAssignmentPattern;
43714             // Most nodes aren't valid in an assignment pattern, so we clear the value here
43715             // and set it before we descend into nodes that could actually be part of an assignment pattern.
43716             inAssignmentPattern = false;
43717             if (checkUnreachable(node)) {
43718                 bindEachChild(node);
43719                 bindJSDoc(node);
43720                 inAssignmentPattern = saveInAssignmentPattern;
43721                 return;
43722             }
43723             if (node.kind >= 236 /* FirstStatement */ && node.kind <= 252 /* LastStatement */ && !options.allowUnreachableCode) {
43724                 node.flowNode = currentFlow;
43725             }
43726             switch (node.kind) {
43727                 case 240 /* WhileStatement */:
43728                     bindWhileStatement(node);
43729                     break;
43730                 case 239 /* DoStatement */:
43731                     bindDoStatement(node);
43732                     break;
43733                 case 241 /* ForStatement */:
43734                     bindForStatement(node);
43735                     break;
43736                 case 242 /* ForInStatement */:
43737                 case 243 /* ForOfStatement */:
43738                     bindForInOrForOfStatement(node);
43739                     break;
43740                 case 238 /* IfStatement */:
43741                     bindIfStatement(node);
43742                     break;
43743                 case 246 /* ReturnStatement */:
43744                 case 250 /* ThrowStatement */:
43745                     bindReturnOrThrow(node);
43746                     break;
43747                 case 245 /* BreakStatement */:
43748                 case 244 /* ContinueStatement */:
43749                     bindBreakOrContinueStatement(node);
43750                     break;
43751                 case 251 /* TryStatement */:
43752                     bindTryStatement(node);
43753                     break;
43754                 case 248 /* SwitchStatement */:
43755                     bindSwitchStatement(node);
43756                     break;
43757                 case 262 /* CaseBlock */:
43758                     bindCaseBlock(node);
43759                     break;
43760                 case 288 /* CaseClause */:
43761                     bindCaseClause(node);
43762                     break;
43763                 case 237 /* ExpressionStatement */:
43764                     bindExpressionStatement(node);
43765                     break;
43766                 case 249 /* LabeledStatement */:
43767                     bindLabeledStatement(node);
43768                     break;
43769                 case 218 /* PrefixUnaryExpression */:
43770                     bindPrefixUnaryExpressionFlow(node);
43771                     break;
43772                 case 219 /* PostfixUnaryExpression */:
43773                     bindPostfixUnaryExpressionFlow(node);
43774                     break;
43775                 case 220 /* BinaryExpression */:
43776                     if (ts.isDestructuringAssignment(node)) {
43777                         // Carry over whether we are in an assignment pattern to
43778                         // binary expressions that could actually be an initializer
43779                         inAssignmentPattern = saveInAssignmentPattern;
43780                         bindDestructuringAssignmentFlow(node);
43781                         return;
43782                     }
43783                     bindBinaryExpressionFlow(node);
43784                     break;
43785                 case 214 /* DeleteExpression */:
43786                     bindDeleteExpressionFlow(node);
43787                     break;
43788                 case 221 /* ConditionalExpression */:
43789                     bindConditionalExpressionFlow(node);
43790                     break;
43791                 case 253 /* VariableDeclaration */:
43792                     bindVariableDeclarationFlow(node);
43793                     break;
43794                 case 205 /* PropertyAccessExpression */:
43795                 case 206 /* ElementAccessExpression */:
43796                     bindAccessExpressionFlow(node);
43797                     break;
43798                 case 207 /* CallExpression */:
43799                     bindCallExpressionFlow(node);
43800                     break;
43801                 case 229 /* NonNullExpression */:
43802                     bindNonNullExpressionFlow(node);
43803                     break;
43804                 case 343 /* JSDocTypedefTag */:
43805                 case 336 /* JSDocCallbackTag */:
43806                 case 337 /* JSDocEnumTag */:
43807                     bindJSDocTypeAlias(node);
43808                     break;
43809                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
43810                 case 303 /* SourceFile */: {
43811                     bindEachFunctionsFirst(node.statements);
43812                     bind(node.endOfFileToken);
43813                     break;
43814                 }
43815                 case 234 /* Block */:
43816                 case 261 /* ModuleBlock */:
43817                     bindEachFunctionsFirst(node.statements);
43818                     break;
43819                 case 202 /* BindingElement */:
43820                     bindBindingElementFlow(node);
43821                     break;
43822                 case 204 /* ObjectLiteralExpression */:
43823                 case 203 /* ArrayLiteralExpression */:
43824                 case 294 /* PropertyAssignment */:
43825                 case 224 /* SpreadElement */:
43826                     // Carry over whether we are in an assignment pattern of Object and Array literals
43827                     // as well as their children that are valid assignment targets.
43828                     inAssignmentPattern = saveInAssignmentPattern;
43829                 // falls through
43830                 default:
43831                     bindEachChild(node);
43832                     break;
43833             }
43834             bindJSDoc(node);
43835             inAssignmentPattern = saveInAssignmentPattern;
43836         }
43837         function isNarrowingExpression(expr) {
43838             switch (expr.kind) {
43839                 case 79 /* Identifier */:
43840                 case 80 /* PrivateIdentifier */:
43841                 case 108 /* ThisKeyword */:
43842                 case 205 /* PropertyAccessExpression */:
43843                 case 206 /* ElementAccessExpression */:
43844                     return containsNarrowableReference(expr);
43845                 case 207 /* CallExpression */:
43846                     return hasNarrowableArgument(expr);
43847                 case 211 /* ParenthesizedExpression */:
43848                 case 229 /* NonNullExpression */:
43849                     return isNarrowingExpression(expr.expression);
43850                 case 220 /* BinaryExpression */:
43851                     return isNarrowingBinaryExpression(expr);
43852                 case 218 /* PrefixUnaryExpression */:
43853                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
43854                 case 215 /* TypeOfExpression */:
43855                     return isNarrowingExpression(expr.expression);
43856             }
43857             return false;
43858         }
43859         function isNarrowableReference(expr) {
43860             return ts.isDottedName(expr)
43861                 || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression)
43862                 || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right)
43863                 || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression)
43864                 || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
43865         }
43866         function containsNarrowableReference(expr) {
43867             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
43868         }
43869         function hasNarrowableArgument(expr) {
43870             if (expr.arguments) {
43871                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
43872                     var argument = _a[_i];
43873                     if (containsNarrowableReference(argument)) {
43874                         return true;
43875                     }
43876                 }
43877             }
43878             if (expr.expression.kind === 205 /* PropertyAccessExpression */ &&
43879                 containsNarrowableReference(expr.expression.expression)) {
43880                 return true;
43881             }
43882             return false;
43883         }
43884         function isNarrowingTypeofOperands(expr1, expr2) {
43885             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
43886         }
43887         function isNarrowingBinaryExpression(expr) {
43888             switch (expr.operatorToken.kind) {
43889                 case 63 /* EqualsToken */:
43890                 case 75 /* BarBarEqualsToken */:
43891                 case 76 /* AmpersandAmpersandEqualsToken */:
43892                 case 77 /* QuestionQuestionEqualsToken */:
43893                     return containsNarrowableReference(expr.left);
43894                 case 34 /* EqualsEqualsToken */:
43895                 case 35 /* ExclamationEqualsToken */:
43896                 case 36 /* EqualsEqualsEqualsToken */:
43897                 case 37 /* ExclamationEqualsEqualsToken */:
43898                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
43899                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
43900                 case 102 /* InstanceOfKeyword */:
43901                     return isNarrowableOperand(expr.left);
43902                 case 101 /* InKeyword */:
43903                     return isNarrowingExpression(expr.right);
43904                 case 27 /* CommaToken */:
43905                     return isNarrowingExpression(expr.right);
43906             }
43907             return false;
43908         }
43909         function isNarrowableOperand(expr) {
43910             switch (expr.kind) {
43911                 case 211 /* ParenthesizedExpression */:
43912                     return isNarrowableOperand(expr.expression);
43913                 case 220 /* BinaryExpression */:
43914                     switch (expr.operatorToken.kind) {
43915                         case 63 /* EqualsToken */:
43916                             return isNarrowableOperand(expr.left);
43917                         case 27 /* CommaToken */:
43918                             return isNarrowableOperand(expr.right);
43919                     }
43920             }
43921             return containsNarrowableReference(expr);
43922         }
43923         function createBranchLabel() {
43924             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
43925         }
43926         function createLoopLabel() {
43927             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
43928         }
43929         function createReduceLabel(target, antecedents, antecedent) {
43930             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
43931         }
43932         function setFlowNodeReferenced(flow) {
43933             // On first reference we set the Referenced flag, thereafter we set the Shared flag
43934             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
43935         }
43936         function addAntecedent(label, antecedent) {
43937             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
43938                 (label.antecedents || (label.antecedents = [])).push(antecedent);
43939                 setFlowNodeReferenced(antecedent);
43940             }
43941         }
43942         function createFlowCondition(flags, antecedent, expression) {
43943             if (antecedent.flags & 1 /* Unreachable */) {
43944                 return antecedent;
43945             }
43946             if (!expression) {
43947                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
43948             }
43949             if ((expression.kind === 110 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
43950                 expression.kind === 95 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
43951                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
43952                 return unreachableFlow;
43953             }
43954             if (!isNarrowingExpression(expression)) {
43955                 return antecedent;
43956             }
43957             setFlowNodeReferenced(antecedent);
43958             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
43959         }
43960         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
43961             setFlowNodeReferenced(antecedent);
43962             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
43963         }
43964         function createFlowMutation(flags, antecedent, node) {
43965             setFlowNodeReferenced(antecedent);
43966             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
43967             if (currentExceptionTarget) {
43968                 addAntecedent(currentExceptionTarget, result);
43969             }
43970             return result;
43971         }
43972         function createFlowCall(antecedent, node) {
43973             setFlowNodeReferenced(antecedent);
43974             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
43975         }
43976         function finishFlowLabel(flow) {
43977             var antecedents = flow.antecedents;
43978             if (!antecedents) {
43979                 return unreachableFlow;
43980             }
43981             if (antecedents.length === 1) {
43982                 return antecedents[0];
43983             }
43984             return flow;
43985         }
43986         function isStatementCondition(node) {
43987             var parent = node.parent;
43988             switch (parent.kind) {
43989                 case 238 /* IfStatement */:
43990                 case 240 /* WhileStatement */:
43991                 case 239 /* DoStatement */:
43992                     return parent.expression === node;
43993                 case 241 /* ForStatement */:
43994                 case 221 /* ConditionalExpression */:
43995                     return parent.condition === node;
43996             }
43997             return false;
43998         }
43999         function isLogicalExpression(node) {
44000             while (true) {
44001                 if (node.kind === 211 /* ParenthesizedExpression */) {
44002                     node = node.expression;
44003                 }
44004                 else if (node.kind === 218 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
44005                     node = node.operand;
44006                 }
44007                 else {
44008                     return node.kind === 220 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
44009                         node.operatorToken.kind === 56 /* BarBarToken */ ||
44010                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
44011                 }
44012             }
44013         }
44014         function isLogicalAssignmentExpression(node) {
44015             node = ts.skipParentheses(node);
44016             return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
44017         }
44018         function isTopLevelLogicalExpression(node) {
44019             while (ts.isParenthesizedExpression(node.parent) ||
44020                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
44021                 node = node.parent;
44022             }
44023             return !isStatementCondition(node) &&
44024                 !isLogicalAssignmentExpression(node.parent) &&
44025                 !isLogicalExpression(node.parent) &&
44026                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
44027         }
44028         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
44029             var savedTrueTarget = currentTrueTarget;
44030             var savedFalseTarget = currentFalseTarget;
44031             currentTrueTarget = trueTarget;
44032             currentFalseTarget = falseTarget;
44033             action(value);
44034             currentTrueTarget = savedTrueTarget;
44035             currentFalseTarget = savedFalseTarget;
44036         }
44037         function bindCondition(node, trueTarget, falseTarget) {
44038             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
44039             if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
44040                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
44041                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
44042             }
44043         }
44044         function bindIterativeStatement(node, breakTarget, continueTarget) {
44045             var saveBreakTarget = currentBreakTarget;
44046             var saveContinueTarget = currentContinueTarget;
44047             currentBreakTarget = breakTarget;
44048             currentContinueTarget = continueTarget;
44049             bind(node);
44050             currentBreakTarget = saveBreakTarget;
44051             currentContinueTarget = saveContinueTarget;
44052         }
44053         function setContinueTarget(node, target) {
44054             var label = activeLabelList;
44055             while (label && node.parent.kind === 249 /* LabeledStatement */) {
44056                 label.continueTarget = target;
44057                 label = label.next;
44058                 node = node.parent;
44059             }
44060             return target;
44061         }
44062         function bindWhileStatement(node) {
44063             var preWhileLabel = setContinueTarget(node, createLoopLabel());
44064             var preBodyLabel = createBranchLabel();
44065             var postWhileLabel = createBranchLabel();
44066             addAntecedent(preWhileLabel, currentFlow);
44067             currentFlow = preWhileLabel;
44068             bindCondition(node.expression, preBodyLabel, postWhileLabel);
44069             currentFlow = finishFlowLabel(preBodyLabel);
44070             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
44071             addAntecedent(preWhileLabel, currentFlow);
44072             currentFlow = finishFlowLabel(postWhileLabel);
44073         }
44074         function bindDoStatement(node) {
44075             var preDoLabel = createLoopLabel();
44076             var preConditionLabel = setContinueTarget(node, createBranchLabel());
44077             var postDoLabel = createBranchLabel();
44078             addAntecedent(preDoLabel, currentFlow);
44079             currentFlow = preDoLabel;
44080             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
44081             addAntecedent(preConditionLabel, currentFlow);
44082             currentFlow = finishFlowLabel(preConditionLabel);
44083             bindCondition(node.expression, preDoLabel, postDoLabel);
44084             currentFlow = finishFlowLabel(postDoLabel);
44085         }
44086         function bindForStatement(node) {
44087             var preLoopLabel = setContinueTarget(node, createLoopLabel());
44088             var preBodyLabel = createBranchLabel();
44089             var postLoopLabel = createBranchLabel();
44090             bind(node.initializer);
44091             addAntecedent(preLoopLabel, currentFlow);
44092             currentFlow = preLoopLabel;
44093             bindCondition(node.condition, preBodyLabel, postLoopLabel);
44094             currentFlow = finishFlowLabel(preBodyLabel);
44095             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
44096             bind(node.incrementor);
44097             addAntecedent(preLoopLabel, currentFlow);
44098             currentFlow = finishFlowLabel(postLoopLabel);
44099         }
44100         function bindForInOrForOfStatement(node) {
44101             var preLoopLabel = setContinueTarget(node, createLoopLabel());
44102             var postLoopLabel = createBranchLabel();
44103             bind(node.expression);
44104             addAntecedent(preLoopLabel, currentFlow);
44105             currentFlow = preLoopLabel;
44106             if (node.kind === 243 /* ForOfStatement */) {
44107                 bind(node.awaitModifier);
44108             }
44109             addAntecedent(postLoopLabel, currentFlow);
44110             bind(node.initializer);
44111             if (node.initializer.kind !== 254 /* VariableDeclarationList */) {
44112                 bindAssignmentTargetFlow(node.initializer);
44113             }
44114             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
44115             addAntecedent(preLoopLabel, currentFlow);
44116             currentFlow = finishFlowLabel(postLoopLabel);
44117         }
44118         function bindIfStatement(node) {
44119             var thenLabel = createBranchLabel();
44120             var elseLabel = createBranchLabel();
44121             var postIfLabel = createBranchLabel();
44122             bindCondition(node.expression, thenLabel, elseLabel);
44123             currentFlow = finishFlowLabel(thenLabel);
44124             bind(node.thenStatement);
44125             addAntecedent(postIfLabel, currentFlow);
44126             currentFlow = finishFlowLabel(elseLabel);
44127             bind(node.elseStatement);
44128             addAntecedent(postIfLabel, currentFlow);
44129             currentFlow = finishFlowLabel(postIfLabel);
44130         }
44131         function bindReturnOrThrow(node) {
44132             bind(node.expression);
44133             if (node.kind === 246 /* ReturnStatement */) {
44134                 hasExplicitReturn = true;
44135                 if (currentReturnTarget) {
44136                     addAntecedent(currentReturnTarget, currentFlow);
44137                 }
44138             }
44139             currentFlow = unreachableFlow;
44140         }
44141         function findActiveLabel(name) {
44142             for (var label = activeLabelList; label; label = label.next) {
44143                 if (label.name === name) {
44144                     return label;
44145                 }
44146             }
44147             return undefined;
44148         }
44149         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
44150             var flowLabel = node.kind === 245 /* BreakStatement */ ? breakTarget : continueTarget;
44151             if (flowLabel) {
44152                 addAntecedent(flowLabel, currentFlow);
44153                 currentFlow = unreachableFlow;
44154             }
44155         }
44156         function bindBreakOrContinueStatement(node) {
44157             bind(node.label);
44158             if (node.label) {
44159                 var activeLabel = findActiveLabel(node.label.escapedText);
44160                 if (activeLabel) {
44161                     activeLabel.referenced = true;
44162                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
44163                 }
44164             }
44165             else {
44166                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
44167             }
44168         }
44169         function bindTryStatement(node) {
44170             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
44171             // to track code that causes mutations (because only mutations widen the possible control flow type of
44172             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
44173             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
44174             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
44175             // represent exceptions that occur before any mutations.
44176             var saveReturnTarget = currentReturnTarget;
44177             var saveExceptionTarget = currentExceptionTarget;
44178             var normalExitLabel = createBranchLabel();
44179             var returnLabel = createBranchLabel();
44180             var exceptionLabel = createBranchLabel();
44181             if (node.finallyBlock) {
44182                 currentReturnTarget = returnLabel;
44183             }
44184             addAntecedent(exceptionLabel, currentFlow);
44185             currentExceptionTarget = exceptionLabel;
44186             bind(node.tryBlock);
44187             addAntecedent(normalExitLabel, currentFlow);
44188             if (node.catchClause) {
44189                 // Start of catch clause is the target of exceptions from try block.
44190                 currentFlow = finishFlowLabel(exceptionLabel);
44191                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
44192                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
44193                 // acts like a second try block.
44194                 exceptionLabel = createBranchLabel();
44195                 addAntecedent(exceptionLabel, currentFlow);
44196                 currentExceptionTarget = exceptionLabel;
44197                 bind(node.catchClause);
44198                 addAntecedent(normalExitLabel, currentFlow);
44199             }
44200             currentReturnTarget = saveReturnTarget;
44201             currentExceptionTarget = saveExceptionTarget;
44202             if (node.finallyBlock) {
44203                 // Possible ways control can reach the finally block:
44204                 // 1) Normal completion of try block of a try-finally or try-catch-finally
44205                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
44206                 // 3) Return in try or catch block of a try-finally or try-catch-finally
44207                 // 4) Exception in try block of a try-finally
44208                 // 5) Exception in catch block of a try-catch-finally
44209                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
44210                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
44211                 // the finally block, we only want to consider the first two (if we're past a finally block then it
44212                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
44213                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
44214                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
44215                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
44216                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
44217                 var finallyLabel = createBranchLabel();
44218                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
44219                 currentFlow = finallyLabel;
44220                 bind(node.finallyBlock);
44221                 if (currentFlow.flags & 1 /* Unreachable */) {
44222                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
44223                     currentFlow = unreachableFlow;
44224                 }
44225                 else {
44226                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
44227                     // flow that goes back through the finally block and back through only the return statements.
44228                     if (currentReturnTarget && returnLabel.antecedents) {
44229                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
44230                     }
44231                     // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
44232                     // control flow that goes back through the finally blok and back through each possible exception source.
44233                     if (currentExceptionTarget && exceptionLabel.antecedents) {
44234                         addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
44235                     }
44236                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
44237                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
44238                     // result in an unreachable current control flow.
44239                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
44240                 }
44241             }
44242             else {
44243                 currentFlow = finishFlowLabel(normalExitLabel);
44244             }
44245         }
44246         function bindSwitchStatement(node) {
44247             var postSwitchLabel = createBranchLabel();
44248             bind(node.expression);
44249             var saveBreakTarget = currentBreakTarget;
44250             var savePreSwitchCaseFlow = preSwitchCaseFlow;
44251             currentBreakTarget = postSwitchLabel;
44252             preSwitchCaseFlow = currentFlow;
44253             bind(node.caseBlock);
44254             addAntecedent(postSwitchLabel, currentFlow);
44255             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 289 /* DefaultClause */; });
44256             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
44257             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
44258             // this property in control flow analysis, it's there only for backwards compatibility.
44259             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
44260             if (!hasDefault) {
44261                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
44262             }
44263             currentBreakTarget = saveBreakTarget;
44264             preSwitchCaseFlow = savePreSwitchCaseFlow;
44265             currentFlow = finishFlowLabel(postSwitchLabel);
44266         }
44267         function bindCaseBlock(node) {
44268             var clauses = node.clauses;
44269             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
44270             var fallthroughFlow = unreachableFlow;
44271             for (var i = 0; i < clauses.length; i++) {
44272                 var clauseStart = i;
44273                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
44274                     bind(clauses[i]);
44275                     i++;
44276                 }
44277                 var preCaseLabel = createBranchLabel();
44278                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
44279                 addAntecedent(preCaseLabel, fallthroughFlow);
44280                 currentFlow = finishFlowLabel(preCaseLabel);
44281                 var clause = clauses[i];
44282                 bind(clause);
44283                 fallthroughFlow = currentFlow;
44284                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
44285                     clause.fallthroughFlowNode = currentFlow;
44286                 }
44287             }
44288         }
44289         function bindCaseClause(node) {
44290             var saveCurrentFlow = currentFlow;
44291             currentFlow = preSwitchCaseFlow;
44292             bind(node.expression);
44293             currentFlow = saveCurrentFlow;
44294             bindEach(node.statements);
44295         }
44296         function bindExpressionStatement(node) {
44297             bind(node.expression);
44298             maybeBindExpressionFlowIfCall(node.expression);
44299         }
44300         function maybeBindExpressionFlowIfCall(node) {
44301             // A top level or LHS of comma expression call expression with a dotted function name and at least one argument
44302             // is potentially an assertion and is therefore included in the control flow.
44303             if (node.kind === 207 /* CallExpression */) {
44304                 var call = node;
44305                 if (call.expression.kind !== 106 /* SuperKeyword */ && ts.isDottedName(call.expression)) {
44306                     currentFlow = createFlowCall(currentFlow, call);
44307                 }
44308             }
44309         }
44310         function bindLabeledStatement(node) {
44311             var postStatementLabel = createBranchLabel();
44312             activeLabelList = {
44313                 next: activeLabelList,
44314                 name: node.label.escapedText,
44315                 breakTarget: postStatementLabel,
44316                 continueTarget: undefined,
44317                 referenced: false
44318             };
44319             bind(node.label);
44320             bind(node.statement);
44321             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
44322                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
44323             }
44324             activeLabelList = activeLabelList.next;
44325             addAntecedent(postStatementLabel, currentFlow);
44326             currentFlow = finishFlowLabel(postStatementLabel);
44327         }
44328         function bindDestructuringTargetFlow(node) {
44329             if (node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 63 /* EqualsToken */) {
44330                 bindAssignmentTargetFlow(node.left);
44331             }
44332             else {
44333                 bindAssignmentTargetFlow(node);
44334             }
44335         }
44336         function bindAssignmentTargetFlow(node) {
44337             if (isNarrowableReference(node)) {
44338                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
44339             }
44340             else if (node.kind === 203 /* ArrayLiteralExpression */) {
44341                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
44342                     var e = _a[_i];
44343                     if (e.kind === 224 /* SpreadElement */) {
44344                         bindAssignmentTargetFlow(e.expression);
44345                     }
44346                     else {
44347                         bindDestructuringTargetFlow(e);
44348                     }
44349                 }
44350             }
44351             else if (node.kind === 204 /* ObjectLiteralExpression */) {
44352                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
44353                     var p = _c[_b];
44354                     if (p.kind === 294 /* PropertyAssignment */) {
44355                         bindDestructuringTargetFlow(p.initializer);
44356                     }
44357                     else if (p.kind === 295 /* ShorthandPropertyAssignment */) {
44358                         bindAssignmentTargetFlow(p.name);
44359                     }
44360                     else if (p.kind === 296 /* SpreadAssignment */) {
44361                         bindAssignmentTargetFlow(p.expression);
44362                     }
44363                 }
44364             }
44365         }
44366         function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
44367             var preRightLabel = createBranchLabel();
44368             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 76 /* AmpersandAmpersandEqualsToken */) {
44369                 bindCondition(node.left, preRightLabel, falseTarget);
44370             }
44371             else {
44372                 bindCondition(node.left, trueTarget, preRightLabel);
44373             }
44374             currentFlow = finishFlowLabel(preRightLabel);
44375             bind(node.operatorToken);
44376             if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
44377                 doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
44378                 bindAssignmentTargetFlow(node.left);
44379                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
44380                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
44381             }
44382             else {
44383                 bindCondition(node.right, trueTarget, falseTarget);
44384             }
44385         }
44386         function bindPrefixUnaryExpressionFlow(node) {
44387             if (node.operator === 53 /* ExclamationToken */) {
44388                 var saveTrueTarget = currentTrueTarget;
44389                 currentTrueTarget = currentFalseTarget;
44390                 currentFalseTarget = saveTrueTarget;
44391                 bindEachChild(node);
44392                 currentFalseTarget = currentTrueTarget;
44393                 currentTrueTarget = saveTrueTarget;
44394             }
44395             else {
44396                 bindEachChild(node);
44397                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
44398                     bindAssignmentTargetFlow(node.operand);
44399                 }
44400             }
44401         }
44402         function bindPostfixUnaryExpressionFlow(node) {
44403             bindEachChild(node);
44404             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
44405                 bindAssignmentTargetFlow(node.operand);
44406             }
44407         }
44408         function bindDestructuringAssignmentFlow(node) {
44409             if (inAssignmentPattern) {
44410                 inAssignmentPattern = false;
44411                 bind(node.operatorToken);
44412                 bind(node.right);
44413                 inAssignmentPattern = true;
44414                 bind(node.left);
44415             }
44416             else {
44417                 inAssignmentPattern = true;
44418                 bind(node.left);
44419                 inAssignmentPattern = false;
44420                 bind(node.operatorToken);
44421                 bind(node.right);
44422             }
44423             bindAssignmentTargetFlow(node.left);
44424         }
44425         function createBindBinaryExpressionFlow() {
44426             return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined);
44427             function onEnter(node, state) {
44428                 if (state) {
44429                     state.stackIndex++;
44430                     // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to
44431                     // `bindBinaryExpressionFlow` will already have done this work.
44432                     ts.setParent(node, parent);
44433                     var saveInStrictMode = inStrictMode;
44434                     bindWorker(node);
44435                     var saveParent = parent;
44436                     parent = node;
44437                     state.skip = false;
44438                     state.inStrictModeStack[state.stackIndex] = saveInStrictMode;
44439                     state.parentStack[state.stackIndex] = saveParent;
44440                 }
44441                 else {
44442                     state = {
44443                         stackIndex: 0,
44444                         skip: false,
44445                         inStrictModeStack: [undefined],
44446                         parentStack: [undefined]
44447                     };
44448                 }
44449                 // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
44450                 // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
44451                 // For now, though, since the common cases are chained `+`, leaving it recursive is fine
44452                 var operator = node.operatorToken.kind;
44453                 if (operator === 55 /* AmpersandAmpersandToken */ ||
44454                     operator === 56 /* BarBarToken */ ||
44455                     operator === 60 /* QuestionQuestionToken */ ||
44456                     ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
44457                     if (isTopLevelLogicalExpression(node)) {
44458                         var postExpressionLabel = createBranchLabel();
44459                         bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
44460                         currentFlow = finishFlowLabel(postExpressionLabel);
44461                     }
44462                     else {
44463                         bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
44464                     }
44465                     state.skip = true;
44466                 }
44467                 return state;
44468             }
44469             function onLeft(left, state, _node) {
44470                 if (!state.skip) {
44471                     return maybeBind(left);
44472                 }
44473             }
44474             function onOperator(operatorToken, state, node) {
44475                 if (!state.skip) {
44476                     if (operatorToken.kind === 27 /* CommaToken */) {
44477                         maybeBindExpressionFlowIfCall(node.left);
44478                     }
44479                     bind(operatorToken);
44480                 }
44481             }
44482             function onRight(right, state, _node) {
44483                 if (!state.skip) {
44484                     return maybeBind(right);
44485                 }
44486             }
44487             function onExit(node, state) {
44488                 if (!state.skip) {
44489                     var operator = node.operatorToken.kind;
44490                     if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
44491                         bindAssignmentTargetFlow(node.left);
44492                         if (operator === 63 /* EqualsToken */ && node.left.kind === 206 /* ElementAccessExpression */) {
44493                             var elementAccess = node.left;
44494                             if (isNarrowableOperand(elementAccess.expression)) {
44495                                 currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
44496                             }
44497                         }
44498                     }
44499                 }
44500                 var savedInStrictMode = state.inStrictModeStack[state.stackIndex];
44501                 var savedParent = state.parentStack[state.stackIndex];
44502                 if (savedInStrictMode !== undefined) {
44503                     inStrictMode = savedInStrictMode;
44504                 }
44505                 if (savedParent !== undefined) {
44506                     parent = savedParent;
44507                 }
44508                 state.skip = false;
44509                 state.stackIndex--;
44510             }
44511             function maybeBind(node) {
44512                 if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) {
44513                     return node;
44514                 }
44515                 bind(node);
44516             }
44517         }
44518         function bindDeleteExpressionFlow(node) {
44519             bindEachChild(node);
44520             if (node.expression.kind === 205 /* PropertyAccessExpression */) {
44521                 bindAssignmentTargetFlow(node.expression);
44522             }
44523         }
44524         function bindConditionalExpressionFlow(node) {
44525             var trueLabel = createBranchLabel();
44526             var falseLabel = createBranchLabel();
44527             var postExpressionLabel = createBranchLabel();
44528             bindCondition(node.condition, trueLabel, falseLabel);
44529             currentFlow = finishFlowLabel(trueLabel);
44530             bind(node.questionToken);
44531             bind(node.whenTrue);
44532             addAntecedent(postExpressionLabel, currentFlow);
44533             currentFlow = finishFlowLabel(falseLabel);
44534             bind(node.colonToken);
44535             bind(node.whenFalse);
44536             addAntecedent(postExpressionLabel, currentFlow);
44537             currentFlow = finishFlowLabel(postExpressionLabel);
44538         }
44539         function bindInitializedVariableFlow(node) {
44540             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
44541             if (ts.isBindingPattern(name)) {
44542                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
44543                     var child = _a[_i];
44544                     bindInitializedVariableFlow(child);
44545                 }
44546             }
44547             else {
44548                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
44549             }
44550         }
44551         function bindVariableDeclarationFlow(node) {
44552             bindEachChild(node);
44553             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
44554                 bindInitializedVariableFlow(node);
44555             }
44556         }
44557         function bindBindingElementFlow(node) {
44558             if (ts.isBindingPattern(node.name)) {
44559                 // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per:
44560                 // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
44561                 //   - `BindingElement: BindingPattern Initializer?`
44562                 // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization
44563                 //   - `BindingElement: BindingPattern Initializer?`
44564                 bindEach(node.decorators);
44565                 bindEach(node.modifiers);
44566                 bind(node.dotDotDotToken);
44567                 bind(node.propertyName);
44568                 bind(node.initializer);
44569                 bind(node.name);
44570             }
44571             else {
44572                 bindEachChild(node);
44573             }
44574         }
44575         function bindJSDocTypeAlias(node) {
44576             bind(node.tagName);
44577             if (node.kind !== 337 /* JSDocEnumTag */ && node.fullName) {
44578                 // don't bind the type name yet; that's delayed until delayedBindJSDocTypedefTag
44579                 ts.setParent(node.fullName, node);
44580                 ts.setParentRecursive(node.fullName, /*incremental*/ false);
44581             }
44582             if (typeof node.comment !== "string") {
44583                 bindEach(node.comment);
44584             }
44585         }
44586         function bindJSDocClassTag(node) {
44587             bindEachChild(node);
44588             var host = ts.getHostSignatureFromJSDoc(node);
44589             if (host && host.kind !== 168 /* MethodDeclaration */) {
44590                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
44591             }
44592         }
44593         function bindOptionalExpression(node, trueTarget, falseTarget) {
44594             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
44595             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
44596                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
44597                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
44598             }
44599         }
44600         function bindOptionalChainRest(node) {
44601             switch (node.kind) {
44602                 case 205 /* PropertyAccessExpression */:
44603                     bind(node.questionDotToken);
44604                     bind(node.name);
44605                     break;
44606                 case 206 /* ElementAccessExpression */:
44607                     bind(node.questionDotToken);
44608                     bind(node.argumentExpression);
44609                     break;
44610                 case 207 /* CallExpression */:
44611                     bind(node.questionDotToken);
44612                     bindEach(node.typeArguments);
44613                     bindEach(node.arguments);
44614                     break;
44615             }
44616         }
44617         function bindOptionalChain(node, trueTarget, falseTarget) {
44618             // For an optional chain, we emulate the behavior of a logical expression:
44619             //
44620             // a?.b         -> a && a.b
44621             // a?.b.c       -> a && a.b.c
44622             // a?.b?.c      -> a && a.b && a.b.c
44623             // a?.[x = 1]   -> a && a[x = 1]
44624             //
44625             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
44626             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
44627             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
44628             // chain node. We then treat the entire node as the right side of the expression.
44629             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
44630             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
44631             if (preChainLabel) {
44632                 currentFlow = finishFlowLabel(preChainLabel);
44633             }
44634             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
44635             if (ts.isOutermostOptionalChain(node)) {
44636                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
44637                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
44638             }
44639         }
44640         function bindOptionalChainFlow(node) {
44641             if (isTopLevelLogicalExpression(node)) {
44642                 var postExpressionLabel = createBranchLabel();
44643                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
44644                 currentFlow = finishFlowLabel(postExpressionLabel);
44645             }
44646             else {
44647                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
44648             }
44649         }
44650         function bindNonNullExpressionFlow(node) {
44651             if (ts.isOptionalChain(node)) {
44652                 bindOptionalChainFlow(node);
44653             }
44654             else {
44655                 bindEachChild(node);
44656             }
44657         }
44658         function bindAccessExpressionFlow(node) {
44659             if (ts.isOptionalChain(node)) {
44660                 bindOptionalChainFlow(node);
44661             }
44662             else {
44663                 bindEachChild(node);
44664             }
44665         }
44666         function bindCallExpressionFlow(node) {
44667             if (ts.isOptionalChain(node)) {
44668                 bindOptionalChainFlow(node);
44669             }
44670             else {
44671                 // If the target of the call expression is a function expression or arrow function we have
44672                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
44673                 // the current control flow (which includes evaluation of the IIFE arguments).
44674                 var expr = ts.skipParentheses(node.expression);
44675                 if (expr.kind === 212 /* FunctionExpression */ || expr.kind === 213 /* ArrowFunction */) {
44676                     bindEach(node.typeArguments);
44677                     bindEach(node.arguments);
44678                     bind(node.expression);
44679                 }
44680                 else {
44681                     bindEachChild(node);
44682                     if (node.expression.kind === 106 /* SuperKeyword */) {
44683                         currentFlow = createFlowCall(currentFlow, node);
44684                     }
44685                 }
44686             }
44687             if (node.expression.kind === 205 /* PropertyAccessExpression */) {
44688                 var propertyAccess = node.expression;
44689                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
44690                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
44691                 }
44692             }
44693         }
44694         function getContainerFlags(node) {
44695             switch (node.kind) {
44696                 case 225 /* ClassExpression */:
44697                 case 256 /* ClassDeclaration */:
44698                 case 259 /* EnumDeclaration */:
44699                 case 204 /* ObjectLiteralExpression */:
44700                 case 181 /* TypeLiteral */:
44701                 case 320 /* JSDocTypeLiteral */:
44702                 case 285 /* JsxAttributes */:
44703                     return 1 /* IsContainer */;
44704                 case 257 /* InterfaceDeclaration */:
44705                     return 1 /* IsContainer */ | 64 /* IsInterface */;
44706                 case 260 /* ModuleDeclaration */:
44707                 case 258 /* TypeAliasDeclaration */:
44708                 case 194 /* MappedType */:
44709                     return 1 /* IsContainer */ | 32 /* HasLocals */;
44710                 case 303 /* SourceFile */:
44711                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
44712                 case 171 /* GetAccessor */:
44713                 case 172 /* SetAccessor */:
44714                 case 168 /* MethodDeclaration */:
44715                     if (ts.isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
44716                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */;
44717                     }
44718                 // falls through
44719                 case 170 /* Constructor */:
44720                 case 255 /* FunctionDeclaration */:
44721                 case 167 /* MethodSignature */:
44722                 case 173 /* CallSignature */:
44723                 case 321 /* JSDocSignature */:
44724                 case 315 /* JSDocFunctionType */:
44725                 case 178 /* FunctionType */:
44726                 case 174 /* ConstructSignature */:
44727                 case 175 /* IndexSignature */:
44728                 case 179 /* ConstructorType */:
44729                 case 169 /* ClassStaticBlockDeclaration */:
44730                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
44731                 case 212 /* FunctionExpression */:
44732                 case 213 /* ArrowFunction */:
44733                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
44734                 case 261 /* ModuleBlock */:
44735                     return 4 /* IsControlFlowContainer */;
44736                 case 166 /* PropertyDeclaration */:
44737                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
44738                 case 291 /* CatchClause */:
44739                 case 241 /* ForStatement */:
44740                 case 242 /* ForInStatement */:
44741                 case 243 /* ForOfStatement */:
44742                 case 262 /* CaseBlock */:
44743                     return 2 /* IsBlockScopedContainer */;
44744                 case 234 /* Block */:
44745                     // do not treat blocks directly inside a function as a block-scoped-container.
44746                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
44747                     // would not appear to be a redeclaration of a block scoped local in the following
44748                     // example:
44749                     //
44750                     //      function foo() {
44751                     //          var x;
44752                     //          let x;
44753                     //      }
44754                     //
44755                     // If we placed 'var x' into the function locals and 'let x' into the locals of
44756                     // the block, then there would be no collision.
44757                     //
44758                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
44759                     // and 'let x' go into the Function-container's locals, and we do get a collision
44760                     // conflict.
44761                     return ts.isFunctionLike(node.parent) || ts.isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
44762             }
44763             return 0 /* None */;
44764         }
44765         function addToContainerChain(next) {
44766             if (lastContainer) {
44767                 lastContainer.nextContainer = next;
44768             }
44769             lastContainer = next;
44770         }
44771         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
44772             switch (container.kind) {
44773                 // Modules, source files, and classes need specialized handling for how their
44774                 // members are declared (for example, a member of a class will go into a specific
44775                 // symbol table depending on if it is static or not). We defer to specialized
44776                 // handlers to take care of declaring these child members.
44777                 case 260 /* ModuleDeclaration */:
44778                     return declareModuleMember(node, symbolFlags, symbolExcludes);
44779                 case 303 /* SourceFile */:
44780                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
44781                 case 225 /* ClassExpression */:
44782                 case 256 /* ClassDeclaration */:
44783                     return declareClassMember(node, symbolFlags, symbolExcludes);
44784                 case 259 /* EnumDeclaration */:
44785                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
44786                 case 181 /* TypeLiteral */:
44787                 case 320 /* JSDocTypeLiteral */:
44788                 case 204 /* ObjectLiteralExpression */:
44789                 case 257 /* InterfaceDeclaration */:
44790                 case 285 /* JsxAttributes */:
44791                     // Interface/Object-types always have their children added to the 'members' of
44792                     // their container. They are only accessible through an instance of their
44793                     // container, and are never in scope otherwise (even inside the body of the
44794                     // object / type / interface declaring them). An exception is type parameters,
44795                     // which are in scope without qualification (similar to 'locals').
44796                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
44797                 case 178 /* FunctionType */:
44798                 case 179 /* ConstructorType */:
44799                 case 173 /* CallSignature */:
44800                 case 174 /* ConstructSignature */:
44801                 case 321 /* JSDocSignature */:
44802                 case 175 /* IndexSignature */:
44803                 case 168 /* MethodDeclaration */:
44804                 case 167 /* MethodSignature */:
44805                 case 170 /* Constructor */:
44806                 case 171 /* GetAccessor */:
44807                 case 172 /* SetAccessor */:
44808                 case 255 /* FunctionDeclaration */:
44809                 case 212 /* FunctionExpression */:
44810                 case 213 /* ArrowFunction */:
44811                 case 315 /* JSDocFunctionType */:
44812                 case 343 /* JSDocTypedefTag */:
44813                 case 336 /* JSDocCallbackTag */:
44814                 case 169 /* ClassStaticBlockDeclaration */:
44815                 case 258 /* TypeAliasDeclaration */:
44816                 case 194 /* MappedType */:
44817                     // All the children of these container types are never visible through another
44818                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
44819                     // they're only accessed 'lexically' (i.e. from code that exists underneath
44820                     // their container in the tree). To accomplish this, we simply add their declared
44821                     // symbol to the 'locals' of the container.  These symbols can then be found as
44822                     // the type checker walks up the containers, checking them for matching names.
44823                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
44824             }
44825         }
44826         function declareClassMember(node, symbolFlags, symbolExcludes) {
44827             return ts.isStatic(node)
44828                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
44829                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
44830         }
44831         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
44832             return ts.isExternalModule(file)
44833                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
44834                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
44835         }
44836         function hasExportDeclarations(node) {
44837             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
44838             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
44839         }
44840         function setExportContextFlag(node) {
44841             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
44842             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
44843             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
44844                 node.flags |= 64 /* ExportContext */;
44845             }
44846             else {
44847                 node.flags &= ~64 /* ExportContext */;
44848             }
44849         }
44850         function bindModuleDeclaration(node) {
44851             setExportContextFlag(node);
44852             if (ts.isAmbientModule(node)) {
44853                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
44854                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
44855                 }
44856                 if (ts.isModuleAugmentationExternal(node)) {
44857                     declareModuleSymbol(node);
44858                 }
44859                 else {
44860                     var pattern = void 0;
44861                     if (node.name.kind === 10 /* StringLiteral */) {
44862                         var text = node.name.text;
44863                         pattern = ts.tryParsePattern(text);
44864                         if (pattern === undefined) {
44865                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
44866                         }
44867                     }
44868                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
44869                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && !ts.isString(pattern) ? { pattern: pattern, symbol: symbol } : undefined);
44870                 }
44871             }
44872             else {
44873                 var state = declareModuleSymbol(node);
44874                 if (state !== 0 /* NonInstantiated */) {
44875                     var symbol = node.symbol;
44876                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
44877                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
44878                         // Current must be `const enum` only
44879                         && state === 2 /* ConstEnumOnly */
44880                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
44881                         && symbol.constEnumOnlyModule !== false;
44882                 }
44883             }
44884         }
44885         function declareModuleSymbol(node) {
44886             var state = getModuleInstanceState(node);
44887             var instantiated = state !== 0 /* NonInstantiated */;
44888             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
44889             return state;
44890         }
44891         function bindFunctionOrConstructorType(node) {
44892             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
44893             // to the one we would get for: { <...>(...): T }
44894             //
44895             // We do that by making an anonymous type literal symbol, and then setting the function
44896             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
44897             // from an actual type literal symbol you would have gotten had you used the long form.
44898             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
44899             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
44900             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
44901             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
44902             typeLiteralSymbol.members = ts.createSymbolTable();
44903             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
44904         }
44905         function bindObjectLiteralExpression(node) {
44906             var ElementKind;
44907             (function (ElementKind) {
44908                 ElementKind[ElementKind["Property"] = 1] = "Property";
44909                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
44910             })(ElementKind || (ElementKind = {}));
44911             if (inStrictMode && !ts.isAssignmentTarget(node)) {
44912                 var seen = new ts.Map();
44913                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
44914                     var prop = _a[_i];
44915                     if (prop.kind === 296 /* SpreadAssignment */ || prop.name.kind !== 79 /* Identifier */) {
44916                         continue;
44917                     }
44918                     var identifier = prop.name;
44919                     // ECMA-262 11.1.5 Object Initializer
44920                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
44921                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
44922                     // IsDataDescriptor(propId.descriptor) is true.
44923                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
44924                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
44925                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
44926                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
44927                     var currentKind = prop.kind === 294 /* PropertyAssignment */ || prop.kind === 295 /* ShorthandPropertyAssignment */ || prop.kind === 168 /* MethodDeclaration */
44928                         ? 1 /* Property */
44929                         : 2 /* Accessor */;
44930                     var existingKind = seen.get(identifier.escapedText);
44931                     if (!existingKind) {
44932                         seen.set(identifier.escapedText, currentKind);
44933                         continue;
44934                     }
44935                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
44936                         var span = ts.getErrorSpanForNode(file, identifier);
44937                         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));
44938                     }
44939                 }
44940             }
44941             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
44942         }
44943         function bindJsxAttributes(node) {
44944             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
44945         }
44946         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
44947             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
44948         }
44949         function bindAnonymousDeclaration(node, symbolFlags, name) {
44950             var symbol = createSymbol(symbolFlags, name);
44951             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
44952                 symbol.parent = container.symbol;
44953             }
44954             addDeclarationToSymbol(symbol, node, symbolFlags);
44955             return symbol;
44956         }
44957         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
44958             switch (blockScopeContainer.kind) {
44959                 case 260 /* ModuleDeclaration */:
44960                     declareModuleMember(node, symbolFlags, symbolExcludes);
44961                     break;
44962                 case 303 /* SourceFile */:
44963                     if (ts.isExternalOrCommonJsModule(container)) {
44964                         declareModuleMember(node, symbolFlags, symbolExcludes);
44965                         break;
44966                     }
44967                 // falls through
44968                 default:
44969                     if (!blockScopeContainer.locals) {
44970                         blockScopeContainer.locals = ts.createSymbolTable();
44971                         addToContainerChain(blockScopeContainer);
44972                     }
44973                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
44974             }
44975         }
44976         function delayedBindJSDocTypedefTag() {
44977             if (!delayedTypeAliases) {
44978                 return;
44979             }
44980             var saveContainer = container;
44981             var saveLastContainer = lastContainer;
44982             var saveBlockScopeContainer = blockScopeContainer;
44983             var saveParent = parent;
44984             var saveCurrentFlow = currentFlow;
44985             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
44986                 var typeAlias = delayedTypeAliases_1[_i];
44987                 var host = typeAlias.parent.parent;
44988                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
44989                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
44990                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
44991                 parent = typeAlias;
44992                 bind(typeAlias.typeExpression);
44993                 var declName = ts.getNameOfDeclaration(typeAlias);
44994                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
44995                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
44996                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
44997                     if (isTopLevel) {
44998                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
44999                         var oldContainer = container;
45000                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
45001                             case 1 /* ExportsProperty */:
45002                             case 2 /* ModuleExports */:
45003                                 if (!ts.isExternalOrCommonJsModule(file)) {
45004                                     container = undefined;
45005                                 }
45006                                 else {
45007                                     container = file;
45008                                 }
45009                                 break;
45010                             case 4 /* ThisProperty */:
45011                                 container = declName.parent.expression;
45012                                 break;
45013                             case 3 /* PrototypeProperty */:
45014                                 container = declName.parent.expression.name;
45015                                 break;
45016                             case 5 /* Property */:
45017                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
45018                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
45019                                         : declName.parent.expression;
45020                                 break;
45021                             case 0 /* None */:
45022                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
45023                         }
45024                         if (container) {
45025                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
45026                         }
45027                         container = oldContainer;
45028                     }
45029                 }
45030                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 79 /* Identifier */) {
45031                     parent = typeAlias.parent;
45032                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
45033                 }
45034                 else {
45035                     bind(typeAlias.fullName);
45036                 }
45037             }
45038             container = saveContainer;
45039             lastContainer = saveLastContainer;
45040             blockScopeContainer = saveBlockScopeContainer;
45041             parent = saveParent;
45042             currentFlow = saveCurrentFlow;
45043         }
45044         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
45045         // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
45046         // [Yield] or [Await] contexts, respectively.
45047         function checkContextualIdentifier(node) {
45048             // Report error only if there are no parse errors in file
45049             if (!file.parseDiagnostics.length &&
45050                 !(node.flags & 8388608 /* Ambient */) &&
45051                 !(node.flags & 4194304 /* JSDoc */) &&
45052                 !ts.isIdentifierName(node)) {
45053                 // strict mode identifiers
45054                 if (inStrictMode &&
45055                     node.originalKeywordKind >= 117 /* FirstFutureReservedWord */ &&
45056                     node.originalKeywordKind <= 125 /* LastFutureReservedWord */) {
45057                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
45058                 }
45059                 else if (node.originalKeywordKind === 132 /* AwaitKeyword */) {
45060                     if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
45061                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
45062                     }
45063                     else if (node.flags & 32768 /* AwaitContext */) {
45064                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
45065                     }
45066                 }
45067                 else if (node.originalKeywordKind === 125 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
45068                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
45069                 }
45070             }
45071         }
45072         function getStrictModeIdentifierMessage(node) {
45073             // Provide specialized messages to help the user understand why we think they're in
45074             // strict mode.
45075             if (ts.getContainingClass(node)) {
45076                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
45077             }
45078             if (file.externalModuleIndicator) {
45079                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
45080             }
45081             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
45082         }
45083         // The binder visits every node, so this is a good place to check for
45084         // the reserved private name (there is only one)
45085         function checkPrivateIdentifier(node) {
45086             if (node.escapedText === "#constructor") {
45087                 // Report error only if there are no parse errors in file
45088                 if (!file.parseDiagnostics.length) {
45089                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
45090                 }
45091             }
45092         }
45093         function checkStrictModeBinaryExpression(node) {
45094             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
45095                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
45096                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
45097                 checkStrictModeEvalOrArguments(node, node.left);
45098             }
45099         }
45100         function checkStrictModeCatchClause(node) {
45101             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
45102             // Catch production is eval or arguments
45103             if (inStrictMode && node.variableDeclaration) {
45104                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
45105             }
45106         }
45107         function checkStrictModeDeleteExpression(node) {
45108             // Grammar checking
45109             if (inStrictMode && node.expression.kind === 79 /* Identifier */) {
45110                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
45111                 // UnaryExpression is a direct reference to a variable, function argument, or function name
45112                 var span = ts.getErrorSpanForNode(file, node.expression);
45113                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
45114             }
45115         }
45116         function isEvalOrArgumentsIdentifier(node) {
45117             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
45118         }
45119         function checkStrictModeEvalOrArguments(contextNode, name) {
45120             if (name && name.kind === 79 /* Identifier */) {
45121                 var identifier = name;
45122                 if (isEvalOrArgumentsIdentifier(identifier)) {
45123                     // We check first if the name is inside class declaration or class expression; if so give explicit message
45124                     // otherwise report generic error message.
45125                     var span = ts.getErrorSpanForNode(file, name);
45126                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
45127                 }
45128             }
45129         }
45130         function getStrictModeEvalOrArgumentsMessage(node) {
45131             // Provide specialized messages to help the user understand why we think they're in
45132             // strict mode.
45133             if (ts.getContainingClass(node)) {
45134                 return ts.Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode;
45135             }
45136             if (file.externalModuleIndicator) {
45137                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
45138             }
45139             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
45140         }
45141         function checkStrictModeFunctionName(node) {
45142             if (inStrictMode) {
45143                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
45144                 checkStrictModeEvalOrArguments(node, node.name);
45145             }
45146         }
45147         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
45148             // Provide specialized messages to help the user understand why we think they're in
45149             // strict mode.
45150             if (ts.getContainingClass(node)) {
45151                 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;
45152             }
45153             if (file.externalModuleIndicator) {
45154                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
45155             }
45156             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
45157         }
45158         function checkStrictModeFunctionDeclaration(node) {
45159             if (languageVersion < 2 /* ES2015 */) {
45160                 // Report error if function is not top level function declaration
45161                 if (blockScopeContainer.kind !== 303 /* SourceFile */ &&
45162                     blockScopeContainer.kind !== 260 /* ModuleDeclaration */ &&
45163                     !ts.isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) {
45164                     // We check first if the name is inside class declaration or class expression; if so give explicit message
45165                     // otherwise report generic error message.
45166                     var errorSpan = ts.getErrorSpanForNode(file, node);
45167                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
45168                 }
45169             }
45170         }
45171         function checkStrictModeNumericLiteral(node) {
45172             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
45173                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
45174             }
45175         }
45176         function checkStrictModePostfixUnaryExpression(node) {
45177             // Grammar checking
45178             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
45179             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
45180             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
45181             if (inStrictMode) {
45182                 checkStrictModeEvalOrArguments(node, node.operand);
45183             }
45184         }
45185         function checkStrictModePrefixUnaryExpression(node) {
45186             // Grammar checking
45187             if (inStrictMode) {
45188                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
45189                     checkStrictModeEvalOrArguments(node, node.operand);
45190                 }
45191             }
45192         }
45193         function checkStrictModeWithStatement(node) {
45194             // Grammar checking for withStatement
45195             if (inStrictMode) {
45196                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
45197             }
45198         }
45199         function checkStrictModeLabeledStatement(node) {
45200             // Grammar checking for labeledStatement
45201             if (inStrictMode && ts.getEmitScriptTarget(options) >= 2 /* ES2015 */) {
45202                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
45203                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
45204                 }
45205             }
45206         }
45207         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
45208             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
45209             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
45210         }
45211         function errorOrSuggestionOnNode(isError, node, message) {
45212             errorOrSuggestionOnRange(isError, node, node, message);
45213         }
45214         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
45215             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
45216         }
45217         function addErrorOrSuggestionDiagnostic(isError, range, message) {
45218             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
45219             if (isError) {
45220                 file.bindDiagnostics.push(diag);
45221             }
45222             else {
45223                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
45224             }
45225         }
45226         function bind(node) {
45227             if (!node) {
45228                 return;
45229             }
45230             ts.setParent(node, parent);
45231             var saveInStrictMode = inStrictMode;
45232             // Even though in the AST the jsdoc @typedef node belongs to the current node,
45233             // its symbol might be in the same scope with the current node's symbol. Consider:
45234             //
45235             //     /** @typedef {string | number} MyType */
45236             //     function foo();
45237             //
45238             // Here the current node is "foo", which is a container, but the scope of "MyType" should
45239             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
45240             // and skip binding this tag later when binding all the other jsdoc tags.
45241             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
45242             // and then potentially add the symbol to an appropriate symbol table. Possible
45243             // destination symbol tables are:
45244             //
45245             //  1) The 'exports' table of the current container's symbol.
45246             //  2) The 'members' table of the current container's symbol.
45247             //  3) The 'locals' table of the current container.
45248             //
45249             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
45250             // (like TypeLiterals for example) will not be put in any table.
45251             bindWorker(node);
45252             // Then we recurse into the children of the node to bind them as well. For certain
45253             // symbols we do specialized work when we recurse. For example, we'll keep track of
45254             // the current 'container' node when it changes. This helps us know which symbol table
45255             // a local should go into for example. Since terminal nodes are known not to have
45256             // children, as an optimization we don't process those.
45257             if (node.kind > 159 /* LastToken */) {
45258                 var saveParent = parent;
45259                 parent = node;
45260                 var containerFlags = getContainerFlags(node);
45261                 if (containerFlags === 0 /* None */) {
45262                     bindChildren(node);
45263                 }
45264                 else {
45265                     bindContainer(node, containerFlags);
45266                 }
45267                 parent = saveParent;
45268             }
45269             else {
45270                 var saveParent = parent;
45271                 if (node.kind === 1 /* EndOfFileToken */)
45272                     parent = node;
45273                 bindJSDoc(node);
45274                 parent = saveParent;
45275             }
45276             inStrictMode = saveInStrictMode;
45277         }
45278         function bindJSDoc(node) {
45279             if (ts.hasJSDocNodes(node)) {
45280                 if (ts.isInJSFile(node)) {
45281                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
45282                         var j = _a[_i];
45283                         bind(j);
45284                     }
45285                 }
45286                 else {
45287                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
45288                         var j = _c[_b];
45289                         ts.setParent(j, node);
45290                         ts.setParentRecursive(j, /*incremental*/ false);
45291                     }
45292                 }
45293             }
45294         }
45295         function updateStrictModeStatementList(statements) {
45296             if (!inStrictMode) {
45297                 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
45298                     var statement = statements_3[_i];
45299                     if (!ts.isPrologueDirective(statement)) {
45300                         return;
45301                     }
45302                     if (isUseStrictPrologueDirective(statement)) {
45303                         inStrictMode = true;
45304                         return;
45305                     }
45306                 }
45307             }
45308         }
45309         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
45310         function isUseStrictPrologueDirective(node) {
45311             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
45312             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
45313             // string to contain unicode escapes (as per ES5).
45314             return nodeText === '"use strict"' || nodeText === "'use strict'";
45315         }
45316         function bindWorker(node) {
45317             switch (node.kind) {
45318                 /* Strict mode checks */
45319                 case 79 /* Identifier */:
45320                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
45321                     // because it requires all containing namespaces to be in effect, namely the
45322                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
45323                     if (node.isInJSDocNamespace) {
45324                         var parentNode = node.parent;
45325                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
45326                             parentNode = parentNode.parent;
45327                         }
45328                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
45329                         break;
45330                     }
45331                 // falls through
45332                 case 108 /* ThisKeyword */:
45333                     if (currentFlow && (ts.isExpression(node) || parent.kind === 295 /* ShorthandPropertyAssignment */)) {
45334                         node.flowNode = currentFlow;
45335                     }
45336                     return checkContextualIdentifier(node);
45337                 case 160 /* QualifiedName */:
45338                     if (currentFlow && ts.isPartOfTypeQuery(node)) {
45339                         node.flowNode = currentFlow;
45340                     }
45341                     break;
45342                 case 230 /* MetaProperty */:
45343                 case 106 /* SuperKeyword */:
45344                     node.flowNode = currentFlow;
45345                     break;
45346                 case 80 /* PrivateIdentifier */:
45347                     return checkPrivateIdentifier(node);
45348                 case 205 /* PropertyAccessExpression */:
45349                 case 206 /* ElementAccessExpression */:
45350                     var expr = node;
45351                     if (currentFlow && isNarrowableReference(expr)) {
45352                         expr.flowNode = currentFlow;
45353                     }
45354                     if (ts.isSpecialPropertyDeclaration(expr)) {
45355                         bindSpecialPropertyDeclaration(expr);
45356                     }
45357                     if (ts.isInJSFile(expr) &&
45358                         file.commonJsModuleIndicator &&
45359                         ts.isModuleExportsAccessExpression(expr) &&
45360                         !lookupSymbolForName(blockScopeContainer, "module")) {
45361                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
45362                     }
45363                     break;
45364                 case 220 /* BinaryExpression */:
45365                     var specialKind = ts.getAssignmentDeclarationKind(node);
45366                     switch (specialKind) {
45367                         case 1 /* ExportsProperty */:
45368                             bindExportsPropertyAssignment(node);
45369                             break;
45370                         case 2 /* ModuleExports */:
45371                             bindModuleExportsAssignment(node);
45372                             break;
45373                         case 3 /* PrototypeProperty */:
45374                             bindPrototypePropertyAssignment(node.left, node);
45375                             break;
45376                         case 6 /* Prototype */:
45377                             bindPrototypeAssignment(node);
45378                             break;
45379                         case 4 /* ThisProperty */:
45380                             bindThisPropertyAssignment(node);
45381                             break;
45382                         case 5 /* Property */:
45383                             var expression = node.left.expression;
45384                             if (ts.isInJSFile(node) && ts.isIdentifier(expression)) {
45385                                 var symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
45386                                 if (ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration)) {
45387                                     bindThisPropertyAssignment(node);
45388                                     break;
45389                                 }
45390                             }
45391                             bindSpecialPropertyAssignment(node);
45392                             break;
45393                         case 0 /* None */:
45394                             // Nothing to do
45395                             break;
45396                         default:
45397                             ts.Debug.fail("Unknown binary expression special property assignment kind");
45398                     }
45399                     return checkStrictModeBinaryExpression(node);
45400                 case 291 /* CatchClause */:
45401                     return checkStrictModeCatchClause(node);
45402                 case 214 /* DeleteExpression */:
45403                     return checkStrictModeDeleteExpression(node);
45404                 case 8 /* NumericLiteral */:
45405                     return checkStrictModeNumericLiteral(node);
45406                 case 219 /* PostfixUnaryExpression */:
45407                     return checkStrictModePostfixUnaryExpression(node);
45408                 case 218 /* PrefixUnaryExpression */:
45409                     return checkStrictModePrefixUnaryExpression(node);
45410                 case 247 /* WithStatement */:
45411                     return checkStrictModeWithStatement(node);
45412                 case 249 /* LabeledStatement */:
45413                     return checkStrictModeLabeledStatement(node);
45414                 case 191 /* ThisType */:
45415                     seenThisKeyword = true;
45416                     return;
45417                 case 176 /* TypePredicate */:
45418                     break; // Binding the children will handle everything
45419                 case 162 /* TypeParameter */:
45420                     return bindTypeParameter(node);
45421                 case 163 /* Parameter */:
45422                     return bindParameter(node);
45423                 case 253 /* VariableDeclaration */:
45424                     return bindVariableDeclarationOrBindingElement(node);
45425                 case 202 /* BindingElement */:
45426                     node.flowNode = currentFlow;
45427                     return bindVariableDeclarationOrBindingElement(node);
45428                 case 166 /* PropertyDeclaration */:
45429                 case 165 /* PropertySignature */:
45430                     return bindPropertyWorker(node);
45431                 case 294 /* PropertyAssignment */:
45432                 case 295 /* ShorthandPropertyAssignment */:
45433                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
45434                 case 297 /* EnumMember */:
45435                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
45436                 case 173 /* CallSignature */:
45437                 case 174 /* ConstructSignature */:
45438                 case 175 /* IndexSignature */:
45439                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
45440                 case 168 /* MethodDeclaration */:
45441                 case 167 /* MethodSignature */:
45442                     // If this is an ObjectLiteralExpression method, then it sits in the same space
45443                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
45444                     // so that it will conflict with any other object literal members with the same
45445                     // name.
45446                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
45447                 case 255 /* FunctionDeclaration */:
45448                     return bindFunctionDeclaration(node);
45449                 case 170 /* Constructor */:
45450                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
45451                 case 171 /* GetAccessor */:
45452                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
45453                 case 172 /* SetAccessor */:
45454                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
45455                 case 178 /* FunctionType */:
45456                 case 315 /* JSDocFunctionType */:
45457                 case 321 /* JSDocSignature */:
45458                 case 179 /* ConstructorType */:
45459                     return bindFunctionOrConstructorType(node);
45460                 case 181 /* TypeLiteral */:
45461                 case 320 /* JSDocTypeLiteral */:
45462                 case 194 /* MappedType */:
45463                     return bindAnonymousTypeWorker(node);
45464                 case 330 /* JSDocClassTag */:
45465                     return bindJSDocClassTag(node);
45466                 case 204 /* ObjectLiteralExpression */:
45467                     return bindObjectLiteralExpression(node);
45468                 case 212 /* FunctionExpression */:
45469                 case 213 /* ArrowFunction */:
45470                     return bindFunctionExpression(node);
45471                 case 207 /* CallExpression */:
45472                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
45473                     switch (assignmentKind) {
45474                         case 7 /* ObjectDefinePropertyValue */:
45475                             return bindObjectDefinePropertyAssignment(node);
45476                         case 8 /* ObjectDefinePropertyExports */:
45477                             return bindObjectDefinePropertyExport(node);
45478                         case 9 /* ObjectDefinePrototypeProperty */:
45479                             return bindObjectDefinePrototypeProperty(node);
45480                         case 0 /* None */:
45481                             break; // Nothing to do
45482                         default:
45483                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
45484                     }
45485                     if (ts.isInJSFile(node)) {
45486                         bindCallExpression(node);
45487                     }
45488                     break;
45489                 // Members of classes, interfaces, and modules
45490                 case 225 /* ClassExpression */:
45491                 case 256 /* ClassDeclaration */:
45492                     // All classes are automatically in strict mode in ES6.
45493                     inStrictMode = true;
45494                     return bindClassLikeDeclaration(node);
45495                 case 257 /* InterfaceDeclaration */:
45496                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
45497                 case 258 /* TypeAliasDeclaration */:
45498                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
45499                 case 259 /* EnumDeclaration */:
45500                     return bindEnumDeclaration(node);
45501                 case 260 /* ModuleDeclaration */:
45502                     return bindModuleDeclaration(node);
45503                 // Jsx-attributes
45504                 case 285 /* JsxAttributes */:
45505                     return bindJsxAttributes(node);
45506                 case 284 /* JsxAttribute */:
45507                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
45508                 // Imports and exports
45509                 case 264 /* ImportEqualsDeclaration */:
45510                 case 267 /* NamespaceImport */:
45511                 case 269 /* ImportSpecifier */:
45512                 case 274 /* ExportSpecifier */:
45513                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
45514                 case 263 /* NamespaceExportDeclaration */:
45515                     return bindNamespaceExportDeclaration(node);
45516                 case 266 /* ImportClause */:
45517                     return bindImportClause(node);
45518                 case 271 /* ExportDeclaration */:
45519                     return bindExportDeclaration(node);
45520                 case 270 /* ExportAssignment */:
45521                     return bindExportAssignment(node);
45522                 case 303 /* SourceFile */:
45523                     updateStrictModeStatementList(node.statements);
45524                     return bindSourceFileIfExternalModule();
45525                 case 234 /* Block */:
45526                     if (!ts.isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) {
45527                         return;
45528                     }
45529                 // falls through
45530                 case 261 /* ModuleBlock */:
45531                     return updateStrictModeStatementList(node.statements);
45532                 case 338 /* JSDocParameterTag */:
45533                     if (node.parent.kind === 321 /* JSDocSignature */) {
45534                         return bindParameter(node);
45535                     }
45536                     if (node.parent.kind !== 320 /* JSDocTypeLiteral */) {
45537                         break;
45538                     }
45539                 // falls through
45540                 case 345 /* JSDocPropertyTag */:
45541                     var propTag = node;
45542                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 314 /* JSDocOptionalType */ ?
45543                         4 /* Property */ | 16777216 /* Optional */ :
45544                         4 /* Property */;
45545                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
45546                 case 343 /* JSDocTypedefTag */:
45547                 case 336 /* JSDocCallbackTag */:
45548                 case 337 /* JSDocEnumTag */:
45549                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
45550             }
45551         }
45552         function bindPropertyWorker(node) {
45553             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
45554         }
45555         function bindAnonymousTypeWorker(node) {
45556             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
45557         }
45558         function bindSourceFileIfExternalModule() {
45559             setExportContextFlag(file);
45560             if (ts.isExternalModule(file)) {
45561                 bindSourceFileAsExternalModule();
45562             }
45563             else if (ts.isJsonSourceFile(file)) {
45564                 bindSourceFileAsExternalModule();
45565                 // Create symbol equivalent for the module.exports = {}
45566                 var originalSymbol = file.symbol;
45567                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
45568                 file.symbol = originalSymbol;
45569             }
45570         }
45571         function bindSourceFileAsExternalModule() {
45572             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"".concat(ts.removeFileExtension(file.fileName), "\""));
45573         }
45574         function bindExportAssignment(node) {
45575             if (!container.symbol || !container.symbol.exports) {
45576                 // Incorrect export assignment in some sort of block construct
45577                 bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node));
45578             }
45579             else {
45580                 var flags = ts.exportAssignmentIsAlias(node)
45581                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
45582                     ? 2097152 /* Alias */
45583                     // An export default clause with any other expression exports a value
45584                     : 4 /* Property */;
45585                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
45586                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
45587                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
45588                 if (node.isExportEquals) {
45589                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
45590                     ts.setValueDeclaration(symbol, node);
45591                 }
45592             }
45593         }
45594         function bindNamespaceExportDeclaration(node) {
45595             if (node.modifiers && node.modifiers.length) {
45596                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
45597             }
45598             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
45599                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
45600                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
45601                         : undefined;
45602             if (diag) {
45603                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
45604             }
45605             else {
45606                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
45607                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
45608             }
45609         }
45610         function bindExportDeclaration(node) {
45611             if (!container.symbol || !container.symbol.exports) {
45612                 // Export * in some sort of block construct
45613                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
45614             }
45615             else if (!node.exportClause) {
45616                 // All export * declarations are collected in an __export symbol
45617                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
45618             }
45619             else if (ts.isNamespaceExport(node.exportClause)) {
45620                 // declareSymbol walks up parents to find name text, parent _must_ be set
45621                 // but won't be set by the normal binder walk until `bindChildren` later on.
45622                 ts.setParent(node.exportClause, node);
45623                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
45624             }
45625         }
45626         function bindImportClause(node) {
45627             if (node.name) {
45628                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
45629             }
45630         }
45631         function setCommonJsModuleIndicator(node) {
45632             if (file.externalModuleIndicator) {
45633                 return false;
45634             }
45635             if (!file.commonJsModuleIndicator) {
45636                 file.commonJsModuleIndicator = node;
45637                 bindSourceFileAsExternalModule();
45638             }
45639             return true;
45640         }
45641         function bindObjectDefinePropertyExport(node) {
45642             if (!setCommonJsModuleIndicator(node)) {
45643                 return;
45644             }
45645             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
45646                 if (symbol) {
45647                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
45648                 }
45649                 return symbol;
45650             });
45651             if (symbol) {
45652                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
45653                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
45654             }
45655         }
45656         function bindExportsPropertyAssignment(node) {
45657             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
45658             // expression is the declaration
45659             if (!setCommonJsModuleIndicator(node)) {
45660                 return;
45661             }
45662             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
45663                 if (symbol) {
45664                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
45665                 }
45666                 return symbol;
45667             });
45668             if (symbol) {
45669                 var isAlias = ts.isAliasableExpression(node.right) && (ts.isExportsIdentifier(node.left.expression) || ts.isModuleExportsAccessExpression(node.left.expression));
45670                 var flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
45671                 ts.setParent(node.left, node);
45672                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
45673             }
45674         }
45675         function bindModuleExportsAssignment(node) {
45676             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
45677             // is still pointing to 'module.exports'.
45678             // We do not want to consider this as 'export=' since a module can have only one of these.
45679             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
45680             if (!setCommonJsModuleIndicator(node)) {
45681                 return;
45682             }
45683             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
45684             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
45685                 return;
45686             }
45687             if (ts.isObjectLiteralExpression(assignedExpression) && ts.every(assignedExpression.properties, ts.isShorthandPropertyAssignment)) {
45688                 ts.forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
45689                 return;
45690             }
45691             // 'module.exports = expr' assignment
45692             var flags = ts.exportAssignmentIsAlias(node)
45693                 ? 2097152 /* Alias */
45694                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
45695             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
45696             ts.setValueDeclaration(symbol, node);
45697         }
45698         function bindExportAssignedObjectMemberAlias(node) {
45699             declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
45700         }
45701         function bindThisPropertyAssignment(node) {
45702             ts.Debug.assert(ts.isInJSFile(node));
45703             // private identifiers *must* be declared (even in JS files)
45704             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
45705                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
45706             if (hasPrivateIdentifier) {
45707                 return;
45708             }
45709             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
45710             switch (thisContainer.kind) {
45711                 case 255 /* FunctionDeclaration */:
45712                 case 212 /* FunctionExpression */:
45713                     var constructorSymbol = thisContainer.symbol;
45714                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
45715                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 63 /* EqualsToken */) {
45716                         var l = thisContainer.parent.left;
45717                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
45718                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
45719                         }
45720                     }
45721                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
45722                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
45723                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
45724                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
45725                         if (ts.hasDynamicName(node)) {
45726                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol, constructorSymbol.members);
45727                         }
45728                         else {
45729                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
45730                         }
45731                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
45732                     }
45733                     break;
45734                 case 170 /* Constructor */:
45735                 case 166 /* PropertyDeclaration */:
45736                 case 168 /* MethodDeclaration */:
45737                 case 171 /* GetAccessor */:
45738                 case 172 /* SetAccessor */:
45739                 case 169 /* ClassStaticBlockDeclaration */:
45740                     // this.foo assignment in a JavaScript class
45741                     // Bind this property to the containing class
45742                     var containingClass = thisContainer.parent;
45743                     var symbolTable = ts.isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members;
45744                     if (ts.hasDynamicName(node)) {
45745                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable);
45746                     }
45747                     else {
45748                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
45749                     }
45750                     break;
45751                 case 303 /* SourceFile */:
45752                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
45753                     if (ts.hasDynamicName(node)) {
45754                         break;
45755                     }
45756                     else if (thisContainer.commonJsModuleIndicator) {
45757                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
45758                     }
45759                     else {
45760                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
45761                     }
45762                     break;
45763                 default:
45764                     ts.Debug.failBadSyntaxKind(thisContainer);
45765             }
45766         }
45767         function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) {
45768             declareSymbol(symbolTable, symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true, /*isComputedName*/ true);
45769             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
45770         }
45771         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
45772             if (symbol) {
45773                 (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
45774             }
45775         }
45776         function bindSpecialPropertyDeclaration(node) {
45777             if (node.expression.kind === 108 /* ThisKeyword */) {
45778                 bindThisPropertyAssignment(node);
45779             }
45780             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 303 /* SourceFile */) {
45781                 if (ts.isPrototypeAccess(node.expression)) {
45782                     bindPrototypePropertyAssignment(node, node.parent);
45783                 }
45784                 else {
45785                     bindStaticPropertyAssignment(node);
45786                 }
45787             }
45788         }
45789         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
45790         function bindPrototypeAssignment(node) {
45791             ts.setParent(node.left, node);
45792             ts.setParent(node.right, node);
45793             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
45794         }
45795         function bindObjectDefinePrototypeProperty(node) {
45796             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
45797             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
45798                 // Ensure the namespace symbol becomes class-like
45799                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
45800             }
45801             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
45802         }
45803         /**
45804          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
45805          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
45806          */
45807         function bindPrototypePropertyAssignment(lhs, parent) {
45808             // Look up the function in the local scope, since prototype assignments should
45809             // follow the function declaration
45810             var classPrototype = lhs.expression;
45811             var constructorFunction = classPrototype.expression;
45812             // Fix up parent pointers since we're going to use these nodes before we bind into them
45813             ts.setParent(constructorFunction, classPrototype);
45814             ts.setParent(classPrototype, lhs);
45815             ts.setParent(lhs, parent);
45816             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
45817         }
45818         function bindObjectDefinePropertyAssignment(node) {
45819             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
45820             var isToplevel = node.parent.parent.kind === 303 /* SourceFile */;
45821             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
45822             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
45823         }
45824         function bindSpecialPropertyAssignment(node) {
45825             var _a;
45826             // Class declarations in Typescript do not allow property declarations
45827             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
45828             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
45829                 return;
45830             }
45831             var rootExpr = ts.getLeftmostAccessExpression(node.left);
45832             if (ts.isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) === null || _a === void 0 ? void 0 : _a.flags) & 2097152 /* Alias */) {
45833                 return;
45834             }
45835             // Fix up parent pointers since we're going to use these nodes before we bind into them
45836             ts.setParent(node.left, node);
45837             ts.setParent(node.right, node);
45838             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
45839                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
45840                 //    var util = module.exports;
45841                 //    util.property = function ...
45842                 bindExportsPropertyAssignment(node);
45843             }
45844             else if (ts.hasDynamicName(node)) {
45845                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
45846                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
45847                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
45848             }
45849             else {
45850                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
45851             }
45852         }
45853         /**
45854          * 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.
45855          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
45856          */
45857         function bindStaticPropertyAssignment(node) {
45858             ts.Debug.assert(!ts.isIdentifier(node));
45859             ts.setParent(node.expression, node);
45860             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
45861         }
45862         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
45863             if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
45864                 return namespaceSymbol;
45865             }
45866             if (isToplevel && !isPrototypeProperty) {
45867                 // make symbols or add declarations for intermediate containers
45868                 var flags_2 = 1536 /* Module */ | 67108864 /* Assignment */;
45869                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
45870                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
45871                     if (symbol) {
45872                         addDeclarationToSymbol(symbol, id, flags_2);
45873                         return symbol;
45874                     }
45875                     else {
45876                         var table = parent ? parent.exports :
45877                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
45878                         return declareSymbol(table, parent, id, flags_2, excludeFlags_1);
45879                     }
45880                 });
45881             }
45882             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
45883                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
45884             }
45885             return namespaceSymbol;
45886         }
45887         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
45888             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
45889                 return;
45890             }
45891             // Set up the members collection if it doesn't exist already
45892             var symbolTable = isPrototypeProperty ?
45893                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
45894                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
45895             var includes = 0 /* None */;
45896             var excludes = 0 /* None */;
45897             // Method-like
45898             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
45899                 includes = 8192 /* Method */;
45900                 excludes = 103359 /* MethodExcludes */;
45901             }
45902             // Maybe accessor-like
45903             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
45904                 if (ts.some(declaration.arguments[2].properties, function (p) {
45905                     var id = ts.getNameOfDeclaration(p);
45906                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
45907                 })) {
45908                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
45909                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
45910                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
45911                     excludes |= 78783 /* SetAccessorExcludes */;
45912                 }
45913                 if (ts.some(declaration.arguments[2].properties, function (p) {
45914                     var id = ts.getNameOfDeclaration(p);
45915                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
45916                 })) {
45917                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
45918                     excludes |= 46015 /* GetAccessorExcludes */;
45919                 }
45920             }
45921             if (includes === 0 /* None */) {
45922                 includes = 4 /* Property */;
45923                 excludes = 0 /* PropertyExcludes */;
45924             }
45925             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
45926         }
45927         function isTopLevelNamespaceAssignment(propertyAccess) {
45928             return ts.isBinaryExpression(propertyAccess.parent)
45929                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 303 /* SourceFile */
45930                 : propertyAccess.parent.parent.kind === 303 /* SourceFile */;
45931         }
45932         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
45933             var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
45934             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
45935             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
45936             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
45937         }
45938         /**
45939          * Javascript expando values are:
45940          * - Functions
45941          * - classes
45942          * - namespaces
45943          * - variables initialized with function expressions
45944          * -                       with class expressions
45945          * -                       with empty object literals
45946          * -                       with non-empty object literals if assigned to the prototype property
45947          */
45948         function isExpandoSymbol(symbol) {
45949             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
45950                 return true;
45951             }
45952             var node = symbol.valueDeclaration;
45953             if (node && ts.isCallExpression(node)) {
45954                 return !!ts.getAssignedExpandoInitializer(node);
45955             }
45956             var init = !node ? undefined :
45957                 ts.isVariableDeclaration(node) ? node.initializer :
45958                     ts.isBinaryExpression(node) ? node.right :
45959                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
45960                             undefined;
45961             init = init && ts.getRightMostAssignedExpression(init);
45962             if (init) {
45963                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
45964                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
45965             }
45966             return false;
45967         }
45968         function getParentOfBinaryExpression(expr) {
45969             while (ts.isBinaryExpression(expr.parent)) {
45970                 expr = expr.parent;
45971             }
45972             return expr.parent;
45973         }
45974         function lookupSymbolForPropertyAccess(node, lookupContainer) {
45975             if (lookupContainer === void 0) { lookupContainer = container; }
45976             if (ts.isIdentifier(node)) {
45977                 return lookupSymbolForName(lookupContainer, node.escapedText);
45978             }
45979             else {
45980                 var symbol = lookupSymbolForPropertyAccess(node.expression);
45981                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
45982             }
45983         }
45984         function forEachIdentifierInEntityName(e, parent, action) {
45985             if (isExportsOrModuleExportsOrAlias(file, e)) {
45986                 return file.symbol;
45987             }
45988             else if (ts.isIdentifier(e)) {
45989                 return action(e, lookupSymbolForPropertyAccess(e), parent);
45990             }
45991             else {
45992                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
45993                 var name = ts.getNameOrArgument(e);
45994                 // unreachable
45995                 if (ts.isPrivateIdentifier(name)) {
45996                     ts.Debug.fail("unexpected PrivateIdentifier");
45997                 }
45998                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
45999             }
46000         }
46001         function bindCallExpression(node) {
46002             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
46003             // this check if we've already seen the module indicator
46004             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
46005                 setCommonJsModuleIndicator(node);
46006             }
46007         }
46008         function bindClassLikeDeclaration(node) {
46009             if (node.kind === 256 /* ClassDeclaration */) {
46010                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
46011             }
46012             else {
46013                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
46014                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
46015                 // Add name of class expression into the map for semantic classifier
46016                 if (node.name) {
46017                     classifiableNames.add(node.name.escapedText);
46018                 }
46019             }
46020             var symbol = node.symbol;
46021             // TypeScript 1.0 spec (April 2014): 8.4
46022             // Every class automatically contains a static property member named 'prototype', the
46023             // type of which is an instantiation of the class type with type Any supplied as a type
46024             // argument for each type parameter. It is an error to explicitly declare a static
46025             // property member with the name 'prototype'.
46026             //
46027             // Note: we check for this here because this class may be merging into a module.  The
46028             // module might have an exported variable called 'prototype'.  We can't allow that as
46029             // that would clash with the built-in 'prototype' for the class.
46030             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
46031             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
46032             if (symbolExport) {
46033                 if (node.name) {
46034                     ts.setParent(node.name, node);
46035                 }
46036                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
46037             }
46038             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
46039             prototypeSymbol.parent = symbol;
46040         }
46041         function bindEnumDeclaration(node) {
46042             return ts.isEnumConst(node)
46043                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
46044                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
46045         }
46046         function bindVariableDeclarationOrBindingElement(node) {
46047             if (inStrictMode) {
46048                 checkStrictModeEvalOrArguments(node, node.name);
46049             }
46050             if (!ts.isBindingPattern(node.name)) {
46051                 if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) {
46052                     declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
46053                 }
46054                 else if (ts.isBlockOrCatchScoped(node)) {
46055                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
46056                 }
46057                 else if (ts.isParameterDeclaration(node)) {
46058                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
46059                     // because its parent chain has already been set up, since parents are set before descending into children.
46060                     //
46061                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
46062                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
46063                     // For example:
46064                     //      function foo([a,a]) {} // Duplicate Identifier error
46065                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
46066                     //                             // which correctly set excluded symbols
46067                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
46068                 }
46069                 else {
46070                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
46071                 }
46072             }
46073         }
46074         function bindParameter(node) {
46075             if (node.kind === 338 /* JSDocParameterTag */ && container.kind !== 321 /* JSDocSignature */) {
46076                 return;
46077             }
46078             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
46079                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
46080                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
46081                 checkStrictModeEvalOrArguments(node, node.name);
46082             }
46083             if (ts.isBindingPattern(node.name)) {
46084                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
46085             }
46086             else {
46087                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
46088             }
46089             // If this is a property-parameter, then also declare the property symbol into the
46090             // containing class.
46091             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
46092                 var classDeclaration = node.parent.parent;
46093                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
46094             }
46095         }
46096         function bindFunctionDeclaration(node) {
46097             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
46098                 if (ts.isAsyncFunction(node)) {
46099                     emitFlags |= 2048 /* HasAsyncFunctions */;
46100                 }
46101             }
46102             checkStrictModeFunctionName(node);
46103             if (inStrictMode) {
46104                 checkStrictModeFunctionDeclaration(node);
46105                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
46106             }
46107             else {
46108                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
46109             }
46110         }
46111         function bindFunctionExpression(node) {
46112             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
46113                 if (ts.isAsyncFunction(node)) {
46114                     emitFlags |= 2048 /* HasAsyncFunctions */;
46115                 }
46116             }
46117             if (currentFlow) {
46118                 node.flowNode = currentFlow;
46119             }
46120             checkStrictModeFunctionName(node);
46121             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
46122             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
46123         }
46124         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
46125             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
46126                 emitFlags |= 2048 /* HasAsyncFunctions */;
46127             }
46128             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
46129                 node.flowNode = currentFlow;
46130             }
46131             return ts.hasDynamicName(node)
46132                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
46133                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
46134         }
46135         function getInferTypeContainer(node) {
46136             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
46137             return extendsType && extendsType.parent;
46138         }
46139         function bindTypeParameter(node) {
46140             if (ts.isJSDocTemplateTag(node.parent)) {
46141                 var container_1 = ts.getEffectiveContainerForJSDocTemplateTag(node.parent);
46142                 if (container_1) {
46143                     if (!container_1.locals) {
46144                         container_1.locals = ts.createSymbolTable();
46145                     }
46146                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
46147                 }
46148                 else {
46149                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
46150                 }
46151             }
46152             else if (node.parent.kind === 189 /* InferType */) {
46153                 var container_2 = getInferTypeContainer(node.parent);
46154                 if (container_2) {
46155                     if (!container_2.locals) {
46156                         container_2.locals = ts.createSymbolTable();
46157                     }
46158                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
46159                 }
46160                 else {
46161                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
46162                 }
46163             }
46164             else {
46165                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
46166             }
46167         }
46168         // reachability checks
46169         function shouldReportErrorOnModuleDeclaration(node) {
46170             var instanceState = getModuleInstanceState(node);
46171             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options));
46172         }
46173         function checkUnreachable(node) {
46174             if (!(currentFlow.flags & 1 /* Unreachable */)) {
46175                 return false;
46176             }
46177             if (currentFlow === unreachableFlow) {
46178                 var reportError = 
46179                 // report error on all statements except empty ones
46180                 (ts.isStatementButNotDeclaration(node) && node.kind !== 235 /* EmptyStatement */) ||
46181                     // report error on class declarations
46182                     node.kind === 256 /* ClassDeclaration */ ||
46183                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
46184                     (node.kind === 260 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
46185                 if (reportError) {
46186                     currentFlow = reportedUnreachableFlow;
46187                     if (!options.allowUnreachableCode) {
46188                         // unreachable code is reported if
46189                         // - user has explicitly asked about it AND
46190                         // - statement is in not ambient context (statements in ambient context is already an error
46191                         //   so we should not report extras) AND
46192                         //   - node is not variable statement OR
46193                         //   - node is block scoped variable statement OR
46194                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
46195                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
46196                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
46197                         var isError_1 = ts.unreachableCodeIsError(options) &&
46198                             !(node.flags & 8388608 /* Ambient */) &&
46199                             (!ts.isVariableStatement(node) ||
46200                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
46201                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
46202                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
46203                     }
46204                 }
46205             }
46206             return true;
46207         }
46208     }
46209     function eachUnreachableRange(node, cb) {
46210         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
46211             var statements = node.parent.statements;
46212             var slice_1 = ts.sliceAfter(statements, node);
46213             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
46214         }
46215         else {
46216             cb(node, node);
46217         }
46218     }
46219     // As opposed to a pure declaration like an `interface`
46220     function isExecutableStatement(s) {
46221         // Don't remove statements that can validly be used before they appear.
46222         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
46223             // `var x;` may declare a variable used above
46224             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
46225     }
46226     function isPurelyTypeDeclaration(s) {
46227         switch (s.kind) {
46228             case 257 /* InterfaceDeclaration */:
46229             case 258 /* TypeAliasDeclaration */:
46230                 return true;
46231             case 260 /* ModuleDeclaration */:
46232                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
46233             case 259 /* EnumDeclaration */:
46234                 return ts.hasSyntacticModifier(s, 2048 /* Const */);
46235             default:
46236                 return false;
46237         }
46238     }
46239     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
46240         var i = 0;
46241         var q = [node];
46242         while (q.length && i < 100) {
46243             i++;
46244             node = q.shift();
46245             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
46246                 return true;
46247             }
46248             else if (ts.isIdentifier(node)) {
46249                 var symbol = lookupSymbolForName(sourceFile, node.escapedText);
46250                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
46251                     var init = symbol.valueDeclaration.initializer;
46252                     q.push(init);
46253                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
46254                         q.push(init.left);
46255                         q.push(init.right);
46256                     }
46257                 }
46258             }
46259         }
46260         return false;
46261     }
46262     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
46263     function lookupSymbolForName(container, name) {
46264         var local = container.locals && container.locals.get(name);
46265         if (local) {
46266             return local.exportSymbol || local;
46267         }
46268         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
46269             return container.jsGlobalAugmentations.get(name);
46270         }
46271         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
46272     }
46273 })(ts || (ts = {}));
46274 /** @internal */
46275 var ts;
46276 (function (ts) {
46277     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
46278         return getSymbolWalker;
46279         function getSymbolWalker(accept) {
46280             if (accept === void 0) { accept = function () { return true; }; }
46281             var visitedTypes = []; // Sparse array from id to type
46282             var visitedSymbols = []; // Sparse array from id to symbol
46283             return {
46284                 walkType: function (type) {
46285                     try {
46286                         visitType(type);
46287                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
46288                     }
46289                     finally {
46290                         ts.clear(visitedTypes);
46291                         ts.clear(visitedSymbols);
46292                     }
46293                 },
46294                 walkSymbol: function (symbol) {
46295                     try {
46296                         visitSymbol(symbol);
46297                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
46298                     }
46299                     finally {
46300                         ts.clear(visitedTypes);
46301                         ts.clear(visitedSymbols);
46302                     }
46303                 },
46304             };
46305             function visitType(type) {
46306                 if (!type) {
46307                     return;
46308                 }
46309                 if (visitedTypes[type.id]) {
46310                     return;
46311                 }
46312                 visitedTypes[type.id] = type;
46313                 // Reuse visitSymbol to visit the type's symbol,
46314                 //  but be sure to bail on recuring into the type if accept declines the symbol.
46315                 var shouldBail = visitSymbol(type.symbol);
46316                 if (shouldBail)
46317                     return;
46318                 // Visit the type's related types, if any
46319                 if (type.flags & 524288 /* Object */) {
46320                     var objectType = type;
46321                     var objectFlags = objectType.objectFlags;
46322                     if (objectFlags & 4 /* Reference */) {
46323                         visitTypeReference(type);
46324                     }
46325                     if (objectFlags & 32 /* Mapped */) {
46326                         visitMappedType(type);
46327                     }
46328                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
46329                         visitInterfaceType(type);
46330                     }
46331                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
46332                         visitObjectType(objectType);
46333                     }
46334                 }
46335                 if (type.flags & 262144 /* TypeParameter */) {
46336                     visitTypeParameter(type);
46337                 }
46338                 if (type.flags & 3145728 /* UnionOrIntersection */) {
46339                     visitUnionOrIntersectionType(type);
46340                 }
46341                 if (type.flags & 4194304 /* Index */) {
46342                     visitIndexType(type);
46343                 }
46344                 if (type.flags & 8388608 /* IndexedAccess */) {
46345                     visitIndexedAccessType(type);
46346                 }
46347             }
46348             function visitTypeReference(type) {
46349                 visitType(type.target);
46350                 ts.forEach(getTypeArguments(type), visitType);
46351             }
46352             function visitTypeParameter(type) {
46353                 visitType(getConstraintOfTypeParameter(type));
46354             }
46355             function visitUnionOrIntersectionType(type) {
46356                 ts.forEach(type.types, visitType);
46357             }
46358             function visitIndexType(type) {
46359                 visitType(type.type);
46360             }
46361             function visitIndexedAccessType(type) {
46362                 visitType(type.objectType);
46363                 visitType(type.indexType);
46364                 visitType(type.constraint);
46365             }
46366             function visitMappedType(type) {
46367                 visitType(type.typeParameter);
46368                 visitType(type.constraintType);
46369                 visitType(type.templateType);
46370                 visitType(type.modifiersType);
46371             }
46372             function visitSignature(signature) {
46373                 var typePredicate = getTypePredicateOfSignature(signature);
46374                 if (typePredicate) {
46375                     visitType(typePredicate.type);
46376                 }
46377                 ts.forEach(signature.typeParameters, visitType);
46378                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
46379                     var parameter = _a[_i];
46380                     visitSymbol(parameter);
46381                 }
46382                 visitType(getRestTypeOfSignature(signature));
46383                 visitType(getReturnTypeOfSignature(signature));
46384             }
46385             function visitInterfaceType(interfaceT) {
46386                 visitObjectType(interfaceT);
46387                 ts.forEach(interfaceT.typeParameters, visitType);
46388                 ts.forEach(getBaseTypes(interfaceT), visitType);
46389                 visitType(interfaceT.thisType);
46390             }
46391             function visitObjectType(type) {
46392                 var resolved = resolveStructuredTypeMembers(type);
46393                 for (var _i = 0, _a = resolved.indexInfos; _i < _a.length; _i++) {
46394                     var info = _a[_i];
46395                     visitType(info.keyType);
46396                     visitType(info.type);
46397                 }
46398                 for (var _b = 0, _c = resolved.callSignatures; _b < _c.length; _b++) {
46399                     var signature = _c[_b];
46400                     visitSignature(signature);
46401                 }
46402                 for (var _d = 0, _e = resolved.constructSignatures; _d < _e.length; _d++) {
46403                     var signature = _e[_d];
46404                     visitSignature(signature);
46405                 }
46406                 for (var _f = 0, _g = resolved.properties; _f < _g.length; _f++) {
46407                     var p = _g[_f];
46408                     visitSymbol(p);
46409                 }
46410             }
46411             function visitSymbol(symbol) {
46412                 if (!symbol) {
46413                     return false;
46414                 }
46415                 var symbolId = ts.getSymbolId(symbol);
46416                 if (visitedSymbols[symbolId]) {
46417                     return false;
46418                 }
46419                 visitedSymbols[symbolId] = symbol;
46420                 if (!accept(symbol)) {
46421                     return true;
46422                 }
46423                 var t = getTypeOfSymbol(symbol);
46424                 visitType(t); // Should handle members on classes and such
46425                 if (symbol.exports) {
46426                     symbol.exports.forEach(visitSymbol);
46427                 }
46428                 ts.forEach(symbol.declarations, function (d) {
46429                     // Type queries are too far resolved when we just visit the symbol's type
46430                     //  (their type resolved directly to the member deeply referenced)
46431                     // So to get the intervening symbols, we need to check if there's a type
46432                     // query node on any of the symbol's declarations and get symbols there
46433                     if (d.type && d.type.kind === 180 /* TypeQuery */) {
46434                         var query = d.type;
46435                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
46436                         visitSymbol(entity);
46437                     }
46438                 });
46439                 return false;
46440             }
46441         }
46442     }
46443     ts.createGetSymbolWalker = createGetSymbolWalker;
46444 })(ts || (ts = {}));
46445 /* @internal */
46446 var ts;
46447 (function (ts) {
46448     var ambientModuleSymbolRegex = /^".+"$/;
46449     var anon = "(anonymous)";
46450     var nextSymbolId = 1;
46451     var nextNodeId = 1;
46452     var nextMergeId = 1;
46453     var nextFlowId = 1;
46454     var IterationUse;
46455     (function (IterationUse) {
46456         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
46457         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
46458         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
46459         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
46460         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
46461         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
46462         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
46463         IterationUse[IterationUse["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
46464         // Spread, Destructuring, Array element assignment
46465         IterationUse[IterationUse["Element"] = 1] = "Element";
46466         IterationUse[IterationUse["Spread"] = 33] = "Spread";
46467         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
46468         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
46469         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
46470         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
46471         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
46472         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
46473         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
46474     })(IterationUse || (IterationUse = {}));
46475     var IterationTypeKind;
46476     (function (IterationTypeKind) {
46477         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
46478         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
46479         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
46480     })(IterationTypeKind || (IterationTypeKind = {}));
46481     var WideningKind;
46482     (function (WideningKind) {
46483         WideningKind[WideningKind["Normal"] = 0] = "Normal";
46484         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
46485         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
46486         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
46487     })(WideningKind || (WideningKind = {}));
46488     var TypeFacts;
46489     (function (TypeFacts) {
46490         TypeFacts[TypeFacts["None"] = 0] = "None";
46491         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
46492         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
46493         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
46494         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
46495         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
46496         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
46497         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
46498         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
46499         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
46500         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
46501         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
46502         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
46503         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
46504         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
46505         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
46506         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
46507         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
46508         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
46509         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
46510         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
46511         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
46512         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
46513         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
46514         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
46515         TypeFacts[TypeFacts["All"] = 16777215] = "All";
46516         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
46517         // The presence of a particular fact means that the given test is true for some (and possibly all) values
46518         // of that kind of type.
46519         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
46520         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
46521         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
46522         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
46523         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
46524         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
46525         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
46526         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
46527         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
46528         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
46529         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
46530         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
46531         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
46532         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
46533         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
46534         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
46535         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
46536         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
46537         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
46538         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
46539         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
46540         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
46541         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
46542         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
46543         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
46544         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
46545         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
46546         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
46547         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
46548         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
46549         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
46550         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
46551         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
46552         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
46553         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
46554         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
46555         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
46556         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
46557         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
46558         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
46559         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
46560         TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
46561         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
46562     })(TypeFacts || (TypeFacts = {}));
46563     var typeofEQFacts = new ts.Map(ts.getEntries({
46564         string: 1 /* TypeofEQString */,
46565         number: 2 /* TypeofEQNumber */,
46566         bigint: 4 /* TypeofEQBigInt */,
46567         boolean: 8 /* TypeofEQBoolean */,
46568         symbol: 16 /* TypeofEQSymbol */,
46569         undefined: 65536 /* EQUndefined */,
46570         object: 32 /* TypeofEQObject */,
46571         function: 64 /* TypeofEQFunction */
46572     }));
46573     var typeofNEFacts = new ts.Map(ts.getEntries({
46574         string: 256 /* TypeofNEString */,
46575         number: 512 /* TypeofNENumber */,
46576         bigint: 1024 /* TypeofNEBigInt */,
46577         boolean: 2048 /* TypeofNEBoolean */,
46578         symbol: 4096 /* TypeofNESymbol */,
46579         undefined: 524288 /* NEUndefined */,
46580         object: 8192 /* TypeofNEObject */,
46581         function: 16384 /* TypeofNEFunction */
46582     }));
46583     var TypeSystemPropertyName;
46584     (function (TypeSystemPropertyName) {
46585         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
46586         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
46587         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
46588         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
46589         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
46590         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
46591         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
46592         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
46593     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
46594     var CheckMode;
46595     (function (CheckMode) {
46596         CheckMode[CheckMode["Normal"] = 0] = "Normal";
46597         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
46598         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
46599         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
46600         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
46601         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
46602     })(CheckMode || (CheckMode = {}));
46603     var SignatureCheckMode;
46604     (function (SignatureCheckMode) {
46605         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
46606         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
46607         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
46608         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
46609         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
46610     })(SignatureCheckMode || (SignatureCheckMode = {}));
46611     var IntersectionState;
46612     (function (IntersectionState) {
46613         IntersectionState[IntersectionState["None"] = 0] = "None";
46614         IntersectionState[IntersectionState["Source"] = 1] = "Source";
46615         IntersectionState[IntersectionState["Target"] = 2] = "Target";
46616         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
46617         IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck";
46618         IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck";
46619     })(IntersectionState || (IntersectionState = {}));
46620     var RecursionFlags;
46621     (function (RecursionFlags) {
46622         RecursionFlags[RecursionFlags["None"] = 0] = "None";
46623         RecursionFlags[RecursionFlags["Source"] = 1] = "Source";
46624         RecursionFlags[RecursionFlags["Target"] = 2] = "Target";
46625         RecursionFlags[RecursionFlags["Both"] = 3] = "Both";
46626     })(RecursionFlags || (RecursionFlags = {}));
46627     var MappedTypeModifiers;
46628     (function (MappedTypeModifiers) {
46629         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
46630         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
46631         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
46632         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
46633     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
46634     var ExpandingFlags;
46635     (function (ExpandingFlags) {
46636         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
46637         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
46638         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
46639         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
46640     })(ExpandingFlags || (ExpandingFlags = {}));
46641     var MembersOrExportsResolutionKind;
46642     (function (MembersOrExportsResolutionKind) {
46643         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
46644         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
46645     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
46646     var UnusedKind;
46647     (function (UnusedKind) {
46648         UnusedKind[UnusedKind["Local"] = 0] = "Local";
46649         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
46650     })(UnusedKind || (UnusedKind = {}));
46651     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
46652     var DeclarationMeaning;
46653     (function (DeclarationMeaning) {
46654         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
46655         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
46656         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
46657         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
46658         DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic";
46659         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
46660         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
46661     })(DeclarationMeaning || (DeclarationMeaning = {}));
46662     var DeclarationSpaces;
46663     (function (DeclarationSpaces) {
46664         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
46665         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
46666         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
46667         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
46668     })(DeclarationSpaces || (DeclarationSpaces = {}));
46669     var MinArgumentCountFlags;
46670     (function (MinArgumentCountFlags) {
46671         MinArgumentCountFlags[MinArgumentCountFlags["None"] = 0] = "None";
46672         MinArgumentCountFlags[MinArgumentCountFlags["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
46673         MinArgumentCountFlags[MinArgumentCountFlags["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
46674     })(MinArgumentCountFlags || (MinArgumentCountFlags = {}));
46675     var IntrinsicTypeKind;
46676     (function (IntrinsicTypeKind) {
46677         IntrinsicTypeKind[IntrinsicTypeKind["Uppercase"] = 0] = "Uppercase";
46678         IntrinsicTypeKind[IntrinsicTypeKind["Lowercase"] = 1] = "Lowercase";
46679         IntrinsicTypeKind[IntrinsicTypeKind["Capitalize"] = 2] = "Capitalize";
46680         IntrinsicTypeKind[IntrinsicTypeKind["Uncapitalize"] = 3] = "Uncapitalize";
46681     })(IntrinsicTypeKind || (IntrinsicTypeKind = {}));
46682     var intrinsicTypeKinds = new ts.Map(ts.getEntries({
46683         Uppercase: 0 /* Uppercase */,
46684         Lowercase: 1 /* Lowercase */,
46685         Capitalize: 2 /* Capitalize */,
46686         Uncapitalize: 3 /* Uncapitalize */
46687     }));
46688     function SymbolLinks() {
46689     }
46690     function NodeLinks() {
46691         this.flags = 0;
46692     }
46693     function getNodeId(node) {
46694         if (!node.id) {
46695             node.id = nextNodeId;
46696             nextNodeId++;
46697         }
46698         return node.id;
46699     }
46700     ts.getNodeId = getNodeId;
46701     function getSymbolId(symbol) {
46702         if (!symbol.id) {
46703             symbol.id = nextSymbolId;
46704             nextSymbolId++;
46705         }
46706         return symbol.id;
46707     }
46708     ts.getSymbolId = getSymbolId;
46709     function isInstantiatedModule(node, preserveConstEnums) {
46710         var moduleState = ts.getModuleInstanceState(node);
46711         return moduleState === 1 /* Instantiated */ ||
46712             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
46713     }
46714     ts.isInstantiatedModule = isInstantiatedModule;
46715     function createTypeChecker(host, produceDiagnostics) {
46716         var getPackagesMap = ts.memoize(function () {
46717             // A package name maps to true when we detect it has .d.ts files.
46718             // This is useful as an approximation of whether a package bundles its own types.
46719             // Note: we only look at files already found by module resolution,
46720             // so there may be files we did not consider.
46721             var map = new ts.Map();
46722             host.getSourceFiles().forEach(function (sf) {
46723                 if (!sf.resolvedModules)
46724                     return;
46725                 sf.resolvedModules.forEach(function (r) {
46726                     if (r && r.packageId)
46727                         map.set(r.packageId.name, r.extension === ".d.ts" /* Dts */ || !!map.get(r.packageId.name));
46728                 });
46729             });
46730             return map;
46731         });
46732         // Cancellation that controls whether or not we can cancel in the middle of type checking.
46733         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
46734         // computing something, and we will leave our internals in an inconsistent state.  Callers
46735         // who set the cancellation token should catch if a cancellation exception occurs, and
46736         // should throw away and create a new TypeChecker.
46737         //
46738         // Currently we only support setting the cancellation token when getting diagnostics.  This
46739         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
46740         // they no longer need the information (for example, if the user started editing again).
46741         var cancellationToken;
46742         var requestedExternalEmitHelpers;
46743         var externalHelpersModule;
46744         var Symbol = ts.objectAllocator.getSymbolConstructor();
46745         var Type = ts.objectAllocator.getTypeConstructor();
46746         var Signature = ts.objectAllocator.getSignatureConstructor();
46747         var typeCount = 0;
46748         var symbolCount = 0;
46749         var enumCount = 0;
46750         var totalInstantiationCount = 0;
46751         var instantiationCount = 0;
46752         var instantiationDepth = 0;
46753         var inlineLevel = 0;
46754         var currentNode;
46755         var emptySymbols = ts.createSymbolTable();
46756         var arrayVariances = [1 /* Covariant */];
46757         var compilerOptions = host.getCompilerOptions();
46758         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
46759         var moduleKind = ts.getEmitModuleKind(compilerOptions);
46760         var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions);
46761         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
46762         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
46763         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
46764         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
46765         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
46766         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
46767         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
46768         var useUnknownInCatchVariables = ts.getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables");
46769         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
46770         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */;
46771         var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes;
46772         var checkBinaryExpression = createCheckBinaryExpression();
46773         var emitResolver = createResolver();
46774         var nodeBuilder = createNodeBuilder();
46775         var globals = ts.createSymbolTable();
46776         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
46777         undefinedSymbol.declarations = [];
46778         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
46779         globalThisSymbol.exports = globals;
46780         globalThisSymbol.declarations = [];
46781         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
46782         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
46783         var requireSymbol = createSymbol(4 /* Property */, "require");
46784         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
46785         var apparentArgumentCount;
46786         // for public members that accept a Node or one of its subtypes, we must guard against
46787         // synthetic nodes created during transformations by calling `getParseTreeNode`.
46788         // for most of these, we perform the guard only on `checker` to avoid any possible
46789         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
46790         // checker.
46791         var checker = {
46792             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
46793             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
46794             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
46795             getTypeCount: function () { return typeCount; },
46796             getInstantiationCount: function () { return totalInstantiationCount; },
46797             getRelationCacheSizes: function () { return ({
46798                 assignable: assignableRelation.size,
46799                 identity: identityRelation.size,
46800                 subtype: subtypeRelation.size,
46801                 strictSubtype: strictSubtypeRelation.size,
46802             }); },
46803             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
46804             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
46805             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
46806             getMergedSymbol: getMergedSymbol,
46807             getDiagnostics: getDiagnostics,
46808             getGlobalDiagnostics: getGlobalDiagnostics,
46809             getRecursionIdentity: getRecursionIdentity,
46810             getUnmatchedProperties: getUnmatchedProperties,
46811             getTypeOfSymbolAtLocation: function (symbol, locationIn) {
46812                 var location = ts.getParseTreeNode(locationIn);
46813                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
46814             },
46815             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
46816                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
46817                 if (parameter === undefined)
46818                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
46819                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
46820             },
46821             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
46822             getPropertiesOfType: getPropertiesOfType,
46823             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
46824             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
46825                 var node = ts.getParseTreeNode(location);
46826                 if (!node) {
46827                     return undefined;
46828                 }
46829                 var propName = ts.escapeLeadingUnderscores(name);
46830                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
46831                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
46832             },
46833             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
46834             getIndexInfoOfType: function (type, kind) { return getIndexInfoOfType(type, kind === 0 /* String */ ? stringType : numberType); },
46835             getIndexInfosOfType: getIndexInfosOfType,
46836             getSignaturesOfType: getSignaturesOfType,
46837             getIndexTypeOfType: function (type, kind) { return getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType); },
46838             getBaseTypes: getBaseTypes,
46839             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
46840             getWidenedType: getWidenedType,
46841             getTypeFromTypeNode: function (nodeIn) {
46842                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
46843                 return node ? getTypeFromTypeNode(node) : errorType;
46844             },
46845             getParameterType: getTypeAtPosition,
46846             getParameterIdentifierNameAtPosition: getParameterIdentifierNameAtPosition,
46847             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
46848             getAwaitedType: function (type) { return getAwaitedType(type); },
46849             getReturnTypeOfSignature: getReturnTypeOfSignature,
46850             isNullableType: isNullableType,
46851             getNullableType: getNullableType,
46852             getNonNullableType: getNonNullableType,
46853             getNonOptionalType: removeOptionalTypeMarker,
46854             getTypeArguments: getTypeArguments,
46855             typeToTypeNode: nodeBuilder.typeToTypeNode,
46856             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
46857             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
46858             symbolToEntityName: nodeBuilder.symbolToEntityName,
46859             symbolToExpression: nodeBuilder.symbolToExpression,
46860             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
46861             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
46862             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
46863             getSymbolsInScope: function (locationIn, meaning) {
46864                 var location = ts.getParseTreeNode(locationIn);
46865                 return location ? getSymbolsInScope(location, meaning) : [];
46866             },
46867             getSymbolAtLocation: function (nodeIn) {
46868                 var node = ts.getParseTreeNode(nodeIn);
46869                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
46870                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
46871             },
46872             getIndexInfosAtLocation: function (nodeIn) {
46873                 var node = ts.getParseTreeNode(nodeIn);
46874                 return node ? getIndexInfosAtLocation(node) : undefined;
46875             },
46876             getShorthandAssignmentValueSymbol: function (nodeIn) {
46877                 var node = ts.getParseTreeNode(nodeIn);
46878                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
46879             },
46880             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
46881                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
46882                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
46883             },
46884             getExportSymbolOfSymbol: function (symbol) {
46885                 return getMergedSymbol(symbol.exportSymbol || symbol);
46886             },
46887             getTypeAtLocation: function (nodeIn) {
46888                 var node = ts.getParseTreeNode(nodeIn);
46889                 return node ? getTypeOfNode(node) : errorType;
46890             },
46891             getTypeOfAssignmentPattern: function (nodeIn) {
46892                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
46893                 return node && getTypeOfAssignmentPattern(node) || errorType;
46894             },
46895             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
46896                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
46897                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
46898             },
46899             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
46900                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
46901             },
46902             typeToString: function (type, enclosingDeclaration, flags) {
46903                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
46904             },
46905             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
46906                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
46907             },
46908             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
46909                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
46910             },
46911             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
46912                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
46913             },
46914             writeType: function (type, enclosingDeclaration, flags, writer) {
46915                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
46916             },
46917             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
46918                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
46919             },
46920             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
46921                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
46922             },
46923             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
46924             getRootSymbols: getRootSymbols,
46925             getSymbolOfExpando: getSymbolOfExpando,
46926             getContextualType: function (nodeIn, contextFlags) {
46927                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
46928                 if (!node) {
46929                     return undefined;
46930                 }
46931                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
46932                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
46933                 if (contextFlags & 4 /* Completions */ && containingCall) {
46934                     var toMarkSkip = node;
46935                     do {
46936                         getNodeLinks(toMarkSkip).skipDirectInference = true;
46937                         toMarkSkip = toMarkSkip.parent;
46938                     } while (toMarkSkip && toMarkSkip !== containingCall);
46939                     getNodeLinks(containingCall).resolvedSignature = undefined;
46940                 }
46941                 var result = getContextualType(node, contextFlags);
46942                 if (contextFlags & 4 /* Completions */ && containingCall) {
46943                     var toMarkSkip = node;
46944                     do {
46945                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
46946                         toMarkSkip = toMarkSkip.parent;
46947                     } while (toMarkSkip && toMarkSkip !== containingCall);
46948                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
46949                 }
46950                 return result;
46951             },
46952             getContextualTypeForObjectLiteralElement: function (nodeIn) {
46953                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
46954                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
46955             },
46956             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
46957                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
46958                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
46959             },
46960             getContextualTypeForJsxAttribute: function (nodeIn) {
46961                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
46962                 return node && getContextualTypeForJsxAttribute(node);
46963             },
46964             isContextSensitive: isContextSensitive,
46965             getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType,
46966             getFullyQualifiedName: getFullyQualifiedName,
46967             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
46968                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
46969             },
46970             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
46971                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
46972             },
46973             getExpandedParameters: getExpandedParameters,
46974             hasEffectiveRestParameter: hasEffectiveRestParameter,
46975             containsArgumentsReference: containsArgumentsReference,
46976             getConstantValue: function (nodeIn) {
46977                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
46978                 return node ? getConstantValue(node) : undefined;
46979             },
46980             isValidPropertyAccess: function (nodeIn, propertyName) {
46981                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
46982                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
46983             },
46984             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
46985                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
46986                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
46987             },
46988             getSignatureFromDeclaration: function (declarationIn) {
46989                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
46990                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
46991             },
46992             isImplementationOfOverload: function (nodeIn) {
46993                 var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
46994                 return node ? isImplementationOfOverload(node) : undefined;
46995             },
46996             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
46997             getAliasedSymbol: resolveAlias,
46998             getEmitResolver: getEmitResolver,
46999             getExportsOfModule: getExportsOfModuleAsArray,
47000             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
47001             forEachExportAndPropertyOfModule: forEachExportAndPropertyOfModule,
47002             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
47003             getAmbientModules: getAmbientModules,
47004             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
47005             isOptionalParameter: function (nodeIn) {
47006                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
47007                 return node ? isOptionalParameter(node) : false;
47008             },
47009             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
47010             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
47011             tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); },
47012             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
47013                 // we deliberately exclude augmentations
47014                 // since we are only interested in declarations of the module itself
47015                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
47016             },
47017             getApparentType: getApparentType,
47018             getUnionType: getUnionType,
47019             isTypeAssignableTo: isTypeAssignableTo,
47020             createAnonymousType: createAnonymousType,
47021             createSignature: createSignature,
47022             createSymbol: createSymbol,
47023             createIndexInfo: createIndexInfo,
47024             getAnyType: function () { return anyType; },
47025             getStringType: function () { return stringType; },
47026             getNumberType: function () { return numberType; },
47027             createPromiseType: createPromiseType,
47028             createArrayType: createArrayType,
47029             getElementTypeOfArrayType: getElementTypeOfArrayType,
47030             getBooleanType: function () { return booleanType; },
47031             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
47032             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
47033             getVoidType: function () { return voidType; },
47034             getUndefinedType: function () { return undefinedType; },
47035             getNullType: function () { return nullType; },
47036             getESSymbolType: function () { return esSymbolType; },
47037             getNeverType: function () { return neverType; },
47038             getOptionalType: function () { return optionalType; },
47039             getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); },
47040             getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); },
47041             isSymbolAccessible: isSymbolAccessible,
47042             isArrayType: isArrayType,
47043             isTupleType: isTupleType,
47044             isArrayLikeType: isArrayLikeType,
47045             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
47046             getExactOptionalProperties: getExactOptionalProperties,
47047             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
47048             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
47049             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
47050             getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
47051             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
47052             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
47053             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
47054             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
47055             getSuggestedSymbolForNonexistentClassMember: getSuggestedSymbolForNonexistentClassMember,
47056             getBaseConstraintOfType: getBaseConstraintOfType,
47057             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
47058             resolveName: function (name, location, meaning, excludeGlobals) {
47059                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
47060             },
47061             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
47062             getJsxFragmentFactory: function (n) {
47063                 var jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
47064                 return jsxFragmentFactory && ts.unescapeLeadingUnderscores(ts.getFirstIdentifier(jsxFragmentFactory).escapedText);
47065             },
47066             getAccessibleSymbolChain: getAccessibleSymbolChain,
47067             getTypePredicateOfSignature: getTypePredicateOfSignature,
47068             resolveExternalModuleName: function (moduleSpecifierIn) {
47069                 var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
47070                 return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
47071             },
47072             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
47073             tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
47074                 var node = ts.getParseTreeNode(nodeIn);
47075                 return node && tryGetThisTypeAt(node, includeGlobalThis);
47076             },
47077             getTypeArgumentConstraint: function (nodeIn) {
47078                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
47079                 return node && getTypeArgumentConstraint(node);
47080             },
47081             getSuggestionDiagnostics: function (fileIn, ct) {
47082                 var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
47083                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
47084                     return ts.emptyArray;
47085                 }
47086                 var diagnostics;
47087                 try {
47088                     // Record the cancellation token so it can be checked later on during checkSourceElement.
47089                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
47090                     // this call is done.
47091                     cancellationToken = ct;
47092                     // Ensure file is type checked
47093                     checkSourceFile(file);
47094                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
47095                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
47096                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
47097                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
47098                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
47099                         }
47100                     });
47101                     return diagnostics || ts.emptyArray;
47102                 }
47103                 finally {
47104                     cancellationToken = undefined;
47105                 }
47106             },
47107             runWithCancellationToken: function (token, callback) {
47108                 try {
47109                     cancellationToken = token;
47110                     return callback(checker);
47111                 }
47112                 finally {
47113                     cancellationToken = undefined;
47114                 }
47115             },
47116             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
47117             isDeclarationVisible: isDeclarationVisible,
47118             isPropertyAccessible: isPropertyAccessible,
47119             getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration,
47120             getMemberOverrideModifierStatus: getMemberOverrideModifierStatus,
47121         };
47122         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
47123             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
47124             apparentArgumentCount = argumentCount;
47125             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
47126             apparentArgumentCount = undefined;
47127             return res;
47128         }
47129         var tupleTypes = new ts.Map();
47130         var unionTypes = new ts.Map();
47131         var intersectionTypes = new ts.Map();
47132         var stringLiteralTypes = new ts.Map();
47133         var numberLiteralTypes = new ts.Map();
47134         var bigIntLiteralTypes = new ts.Map();
47135         var enumLiteralTypes = new ts.Map();
47136         var indexedAccessTypes = new ts.Map();
47137         var templateLiteralTypes = new ts.Map();
47138         var stringMappingTypes = new ts.Map();
47139         var substitutionTypes = new ts.Map();
47140         var subtypeReductionCache = new ts.Map();
47141         var evolvingArrayTypes = [];
47142         var undefinedProperties = new ts.Map();
47143         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
47144         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
47145         var unresolvedSymbols = new ts.Map();
47146         var errorTypes = new ts.Map();
47147         var anyType = createIntrinsicType(1 /* Any */, "any");
47148         var autoType = createIntrinsicType(1 /* Any */, "any");
47149         var wildcardType = createIntrinsicType(1 /* Any */, "any");
47150         var errorType = createIntrinsicType(1 /* Any */, "error");
47151         var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved");
47152         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */);
47153         var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
47154         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
47155         var nonNullUnknownType = createIntrinsicType(2 /* Unknown */, "unknown");
47156         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
47157         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
47158         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
47159         var missingType = exactOptionalPropertyTypes ? createIntrinsicType(32768 /* Undefined */, "undefined") : undefinedType;
47160         var nullType = createIntrinsicType(65536 /* Null */, "null");
47161         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
47162         var stringType = createIntrinsicType(4 /* String */, "string");
47163         var numberType = createIntrinsicType(8 /* Number */, "number");
47164         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
47165         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
47166         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
47167         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
47168         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
47169         trueType.regularType = regularTrueType;
47170         trueType.freshType = trueType;
47171         regularTrueType.regularType = regularTrueType;
47172         regularTrueType.freshType = trueType;
47173         falseType.regularType = regularFalseType;
47174         falseType.freshType = falseType;
47175         regularFalseType.regularType = regularFalseType;
47176         regularFalseType.freshType = falseType;
47177         var booleanType = getUnionType([regularFalseType, regularTrueType]);
47178         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
47179         var voidType = createIntrinsicType(16384 /* Void */, "void");
47180         var neverType = createIntrinsicType(131072 /* Never */, "never");
47181         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
47182         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
47183         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
47184         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
47185         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
47186         var stringOrNumberType = getUnionType([stringType, numberType]);
47187         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
47188         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
47189         var numberOrBigIntType = getUnionType([numberType, bigintType]);
47190         var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
47191         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
47192         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
47193         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47194         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47195         emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */;
47196         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
47197         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
47198         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47199         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47200         emptyGenericType.instantiations = new ts.Map();
47201         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47202         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
47203         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
47204         anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
47205         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47206         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47207         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
47208         var markerSuperType = createTypeParameter();
47209         var markerSubType = createTypeParameter();
47210         markerSubType.constraint = markerSuperType;
47211         var markerOtherType = createTypeParameter();
47212         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
47213         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
47214         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
47215         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
47216         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
47217         var enumNumberIndexInfo = createIndexInfo(numberType, stringType, /*isReadonly*/ true);
47218         var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
47219         var noIterationTypes = {
47220             get yieldType() { return ts.Debug.fail("Not supported"); },
47221             get returnType() { return ts.Debug.fail("Not supported"); },
47222             get nextType() { return ts.Debug.fail("Not supported"); },
47223         };
47224         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
47225         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
47226         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
47227         var asyncIterationTypesResolver = {
47228             iterableCacheKey: "iterationTypesOfAsyncIterable",
47229             iteratorCacheKey: "iterationTypesOfAsyncIterator",
47230             iteratorSymbolName: "asyncIterator",
47231             getGlobalIteratorType: getGlobalAsyncIteratorType,
47232             getGlobalIterableType: getGlobalAsyncIterableType,
47233             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
47234             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
47235             resolveIterationType: getAwaitedType,
47236             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
47237             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
47238             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,
47239         };
47240         var syncIterationTypesResolver = {
47241             iterableCacheKey: "iterationTypesOfIterable",
47242             iteratorCacheKey: "iterationTypesOfIterator",
47243             iteratorSymbolName: "iterator",
47244             getGlobalIteratorType: getGlobalIteratorType,
47245             getGlobalIterableType: getGlobalIterableType,
47246             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
47247             getGlobalGeneratorType: getGlobalGeneratorType,
47248             resolveIterationType: function (type, _errorNode) { return type; },
47249             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
47250             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
47251             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
47252         };
47253         /** Key is "/path/to/a.ts|/path/to/b.ts". */
47254         var amalgamatedDuplicates;
47255         var reverseMappedCache = new ts.Map();
47256         var inInferTypeForHomomorphicMappedType = false;
47257         var ambientModulesCache;
47258         /**
47259          * List of every ambient module with a "*" wildcard.
47260          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
47261          * This is only used if there is no exact match.
47262          */
47263         var patternAmbientModules;
47264         var patternAmbientModuleAugmentations;
47265         var globalObjectType;
47266         var globalFunctionType;
47267         var globalCallableFunctionType;
47268         var globalNewableFunctionType;
47269         var globalArrayType;
47270         var globalReadonlyArrayType;
47271         var globalStringType;
47272         var globalNumberType;
47273         var globalBooleanType;
47274         var globalRegExpType;
47275         var globalThisType;
47276         var anyArrayType;
47277         var autoArrayType;
47278         var anyReadonlyArrayType;
47279         var deferredGlobalNonNullableTypeAlias;
47280         // The library files are only loaded when the feature is used.
47281         // This allows users to just specify library files they want to used through --lib
47282         // and they will not get an error from not having unrelated library files
47283         var deferredGlobalESSymbolConstructorSymbol;
47284         var deferredGlobalESSymbolConstructorTypeSymbol;
47285         var deferredGlobalESSymbolType;
47286         var deferredGlobalTypedPropertyDescriptorType;
47287         var deferredGlobalPromiseType;
47288         var deferredGlobalPromiseLikeType;
47289         var deferredGlobalPromiseConstructorSymbol;
47290         var deferredGlobalPromiseConstructorLikeType;
47291         var deferredGlobalIterableType;
47292         var deferredGlobalIteratorType;
47293         var deferredGlobalIterableIteratorType;
47294         var deferredGlobalGeneratorType;
47295         var deferredGlobalIteratorYieldResultType;
47296         var deferredGlobalIteratorReturnResultType;
47297         var deferredGlobalAsyncIterableType;
47298         var deferredGlobalAsyncIteratorType;
47299         var deferredGlobalAsyncIterableIteratorType;
47300         var deferredGlobalAsyncGeneratorType;
47301         var deferredGlobalTemplateStringsArrayType;
47302         var deferredGlobalImportMetaType;
47303         var deferredGlobalImportMetaExpressionType;
47304         var deferredGlobalImportCallOptionsType;
47305         var deferredGlobalExtractSymbol;
47306         var deferredGlobalOmitSymbol;
47307         var deferredGlobalAwaitedSymbol;
47308         var deferredGlobalBigIntType;
47309         var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
47310         var flowLoopStart = 0;
47311         var flowLoopCount = 0;
47312         var sharedFlowCount = 0;
47313         var flowAnalysisDisabled = false;
47314         var flowInvocationCount = 0;
47315         var lastFlowNode;
47316         var lastFlowNodeReachable;
47317         var flowTypeCache;
47318         var emptyStringType = getStringLiteralType("");
47319         var zeroType = getNumberLiteralType(0);
47320         var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" });
47321         var resolutionTargets = [];
47322         var resolutionResults = [];
47323         var resolutionPropertyNames = [];
47324         var suggestionCount = 0;
47325         var maximumSuggestionCount = 10;
47326         var mergedSymbols = [];
47327         var symbolLinks = [];
47328         var nodeLinks = [];
47329         var flowLoopCaches = [];
47330         var flowLoopNodes = [];
47331         var flowLoopKeys = [];
47332         var flowLoopTypes = [];
47333         var sharedFlowNodes = [];
47334         var sharedFlowTypes = [];
47335         var flowNodeReachable = [];
47336         var flowNodePostSuper = [];
47337         var potentialThisCollisions = [];
47338         var potentialNewTargetCollisions = [];
47339         var potentialWeakMapSetCollisions = [];
47340         var potentialReflectCollisions = [];
47341         var awaitedTypeStack = [];
47342         var diagnostics = ts.createDiagnosticCollection();
47343         var suggestionDiagnostics = ts.createDiagnosticCollection();
47344         var typeofTypesByName = new ts.Map(ts.getEntries({
47345             string: stringType,
47346             number: numberType,
47347             bigint: bigintType,
47348             boolean: booleanType,
47349             symbol: esSymbolType,
47350             undefined: undefinedType
47351         }));
47352         var typeofType = createTypeofType();
47353         var _jsxNamespace;
47354         var _jsxFactoryEntity;
47355         var outofbandVarianceMarkerHandler;
47356         var subtypeRelation = new ts.Map();
47357         var strictSubtypeRelation = new ts.Map();
47358         var assignableRelation = new ts.Map();
47359         var comparableRelation = new ts.Map();
47360         var identityRelation = new ts.Map();
47361         var enumRelation = new ts.Map();
47362         var builtinGlobals = ts.createSymbolTable();
47363         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
47364         // Extensions suggested for path imports when module resolution is node12 or higher.
47365         // The first element of each tuple is the extension a file has.
47366         // The second element of each tuple is the extension that should be used in a path import.
47367         // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs".
47368         var suggestedExtensions = [
47369             [".mts", ".mjs"],
47370             [".ts", ".js"],
47371             [".cts", ".cjs"],
47372             [".mjs", ".mjs"],
47373             [".js", ".js"],
47374             [".cjs", ".cjs"],
47375             [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"],
47376             [".jsx", ".jsx"],
47377             [".json", ".json"],
47378         ];
47379         initializeTypeChecker();
47380         return checker;
47381         function getJsxNamespace(location) {
47382             if (location) {
47383                 var file = ts.getSourceFileOfNode(location);
47384                 if (file) {
47385                     if (ts.isJsxOpeningFragment(location)) {
47386                         if (file.localJsxFragmentNamespace) {
47387                             return file.localJsxFragmentNamespace;
47388                         }
47389                         var jsxFragmentPragma = file.pragmas.get("jsxfrag");
47390                         if (jsxFragmentPragma) {
47391                             var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
47392                             file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
47393                             ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
47394                             if (file.localJsxFragmentFactory) {
47395                                 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
47396                             }
47397                         }
47398                         var entity = getJsxFragmentFactoryEntity(location);
47399                         if (entity) {
47400                             file.localJsxFragmentFactory = entity;
47401                             return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
47402                         }
47403                     }
47404                     else {
47405                         var localJsxNamespace = getLocalJsxNamespace(file);
47406                         if (localJsxNamespace) {
47407                             return file.localJsxNamespace = localJsxNamespace;
47408                         }
47409                     }
47410                 }
47411             }
47412             if (!_jsxNamespace) {
47413                 _jsxNamespace = "React";
47414                 if (compilerOptions.jsxFactory) {
47415                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
47416                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
47417                     if (_jsxFactoryEntity) {
47418                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
47419                     }
47420                 }
47421                 else if (compilerOptions.reactNamespace) {
47422                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
47423                 }
47424             }
47425             if (!_jsxFactoryEntity) {
47426                 _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
47427             }
47428             return _jsxNamespace;
47429         }
47430         function getLocalJsxNamespace(file) {
47431             if (file.localJsxNamespace) {
47432                 return file.localJsxNamespace;
47433             }
47434             var jsxPragma = file.pragmas.get("jsx");
47435             if (jsxPragma) {
47436                 var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
47437                 file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
47438                 ts.visitNode(file.localJsxFactory, markAsSynthetic);
47439                 if (file.localJsxFactory) {
47440                     return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
47441                 }
47442             }
47443         }
47444         function markAsSynthetic(node) {
47445             ts.setTextRangePosEnd(node, -1, -1);
47446             return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
47447         }
47448         function getEmitResolver(sourceFile, cancellationToken) {
47449             // Ensure we have all the type information in place for this file so that all the
47450             // emitter questions of this resolver will return the right information.
47451             getDiagnostics(sourceFile, cancellationToken);
47452             return emitResolver;
47453         }
47454         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
47455             var diagnostic = location
47456                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
47457                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
47458             var existing = diagnostics.lookup(diagnostic);
47459             if (existing) {
47460                 return existing;
47461             }
47462             else {
47463                 diagnostics.add(diagnostic);
47464                 return diagnostic;
47465             }
47466         }
47467         function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
47468             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
47469             diagnostic.skippedOn = key;
47470             return diagnostic;
47471         }
47472         function createError(location, message, arg0, arg1, arg2, arg3) {
47473             return location
47474                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
47475                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
47476         }
47477         function error(location, message, arg0, arg1, arg2, arg3) {
47478             var diagnostic = createError(location, message, arg0, arg1, arg2, arg3);
47479             diagnostics.add(diagnostic);
47480             return diagnostic;
47481         }
47482         function addErrorOrSuggestion(isError, diagnostic) {
47483             if (isError) {
47484                 diagnostics.add(diagnostic);
47485             }
47486             else {
47487                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
47488             }
47489         }
47490         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
47491             // Pseudo-synthesized input node
47492             if (location.pos < 0 || location.end < 0) {
47493                 if (!isError) {
47494                     return; // Drop suggestions (we have no span to suggest on)
47495                 }
47496                 // Issue errors globally
47497                 var file = ts.getSourceFileOfNode(location);
47498                 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
47499                 return;
47500             }
47501             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
47502         }
47503         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
47504             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
47505             if (maybeMissingAwait) {
47506                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
47507                 ts.addRelatedInfo(diagnostic, related);
47508             }
47509             return diagnostic;
47510         }
47511         function addDeprecatedSuggestionWorker(declarations, diagnostic) {
47512             var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations);
47513             if (deprecatedTag) {
47514                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here));
47515             }
47516             // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates.
47517             suggestionDiagnostics.add(diagnostic);
47518             return diagnostic;
47519         }
47520         function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
47521             var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity);
47522             return addDeprecatedSuggestionWorker(declarations, diagnostic);
47523         }
47524         function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
47525             var diagnostic = deprecatedEntity
47526                 ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity)
47527                 : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString);
47528             return addDeprecatedSuggestionWorker(declaration, diagnostic);
47529         }
47530         function createSymbol(flags, name, checkFlags) {
47531             symbolCount++;
47532             var symbol = new Symbol(flags | 33554432 /* Transient */, name);
47533             symbol.checkFlags = checkFlags || 0;
47534             return symbol;
47535         }
47536         function getExcludedSymbolFlags(flags) {
47537             var result = 0;
47538             if (flags & 2 /* BlockScopedVariable */)
47539                 result |= 111551 /* BlockScopedVariableExcludes */;
47540             if (flags & 1 /* FunctionScopedVariable */)
47541                 result |= 111550 /* FunctionScopedVariableExcludes */;
47542             if (flags & 4 /* Property */)
47543                 result |= 0 /* PropertyExcludes */;
47544             if (flags & 8 /* EnumMember */)
47545                 result |= 900095 /* EnumMemberExcludes */;
47546             if (flags & 16 /* Function */)
47547                 result |= 110991 /* FunctionExcludes */;
47548             if (flags & 32 /* Class */)
47549                 result |= 899503 /* ClassExcludes */;
47550             if (flags & 64 /* Interface */)
47551                 result |= 788872 /* InterfaceExcludes */;
47552             if (flags & 256 /* RegularEnum */)
47553                 result |= 899327 /* RegularEnumExcludes */;
47554             if (flags & 128 /* ConstEnum */)
47555                 result |= 899967 /* ConstEnumExcludes */;
47556             if (flags & 512 /* ValueModule */)
47557                 result |= 110735 /* ValueModuleExcludes */;
47558             if (flags & 8192 /* Method */)
47559                 result |= 103359 /* MethodExcludes */;
47560             if (flags & 32768 /* GetAccessor */)
47561                 result |= 46015 /* GetAccessorExcludes */;
47562             if (flags & 65536 /* SetAccessor */)
47563                 result |= 78783 /* SetAccessorExcludes */;
47564             if (flags & 262144 /* TypeParameter */)
47565                 result |= 526824 /* TypeParameterExcludes */;
47566             if (flags & 524288 /* TypeAlias */)
47567                 result |= 788968 /* TypeAliasExcludes */;
47568             if (flags & 2097152 /* Alias */)
47569                 result |= 2097152 /* AliasExcludes */;
47570             return result;
47571         }
47572         function recordMergedSymbol(target, source) {
47573             if (!source.mergeId) {
47574                 source.mergeId = nextMergeId;
47575                 nextMergeId++;
47576             }
47577             mergedSymbols[source.mergeId] = target;
47578         }
47579         function cloneSymbol(symbol) {
47580             var result = createSymbol(symbol.flags, symbol.escapedName);
47581             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
47582             result.parent = symbol.parent;
47583             if (symbol.valueDeclaration)
47584                 result.valueDeclaration = symbol.valueDeclaration;
47585             if (symbol.constEnumOnlyModule)
47586                 result.constEnumOnlyModule = true;
47587             if (symbol.members)
47588                 result.members = new ts.Map(symbol.members);
47589             if (symbol.exports)
47590                 result.exports = new ts.Map(symbol.exports);
47591             recordMergedSymbol(result, symbol);
47592             return result;
47593         }
47594         /**
47595          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
47596          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
47597          */
47598         function mergeSymbol(target, source, unidirectional) {
47599             if (unidirectional === void 0) { unidirectional = false; }
47600             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
47601                 (source.flags | target.flags) & 67108864 /* Assignment */) {
47602                 if (source === target) {
47603                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
47604                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
47605                     return target;
47606                 }
47607                 if (!(target.flags & 33554432 /* Transient */)) {
47608                     var resolvedTarget = resolveSymbol(target);
47609                     if (resolvedTarget === unknownSymbol) {
47610                         return source;
47611                     }
47612                     target = cloneSymbol(resolvedTarget);
47613                 }
47614                 // Javascript static-property-assignment declarations always merge, even though they are also values
47615                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
47616                     // reset flag when merging instantiated module into value module that has only const enums
47617                     target.constEnumOnlyModule = false;
47618                 }
47619                 target.flags |= source.flags;
47620                 if (source.valueDeclaration) {
47621                     ts.setValueDeclaration(target, source.valueDeclaration);
47622                 }
47623                 ts.addRange(target.declarations, source.declarations);
47624                 if (source.members) {
47625                     if (!target.members)
47626                         target.members = ts.createSymbolTable();
47627                     mergeSymbolTable(target.members, source.members, unidirectional);
47628                 }
47629                 if (source.exports) {
47630                     if (!target.exports)
47631                         target.exports = ts.createSymbolTable();
47632                     mergeSymbolTable(target.exports, source.exports, unidirectional);
47633                 }
47634                 if (!unidirectional) {
47635                     recordMergedSymbol(target, source);
47636                 }
47637             }
47638             else if (target.flags & 1024 /* NamespaceModule */) {
47639                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
47640                 // as we will already report a "Declaration name conflicts..." error, and this error
47641                 // won't make much sense.
47642                 if (target !== globalThisSymbol) {
47643                     error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
47644                 }
47645             }
47646             else { // error
47647                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
47648                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
47649                 var message = isEitherEnum
47650                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
47651                     : isEitherBlockScoped_1
47652                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
47653                         : ts.Diagnostics.Duplicate_identifier_0;
47654                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
47655                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
47656                 var symbolName_1 = symbolToString(source);
47657                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
47658                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
47659                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
47660                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
47661                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, "".concat(firstFile_1.path, "|").concat(secondFile_1.path), function () {
47662                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
47663                     });
47664                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
47665                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
47666                     });
47667                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
47668                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
47669                 }
47670                 else {
47671                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
47672                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
47673                 }
47674             }
47675             return target;
47676             function addDuplicateLocations(locs, symbol) {
47677                 if (symbol.declarations) {
47678                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
47679                         var decl = _a[_i];
47680                         ts.pushIfUnique(locs, decl);
47681                     }
47682                 }
47683             }
47684         }
47685         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
47686             ts.forEach(target.declarations, function (node) {
47687                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
47688             });
47689         }
47690         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
47691             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
47692             var err = lookupOrIssueError(errorNode, message, symbolName);
47693             var _loop_7 = function (relatedNode) {
47694                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
47695                 if (adjustedNode === errorNode)
47696                     return "continue";
47697                 err.relatedInformation = err.relatedInformation || [];
47698                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
47699                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
47700                 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 */; }))
47701                     return "continue";
47702                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
47703             };
47704             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
47705                 var relatedNode = _a[_i];
47706                 _loop_7(relatedNode);
47707             }
47708         }
47709         function combineSymbolTables(first, second) {
47710             if (!(first === null || first === void 0 ? void 0 : first.size))
47711                 return second;
47712             if (!(second === null || second === void 0 ? void 0 : second.size))
47713                 return first;
47714             var combined = ts.createSymbolTable();
47715             mergeSymbolTable(combined, first);
47716             mergeSymbolTable(combined, second);
47717             return combined;
47718         }
47719         function mergeSymbolTable(target, source, unidirectional) {
47720             if (unidirectional === void 0) { unidirectional = false; }
47721             source.forEach(function (sourceSymbol, id) {
47722                 var targetSymbol = target.get(id);
47723                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
47724             });
47725         }
47726         function mergeModuleAugmentation(moduleName) {
47727             var _a, _b, _c;
47728             var moduleAugmentation = moduleName.parent;
47729             if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) {
47730                 // this is a combined symbol for multiple augmentations within the same file.
47731                 // its symbol already has accumulated information for all declarations
47732                 // so we need to add it just once - do the work only for first declaration
47733                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
47734                 return;
47735             }
47736             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
47737                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
47738             }
47739             else {
47740                 // find a module that about to be augmented
47741                 // do not validate names of augmentations that are defined in ambient context
47742                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
47743                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
47744                     : undefined;
47745                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
47746                 if (!mainModule_1) {
47747                     return;
47748                 }
47749                 // obtain item referenced by 'export='
47750                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
47751                 if (mainModule_1.flags & 1920 /* Namespace */) {
47752                     // If we're merging an augmentation to a pattern ambient module, we want to
47753                     // perform the merge unidirectionally from the augmentation ('a.foo') to
47754                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
47755                     // all the exports both from the pattern and from the augmentation, but
47756                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
47757                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
47758                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
47759                         if (!patternAmbientModuleAugmentations) {
47760                             patternAmbientModuleAugmentations = new ts.Map();
47761                         }
47762                         // moduleName will be a StringLiteral since this is not `declare global`.
47763                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
47764                     }
47765                     else {
47766                         if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) {
47767                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
47768                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
47769                             for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) {
47770                                 var _e = _d[_i], key = _e[0], value = _e[1];
47771                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
47772                                     mergeSymbol(resolvedExports.get(key), value);
47773                                 }
47774                             }
47775                         }
47776                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
47777                     }
47778                 }
47779                 else {
47780                     // moduleName will be a StringLiteral since this is not `declare global`.
47781                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
47782                 }
47783             }
47784         }
47785         function addToSymbolTable(target, source, message) {
47786             source.forEach(function (sourceSymbol, id) {
47787                 var targetSymbol = target.get(id);
47788                 if (targetSymbol) {
47789                     // Error on redeclarations
47790                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
47791                 }
47792                 else {
47793                     target.set(id, sourceSymbol);
47794                 }
47795             });
47796             function addDeclarationDiagnostic(id, message) {
47797                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
47798             }
47799         }
47800         function getSymbolLinks(symbol) {
47801             if (symbol.flags & 33554432 /* Transient */)
47802                 return symbol;
47803             var id = getSymbolId(symbol);
47804             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
47805         }
47806         function getNodeLinks(node) {
47807             var nodeId = getNodeId(node);
47808             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
47809         }
47810         function isGlobalSourceFile(node) {
47811             return node.kind === 303 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
47812         }
47813         function getSymbol(symbols, name, meaning) {
47814             if (meaning) {
47815                 var symbol = getMergedSymbol(symbols.get(name));
47816                 if (symbol) {
47817                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
47818                     if (symbol.flags & meaning) {
47819                         return symbol;
47820                     }
47821                     if (symbol.flags & 2097152 /* Alias */) {
47822                         var target = resolveAlias(symbol);
47823                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
47824                         if (target === unknownSymbol || target.flags & meaning) {
47825                             return symbol;
47826                         }
47827                     }
47828                 }
47829             }
47830             // return undefined if we can't find a symbol.
47831         }
47832         /**
47833          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
47834          * @param parameter a parameterDeclaration node
47835          * @param parameterName a name of the parameter to get the symbols for.
47836          * @return a tuple of two symbols
47837          */
47838         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
47839             var constructorDeclaration = parameter.parent;
47840             var classDeclaration = parameter.parent.parent;
47841             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
47842             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
47843             if (parameterSymbol && propertySymbol) {
47844                 return [parameterSymbol, propertySymbol];
47845             }
47846             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
47847         }
47848         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
47849             var declarationFile = ts.getSourceFileOfNode(declaration);
47850             var useFile = ts.getSourceFileOfNode(usage);
47851             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
47852             if (declarationFile !== useFile) {
47853                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
47854                     (!ts.outFile(compilerOptions)) ||
47855                     isInTypeQuery(usage) ||
47856                     declaration.flags & 8388608 /* Ambient */) {
47857                     // nodes are in different files and order cannot be determined
47858                     return true;
47859                 }
47860                 // declaration is after usage
47861                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
47862                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
47863                     return true;
47864                 }
47865                 var sourceFiles = host.getSourceFiles();
47866                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
47867             }
47868             if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
47869                 // declaration is before usage
47870                 if (declaration.kind === 202 /* BindingElement */) {
47871                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
47872                     var errorBindingElement = ts.getAncestor(usage, 202 /* BindingElement */);
47873                     if (errorBindingElement) {
47874                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
47875                             declaration.pos < errorBindingElement.pos;
47876                     }
47877                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
47878                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 253 /* VariableDeclaration */), usage);
47879                 }
47880                 else if (declaration.kind === 253 /* VariableDeclaration */) {
47881                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
47882                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
47883                 }
47884                 else if (ts.isClassDeclaration(declaration)) {
47885                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
47886                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
47887                 }
47888                 else if (ts.isPropertyDeclaration(declaration)) {
47889                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
47890                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
47891                 }
47892                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
47893                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
47894                     return !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields
47895                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
47896                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
47897                 }
47898                 return true;
47899             }
47900             // declaration is after usage, but it can still be legal if usage is deferred:
47901             // 1. inside an export specifier
47902             // 2. inside a function
47903             // 3. inside an instance property initializer, a reference to a non-instance property
47904             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
47905             // 4. inside a static property initializer, a reference to a static method in the same class
47906             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
47907             // or if usage is in a type context:
47908             // 1. inside a type query (typeof in type position)
47909             // 2. inside a jsdoc comment
47910             if (usage.parent.kind === 274 /* ExportSpecifier */ || (usage.parent.kind === 270 /* ExportAssignment */ && usage.parent.isExportEquals)) {
47911                 // export specifiers do not use the variable, they only make it available for use
47912                 return true;
47913             }
47914             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
47915             if (usage.kind === 270 /* ExportAssignment */ && usage.isExportEquals) {
47916                 return true;
47917             }
47918             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
47919                 return true;
47920             }
47921             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
47922                 if (ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields
47923                     && ts.getContainingClass(declaration)
47924                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
47925                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
47926                 }
47927                 else {
47928                     return true;
47929                 }
47930             }
47931             return false;
47932             function usageInTypeDeclaration() {
47933                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
47934             }
47935             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
47936                 switch (declaration.parent.parent.kind) {
47937                     case 236 /* VariableStatement */:
47938                     case 241 /* ForStatement */:
47939                     case 243 /* ForOfStatement */:
47940                         // variable statement/for/for-of statement case,
47941                         // use site should not be inside variable declaration (initializer of declaration or binding element)
47942                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
47943                             return true;
47944                         }
47945                         break;
47946                 }
47947                 // ForIn/ForOf case - use site should not be used in expression part
47948                 var grandparent = declaration.parent.parent;
47949                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
47950             }
47951             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
47952                 return !!ts.findAncestor(usage, function (current) {
47953                     if (current === declContainer) {
47954                         return "quit";
47955                     }
47956                     if (ts.isFunctionLike(current)) {
47957                         return true;
47958                     }
47959                     if (ts.isClassStaticBlockDeclaration(current)) {
47960                         return declaration.pos < usage.pos;
47961                     }
47962                     var propertyDeclaration = ts.tryCast(current.parent, ts.isPropertyDeclaration);
47963                     if (propertyDeclaration) {
47964                         var initializerOfProperty = propertyDeclaration.initializer === current;
47965                         if (initializerOfProperty) {
47966                             if (ts.isStatic(current.parent)) {
47967                                 if (declaration.kind === 168 /* MethodDeclaration */) {
47968                                     return true;
47969                                 }
47970                                 if (ts.isPropertyDeclaration(declaration) && ts.getContainingClass(usage) === ts.getContainingClass(declaration)) {
47971                                     var propName = declaration.name;
47972                                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
47973                                         var type = getTypeOfSymbol(getSymbolOfNode(declaration));
47974                                         var staticBlocks = ts.filter(declaration.parent.members, ts.isClassStaticBlockDeclaration);
47975                                         if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration.parent.pos, current.pos)) {
47976                                             return true;
47977                                         }
47978                                     }
47979                                 }
47980                             }
47981                             else {
47982                                 var isDeclarationInstanceProperty = declaration.kind === 166 /* PropertyDeclaration */ && !ts.isStatic(declaration);
47983                                 if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
47984                                     return true;
47985                                 }
47986                             }
47987                         }
47988                     }
47989                     return false;
47990                 });
47991             }
47992             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
47993             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
47994                 // always legal if usage is after declaration
47995                 if (usage.end > declaration.end) {
47996                     return false;
47997                 }
47998                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
47999                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
48000                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
48001                     if (node === declaration) {
48002                         return "quit";
48003                     }
48004                     switch (node.kind) {
48005                         case 213 /* ArrowFunction */:
48006                             return true;
48007                         case 166 /* PropertyDeclaration */:
48008                             // even when stopping at any property declaration, they need to come from the same class
48009                             return stopAtAnyPropertyDeclaration &&
48010                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
48011                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
48012                                 ? "quit" : true;
48013                         case 234 /* Block */:
48014                             switch (node.parent.kind) {
48015                                 case 171 /* GetAccessor */:
48016                                 case 168 /* MethodDeclaration */:
48017                                 case 172 /* SetAccessor */:
48018                                     return true;
48019                                 default:
48020                                     return false;
48021                             }
48022                         default:
48023                             return false;
48024                     }
48025                 });
48026                 return ancestorChangingReferenceScope === undefined;
48027             }
48028         }
48029         function useOuterVariableScopeInParameter(result, location, lastLocation) {
48030             var target = ts.getEmitScriptTarget(compilerOptions);
48031             var functionLocation = location;
48032             if (ts.isParameter(lastLocation)
48033                 && functionLocation.body
48034                 && result.valueDeclaration
48035                 && result.valueDeclaration.pos >= functionLocation.body.pos
48036                 && result.valueDeclaration.end <= functionLocation.body.end) {
48037                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
48038                 // - static field in a class expression
48039                 // - optional chaining pre-es2020
48040                 // - nullish coalesce pre-es2020
48041                 // - spread assignment in binding pattern pre-es2017
48042                 if (target >= 2 /* ES2015 */) {
48043                     var links = getNodeLinks(functionLocation);
48044                     if (links.declarationRequiresScopeChange === undefined) {
48045                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
48046                     }
48047                     return !links.declarationRequiresScopeChange;
48048                 }
48049             }
48050             return false;
48051             function requiresScopeChange(node) {
48052                 return requiresScopeChangeWorker(node.name)
48053                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
48054             }
48055             function requiresScopeChangeWorker(node) {
48056                 switch (node.kind) {
48057                     case 213 /* ArrowFunction */:
48058                     case 212 /* FunctionExpression */:
48059                     case 255 /* FunctionDeclaration */:
48060                     case 170 /* Constructor */:
48061                         // do not descend into these
48062                         return false;
48063                     case 168 /* MethodDeclaration */:
48064                     case 171 /* GetAccessor */:
48065                     case 172 /* SetAccessor */:
48066                     case 294 /* PropertyAssignment */:
48067                         return requiresScopeChangeWorker(node.name);
48068                     case 166 /* PropertyDeclaration */:
48069                         // static properties in classes introduce temporary variables
48070                         if (ts.hasStaticModifier(node)) {
48071                             return target < 99 /* ESNext */ || !useDefineForClassFields;
48072                         }
48073                         return requiresScopeChangeWorker(node.name);
48074                     default:
48075                         // null coalesce and optional chain pre-es2020 produce temporary variables
48076                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
48077                             return target < 7 /* ES2020 */;
48078                         }
48079                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
48080                             return target < 4 /* ES2017 */;
48081                         }
48082                         if (ts.isTypeNode(node))
48083                             return false;
48084                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
48085                 }
48086             }
48087         }
48088         /**
48089          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
48090          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
48091          * the given name can be found.
48092          *
48093          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
48094          */
48095         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) {
48096             if (excludeGlobals === void 0) { excludeGlobals = false; }
48097             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol);
48098         }
48099         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) {
48100             var _a, _b, _c;
48101             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
48102             var result;
48103             var lastLocation;
48104             var lastSelfReferenceLocation;
48105             var propertyWithInvalidInitializer;
48106             var associatedDeclarationForContainingInitializerOrBindingName;
48107             var withinDeferredContext = false;
48108             var errorLocation = location;
48109             var grandparent;
48110             var isInExternalModule = false;
48111             loop: while (location) {
48112                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
48113                 if (location.locals && !isGlobalSourceFile(location)) {
48114                     if (result = lookup(location.locals, name, meaning)) {
48115                         var useResult = true;
48116                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
48117                             // symbol lookup restrictions for function-like declarations
48118                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
48119                             //   list and return type. However, local types are only in scope in the function body.
48120                             // - parameters are only in the scope of function body
48121                             // This restriction does not apply to JSDoc comment types because they are parented
48122                             // at a higher level than type parameters would normally be
48123                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 318 /* JSDocComment */) {
48124                                 useResult = result.flags & 262144 /* TypeParameter */
48125                                     // type parameters are visible in parameter list, return type and type parameter list
48126                                     ? lastLocation === location.type ||
48127                                         lastLocation.kind === 163 /* Parameter */ ||
48128                                         lastLocation.kind === 162 /* TypeParameter */
48129                                     // local types not visible outside the function body
48130                                     : false;
48131                             }
48132                             if (meaning & result.flags & 3 /* Variable */) {
48133                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
48134                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
48135                                     useResult = false;
48136                                 }
48137                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
48138                                     // parameters are visible only inside function body, parameter list and return type
48139                                     // technically for parameter list case here we might mix parameters and variables declared in function,
48140                                     // however it is detected separately when checking initializers of parameters
48141                                     // to make sure that they reference no variables declared after them.
48142                                     useResult =
48143                                         lastLocation.kind === 163 /* Parameter */ ||
48144                                             (lastLocation === location.type &&
48145                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
48146                                 }
48147                             }
48148                         }
48149                         else if (location.kind === 188 /* ConditionalType */) {
48150                             // A type parameter declared using 'infer T' in a conditional type is visible only in
48151                             // the true branch of the conditional type.
48152                             useResult = lastLocation === location.trueType;
48153                         }
48154                         if (useResult) {
48155                             break loop;
48156                         }
48157                         else {
48158                             result = undefined;
48159                         }
48160                     }
48161                 }
48162                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
48163                 switch (location.kind) {
48164                     case 303 /* SourceFile */:
48165                         if (!ts.isExternalOrCommonJsModule(location))
48166                             break;
48167                         isInExternalModule = true;
48168                     // falls through
48169                     case 260 /* ModuleDeclaration */:
48170                         var moduleExports = ((_a = getSymbolOfNode(location)) === null || _a === void 0 ? void 0 : _a.exports) || emptySymbols;
48171                         if (location.kind === 303 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
48172                             // It's an external module. First see if the module has an export default and if the local
48173                             // name of that export default matches.
48174                             if (result = moduleExports.get("default" /* Default */)) {
48175                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
48176                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
48177                                     break loop;
48178                                 }
48179                                 result = undefined;
48180                             }
48181                             // Because of module/namespace merging, a module's exports are in scope,
48182                             // yet we never want to treat an export specifier as putting a member in scope.
48183                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
48184                             // Two things to note about this:
48185                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
48186                             //        on an export specifier is that it might find the export specifier itself, and try to
48187                             //        resolve it as an alias. This will cause the checker to consider the export specifier
48188                             //        a circular alias reference when it might not be.
48189                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
48190                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
48191                             //        which is not the desired behavior.
48192                             var moduleExport = moduleExports.get(name);
48193                             if (moduleExport &&
48194                                 moduleExport.flags === 2097152 /* Alias */ &&
48195                                 (ts.getDeclarationOfKind(moduleExport, 274 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 273 /* NamespaceExport */))) {
48196                                 break;
48197                             }
48198                         }
48199                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
48200                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
48201                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) === null || _b === void 0 ? void 0 : _b.some(ts.isJSDocTypeAlias))) {
48202                                 result = undefined;
48203                             }
48204                             else {
48205                                 break loop;
48206                             }
48207                         }
48208                         break;
48209                     case 259 /* EnumDeclaration */:
48210                         if (result = lookup(((_c = getSymbolOfNode(location)) === null || _c === void 0 ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) {
48211                             break loop;
48212                         }
48213                         break;
48214                     case 166 /* PropertyDeclaration */:
48215                         // TypeScript 1.0 spec (April 2014): 8.4.1
48216                         // Initializer expressions for instance member variables are evaluated in the scope
48217                         // of the class constructor body but are not permitted to reference parameters or
48218                         // local variables of the constructor. This effectively means that entities from outer scopes
48219                         // by the same name as a constructor parameter or local variable are inaccessible
48220                         // in initializer expressions for instance member variables.
48221                         if (!ts.isStatic(location)) {
48222                             var ctor = findConstructorDeclaration(location.parent);
48223                             if (ctor && ctor.locals) {
48224                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
48225                                     // Remember the property node, it will be used later to report appropriate error
48226                                     propertyWithInvalidInitializer = location;
48227                                 }
48228                             }
48229                         }
48230                         break;
48231                     case 256 /* ClassDeclaration */:
48232                     case 225 /* ClassExpression */:
48233                     case 257 /* InterfaceDeclaration */:
48234                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
48235                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
48236                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
48237                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
48238                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
48239                                 // ignore type parameters not declared in this container
48240                                 result = undefined;
48241                                 break;
48242                             }
48243                             if (lastLocation && ts.isStatic(lastLocation)) {
48244                                 // TypeScript 1.0 spec (April 2014): 3.4.1
48245                                 // The scope of a type parameter extends over the entire declaration with which the type
48246                                 // parameter list is associated, with the exception of static member declarations in classes.
48247                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
48248                                 return undefined;
48249                             }
48250                             break loop;
48251                         }
48252                         if (location.kind === 225 /* ClassExpression */ && meaning & 32 /* Class */) {
48253                             var className = location.name;
48254                             if (className && name === className.escapedText) {
48255                                 result = location.symbol;
48256                                 break loop;
48257                             }
48258                         }
48259                         break;
48260                     case 227 /* ExpressionWithTypeArguments */:
48261                         // The type parameters of a class are not in scope in the base class expression.
48262                         if (lastLocation === location.expression && location.parent.token === 94 /* ExtendsKeyword */) {
48263                             var container = location.parent.parent;
48264                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
48265                                 if (nameNotFoundMessage) {
48266                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
48267                                 }
48268                                 return undefined;
48269                             }
48270                         }
48271                         break;
48272                     // It is not legal to reference a class's own type parameters from a computed property name that
48273                     // belongs to the class. For example:
48274                     //
48275                     //   function foo<T>() { return '' }
48276                     //   class C<T> { // <-- Class's own type parameter T
48277                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
48278                     //   }
48279                     //
48280                     case 161 /* ComputedPropertyName */:
48281                         grandparent = location.parent.parent;
48282                         if (ts.isClassLike(grandparent) || grandparent.kind === 257 /* InterfaceDeclaration */) {
48283                             // A reference to this grandparent's type parameters would be an error
48284                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
48285                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
48286                                 return undefined;
48287                             }
48288                         }
48289                         break;
48290                     case 213 /* ArrowFunction */:
48291                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
48292                         // for lower compile targets the resolved symbol is used to emit an error
48293                         if (ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) {
48294                             break;
48295                         }
48296                     // falls through
48297                     case 168 /* MethodDeclaration */:
48298                     case 170 /* Constructor */:
48299                     case 171 /* GetAccessor */:
48300                     case 172 /* SetAccessor */:
48301                     case 255 /* FunctionDeclaration */:
48302                         if (meaning & 3 /* Variable */ && name === "arguments") {
48303                             result = argumentsSymbol;
48304                             break loop;
48305                         }
48306                         break;
48307                     case 212 /* FunctionExpression */:
48308                         if (meaning & 3 /* Variable */ && name === "arguments") {
48309                             result = argumentsSymbol;
48310                             break loop;
48311                         }
48312                         if (meaning & 16 /* Function */) {
48313                             var functionName = location.name;
48314                             if (functionName && name === functionName.escapedText) {
48315                                 result = location.symbol;
48316                                 break loop;
48317                             }
48318                         }
48319                         break;
48320                     case 164 /* Decorator */:
48321                         // Decorators are resolved at the class declaration. Resolving at the parameter
48322                         // or member would result in looking up locals in the method.
48323                         //
48324                         //   function y() {}
48325                         //   class C {
48326                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
48327                         //   }
48328                         //
48329                         if (location.parent && location.parent.kind === 163 /* Parameter */) {
48330                             location = location.parent;
48331                         }
48332                         //
48333                         //   function y() {}
48334                         //   class C {
48335                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
48336                         //   }
48337                         //
48338                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
48339                         //
48340                         //   type T = number;
48341                         //   declare function y(x: T): any;
48342                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
48343                         //   class C<T> {}
48344                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 256 /* ClassDeclaration */)) {
48345                             location = location.parent;
48346                         }
48347                         break;
48348                     case 343 /* JSDocTypedefTag */:
48349                     case 336 /* JSDocCallbackTag */:
48350                     case 337 /* JSDocEnumTag */:
48351                         // js type aliases do not resolve names from their host, so skip past it
48352                         var root = ts.getJSDocRoot(location);
48353                         if (root) {
48354                             location = root.parent;
48355                         }
48356                         break;
48357                     case 163 /* Parameter */:
48358                         if (lastLocation && (lastLocation === location.initializer ||
48359                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
48360                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
48361                                 associatedDeclarationForContainingInitializerOrBindingName = location;
48362                             }
48363                         }
48364                         break;
48365                     case 202 /* BindingElement */:
48366                         if (lastLocation && (lastLocation === location.initializer ||
48367                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
48368                             if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
48369                                 associatedDeclarationForContainingInitializerOrBindingName = location;
48370                             }
48371                         }
48372                         break;
48373                     case 189 /* InferType */:
48374                         if (meaning & 262144 /* TypeParameter */) {
48375                             var parameterName = location.typeParameter.name;
48376                             if (parameterName && name === parameterName.escapedText) {
48377                                 result = location.typeParameter.symbol;
48378                                 break loop;
48379                             }
48380                         }
48381                         break;
48382                 }
48383                 if (isSelfReferenceLocation(location)) {
48384                     lastSelfReferenceLocation = location;
48385                 }
48386                 lastLocation = location;
48387                 location = ts.isJSDocTemplateTag(location) ?
48388                     ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent :
48389                     location.parent;
48390             }
48391             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
48392             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
48393             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
48394             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
48395                 result.isReferenced |= meaning;
48396             }
48397             if (!result) {
48398                 if (lastLocation) {
48399                     ts.Debug.assert(lastLocation.kind === 303 /* SourceFile */);
48400                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
48401                         return lastLocation.symbol;
48402                     }
48403                 }
48404                 if (!excludeGlobals) {
48405                     result = lookup(globals, name, meaning);
48406                 }
48407             }
48408             if (!result) {
48409                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
48410                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
48411                         return requireSymbol;
48412                     }
48413                 }
48414             }
48415             if (!result) {
48416                 if (nameNotFoundMessage) {
48417                     if (!errorLocation ||
48418                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
48419                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
48420                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
48421                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
48422                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
48423                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
48424                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
48425                         var suggestion = void 0;
48426                         if (suggestionCount < maximumSuggestionCount) {
48427                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
48428                             var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration);
48429                             if (isGlobalScopeAugmentationDeclaration) {
48430                                 suggestion = undefined;
48431                             }
48432                             if (suggestion) {
48433                                 var suggestionName = symbolToString(suggestion);
48434                                 var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false);
48435                                 var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1
48436                                     : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1
48437                                         : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1;
48438                                 var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName);
48439                                 addErrorOrSuggestion(!isUncheckedJS, diagnostic);
48440                                 if (suggestion.valueDeclaration) {
48441                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
48442                                 }
48443                             }
48444                         }
48445                         if (!suggestion) {
48446                             if (nameArg) {
48447                                 var lib = getSuggestedLibForNonExistentName(nameArg);
48448                                 if (lib) {
48449                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib);
48450                                 }
48451                                 else {
48452                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
48453                                 }
48454                             }
48455                         }
48456                         suggestionCount++;
48457                     }
48458                 }
48459                 return undefined;
48460             }
48461             // Perform extra checks only if error reporting was requested
48462             if (nameNotFoundMessage) {
48463                 if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields)) {
48464                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
48465                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
48466                     // with ESNext+useDefineForClassFields because the scope semantics are different.
48467                     var propertyName = propertyWithInvalidInitializer.name;
48468                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
48469                     return undefined;
48470                 }
48471                 // Only check for block-scoped variable if we have an error location and are looking for the
48472                 // name with variable meaning
48473                 //      For example,
48474                 //          declare module foo {
48475                 //              interface bar {}
48476                 //          }
48477                 //      const foo/*1*/: foo/*2*/.bar;
48478                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
48479                 // block-scoped variable and namespace module. However, only when we
48480                 // try to resolve name in /*1*/ which is used in variable position,
48481                 // we want to check for block-scoped
48482                 if (errorLocation &&
48483                     (meaning & 2 /* BlockScopedVariable */ ||
48484                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
48485                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
48486                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
48487                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
48488                     }
48489                 }
48490                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
48491                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
48492                     var merged = getMergedSymbol(result);
48493                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
48494                         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));
48495                     }
48496                 }
48497                 // 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
48498                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
48499                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
48500                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
48501                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
48502                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
48503                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
48504                     }
48505                     // And it cannot refer to any declarations which come after it
48506                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
48507                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
48508                     }
48509                 }
48510                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
48511                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
48512                 }
48513             }
48514             return result;
48515         }
48516         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
48517             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
48518                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
48519                 if (typeOnlyDeclaration) {
48520                     var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */
48521                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
48522                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
48523                     var unescapedName = ts.unescapeLeadingUnderscores(name);
48524                     addTypeOnlyDeclarationRelatedInfo(error(useSite, message, unescapedName), typeOnlyDeclaration, unescapedName);
48525                 }
48526             }
48527         }
48528         function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) {
48529             if (!typeOnlyDeclaration)
48530                 return diagnostic;
48531             return ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here, unescapedName));
48532         }
48533         function getIsDeferredContext(location, lastLocation) {
48534             if (location.kind !== 213 /* ArrowFunction */ && location.kind !== 212 /* FunctionExpression */) {
48535                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
48536                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
48537                     (location.kind === 166 /* PropertyDeclaration */ && !ts.isStatic(location))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
48538             }
48539             if (lastLocation && lastLocation === location.name) {
48540                 return false;
48541             }
48542             // generator functions and async functions are not inlined in control flow when immediately invoked
48543             if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
48544                 return true;
48545             }
48546             return !ts.getImmediatelyInvokedFunctionExpression(location);
48547         }
48548         function isSelfReferenceLocation(node) {
48549             switch (node.kind) {
48550                 case 255 /* FunctionDeclaration */:
48551                 case 256 /* ClassDeclaration */:
48552                 case 257 /* InterfaceDeclaration */:
48553                 case 259 /* EnumDeclaration */:
48554                 case 258 /* TypeAliasDeclaration */:
48555                 case 260 /* ModuleDeclaration */: // For `namespace N { N; }`
48556                     return true;
48557                 default:
48558                     return false;
48559             }
48560         }
48561         function diagnosticName(nameArg) {
48562             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
48563         }
48564         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
48565             if (symbol.declarations) {
48566                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
48567                     var decl = _a[_i];
48568                     if (decl.kind === 162 /* TypeParameter */) {
48569                         var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
48570                         if (parent === container) {
48571                             return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
48572                         }
48573                     }
48574                 }
48575             }
48576             return false;
48577         }
48578         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
48579             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
48580                 return false;
48581             }
48582             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
48583             var location = container;
48584             while (location) {
48585                 if (ts.isClassLike(location.parent)) {
48586                     var classSymbol = getSymbolOfNode(location.parent);
48587                     if (!classSymbol) {
48588                         break;
48589                     }
48590                     // Check to see if a static member exists.
48591                     var constructorType = getTypeOfSymbol(classSymbol);
48592                     if (getPropertyOfType(constructorType, name)) {
48593                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
48594                         return true;
48595                     }
48596                     // No static member is present.
48597                     // Check if we're in an instance method and look for a relevant instance member.
48598                     if (location === container && !ts.isStatic(location)) {
48599                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
48600                         if (getPropertyOfType(instanceType, name)) {
48601                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
48602                             return true;
48603                         }
48604                     }
48605                 }
48606                 location = location.parent;
48607             }
48608             return false;
48609         }
48610         function checkAndReportErrorForExtendingInterface(errorLocation) {
48611             var expression = getEntityNameForExtendingInterface(errorLocation);
48612             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
48613                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
48614                 return true;
48615             }
48616             return false;
48617         }
48618         /**
48619          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
48620          * but returns undefined if that expression is not an EntityNameExpression.
48621          */
48622         function getEntityNameForExtendingInterface(node) {
48623             switch (node.kind) {
48624                 case 79 /* Identifier */:
48625                 case 205 /* PropertyAccessExpression */:
48626                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
48627                 case 227 /* ExpressionWithTypeArguments */:
48628                     if (ts.isEntityNameExpression(node.expression)) {
48629                         return node.expression;
48630                     }
48631                 // falls through
48632                 default:
48633                     return undefined;
48634             }
48635         }
48636         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
48637             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
48638             if (meaning === namespaceMeaning) {
48639                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
48640                 var parent = errorLocation.parent;
48641                 if (symbol) {
48642                     if (ts.isQualifiedName(parent)) {
48643                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
48644                         var propName = parent.right.escapedText;
48645                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
48646                         if (propType) {
48647                             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));
48648                             return true;
48649                         }
48650                     }
48651                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
48652                     return true;
48653                 }
48654             }
48655             return false;
48656         }
48657         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
48658             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
48659                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
48660                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
48661                     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));
48662                     return true;
48663                 }
48664             }
48665             return false;
48666         }
48667         function isPrimitiveTypeName(name) {
48668             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
48669         }
48670         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
48671             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 274 /* ExportSpecifier */) {
48672                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
48673                 return true;
48674             }
48675             return false;
48676         }
48677         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
48678             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
48679                 if (isPrimitiveTypeName(name)) {
48680                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
48681                     return true;
48682                 }
48683                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
48684                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
48685                     var rawName = ts.unescapeLeadingUnderscores(name);
48686                     if (isES2015OrLaterConstructorName(name)) {
48687                         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);
48688                     }
48689                     else if (maybeMappedType(errorLocation, symbol)) {
48690                         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");
48691                     }
48692                     else {
48693                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
48694                     }
48695                     return true;
48696                 }
48697             }
48698             return false;
48699         }
48700         function maybeMappedType(node, symbol) {
48701             var container = ts.findAncestor(node.parent, function (n) {
48702                 return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit";
48703             });
48704             if (container && container.members.length === 1) {
48705                 var type = getDeclaredTypeOfSymbol(symbol);
48706                 return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true);
48707             }
48708             return false;
48709         }
48710         function isES2015OrLaterConstructorName(n) {
48711             switch (n) {
48712                 case "Promise":
48713                 case "Symbol":
48714                 case "Map":
48715                 case "WeakMap":
48716                 case "Set":
48717                 case "WeakSet":
48718                     return true;
48719             }
48720             return false;
48721         }
48722         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
48723             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
48724                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
48725                 if (symbol) {
48726                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
48727                     return true;
48728                 }
48729             }
48730             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
48731                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
48732                 if (symbol) {
48733                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
48734                     return true;
48735                 }
48736             }
48737             return false;
48738         }
48739         function checkResolvedBlockScopedVariable(result, errorLocation) {
48740             var _a;
48741             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
48742             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
48743                 // constructor functions aren't block scoped
48744                 return;
48745             }
48746             // Block-scoped variables cannot be used before their definition
48747             var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 259 /* EnumDeclaration */); });
48748             if (declaration === undefined)
48749                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
48750             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
48751                 var diagnosticMessage = void 0;
48752                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
48753                 if (result.flags & 2 /* BlockScopedVariable */) {
48754                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
48755                 }
48756                 else if (result.flags & 32 /* Class */) {
48757                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
48758                 }
48759                 else if (result.flags & 256 /* RegularEnum */) {
48760                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
48761                 }
48762                 else {
48763                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
48764                     if (ts.shouldPreserveConstEnums(compilerOptions)) {
48765                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
48766                     }
48767                 }
48768                 if (diagnosticMessage) {
48769                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
48770                 }
48771             }
48772         }
48773         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
48774          * If at any point current node is equal to 'parent' node - return true.
48775          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
48776          */
48777         function isSameScopeDescendentOf(initial, parent, stopAt) {
48778             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
48779         }
48780         function getAnyImportSyntax(node) {
48781             switch (node.kind) {
48782                 case 264 /* ImportEqualsDeclaration */:
48783                     return node;
48784                 case 266 /* ImportClause */:
48785                     return node.parent;
48786                 case 267 /* NamespaceImport */:
48787                     return node.parent.parent;
48788                 case 269 /* ImportSpecifier */:
48789                     return node.parent.parent.parent;
48790                 default:
48791                     return undefined;
48792             }
48793         }
48794         function getDeclarationOfAliasSymbol(symbol) {
48795             return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration);
48796         }
48797         /**
48798          * An alias symbol is created by one of the following declarations:
48799          * import <symbol> = ...
48800          * import <symbol> from ...
48801          * import * as <symbol> from ...
48802          * import { x as <symbol> } from ...
48803          * export { x as <symbol> } from ...
48804          * export * as ns <symbol> from ...
48805          * export = <EntityNameExpression>
48806          * export default <EntityNameExpression>
48807          * module.exports = <EntityNameExpression>
48808          * {<Identifier>}
48809          * {name: <EntityNameExpression>}
48810          * const { x } = require ...
48811          */
48812         function isAliasSymbolDeclaration(node) {
48813             return node.kind === 264 /* ImportEqualsDeclaration */
48814                 || node.kind === 263 /* NamespaceExportDeclaration */
48815                 || node.kind === 266 /* ImportClause */ && !!node.name
48816                 || node.kind === 267 /* NamespaceImport */
48817                 || node.kind === 273 /* NamespaceExport */
48818                 || node.kind === 269 /* ImportSpecifier */
48819                 || node.kind === 274 /* ExportSpecifier */
48820                 || node.kind === 270 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
48821                 || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node)
48822                 || ts.isAccessExpression(node)
48823                     && ts.isBinaryExpression(node.parent)
48824                     && node.parent.left === node
48825                     && node.parent.operatorToken.kind === 63 /* EqualsToken */
48826                     && isAliasableOrJsExpression(node.parent.right)
48827                 || node.kind === 295 /* ShorthandPropertyAssignment */
48828                 || node.kind === 294 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer)
48829                 || ts.isRequireVariableDeclaration(node);
48830         }
48831         function isAliasableOrJsExpression(e) {
48832             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
48833         }
48834         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
48835             var commonJSPropertyAccess = getCommonJSPropertyAccess(node);
48836             if (commonJSPropertyAccess) {
48837                 var name = ts.getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
48838                 return ts.isIdentifier(commonJSPropertyAccess.name)
48839                     ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText))
48840                     : undefined;
48841             }
48842             if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 276 /* ExternalModuleReference */) {
48843                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node));
48844                 var resolved_4 = resolveExternalModuleSymbol(immediate);
48845                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
48846                 return resolved_4;
48847             }
48848             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
48849             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
48850             return resolved;
48851         }
48852         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
48853             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false) && !node.isTypeOnly) {
48854                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
48855                 var isExport = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */;
48856                 var message = isExport
48857                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
48858                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
48859                 var relatedMessage = isExport
48860                     ? ts.Diagnostics._0_was_exported_here
48861                     : ts.Diagnostics._0_was_imported_here;
48862                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
48863                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
48864             }
48865         }
48866         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
48867             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
48868             var exportSymbol = exportValue ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : moduleSymbol.exports.get(name);
48869             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
48870             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
48871             return resolved;
48872         }
48873         function isSyntacticDefault(node) {
48874             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
48875         }
48876         function getUsageModeForExpression(usage) {
48877             return ts.isStringLiteralLike(usage) ? ts.getModeForUsageLocation(ts.getSourceFileOfNode(usage), usage) : undefined;
48878         }
48879         function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) {
48880             return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS;
48881         }
48882         function isOnlyImportedAsDefault(usage) {
48883             var usageMode = getUsageModeForExpression(usage);
48884             return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */);
48885         }
48886         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) {
48887             var usageMode = file && getUsageModeForExpression(usage);
48888             if (file && usageMode !== undefined) {
48889                 var result = isESMFormatImportImportingCommonjsFormatFile(usageMode, file.impliedNodeFormat);
48890                 if (usageMode === ts.ModuleKind.ESNext || result) {
48891                     return result;
48892                 }
48893                 // fallthrough on cjs usages so we imply defaults for interop'd imports, too
48894             }
48895             if (!allowSyntheticDefaultImports) {
48896                 return false;
48897             }
48898             // Declaration files (and ambient modules)
48899             if (!file || file.isDeclarationFile) {
48900                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
48901                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
48902                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
48903                     return false;
48904                 }
48905                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
48906                 // So we check a bit more,
48907                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
48908                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
48909                     // it definitely is a module and does not have a synthetic default
48910                     return false;
48911                 }
48912                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
48913                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
48914                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
48915                 return true;
48916             }
48917             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
48918             if (!ts.isSourceFileJS(file)) {
48919                 return hasExportAssignmentSymbol(moduleSymbol);
48920             }
48921             // 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
48922             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
48923         }
48924         function getTargetOfImportClause(node, dontResolveAlias) {
48925             var _a;
48926             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
48927             if (moduleSymbol) {
48928                 var exportDefaultSymbol = void 0;
48929                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
48930                     exportDefaultSymbol = moduleSymbol;
48931                 }
48932                 else {
48933                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
48934                 }
48935                 var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile);
48936                 var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier);
48937                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier);
48938                 if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) {
48939                     if (hasExportAssignmentSymbol(moduleSymbol)) {
48940                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
48941                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
48942                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
48943                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
48944                         if (exportAssignment) {
48945                             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));
48946                         }
48947                     }
48948                     else {
48949                         reportNonDefaultExport(moduleSymbol, node);
48950                     }
48951                 }
48952                 else if (hasSyntheticDefault || hasDefaultOnly) {
48953                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
48954                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
48955                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
48956                     return resolved;
48957                 }
48958                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
48959                 return exportDefaultSymbol;
48960             }
48961         }
48962         function reportNonDefaultExport(moduleSymbol, node) {
48963             var _a, _b, _c;
48964             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
48965                 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));
48966             }
48967             else {
48968                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
48969                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
48970                 if (exportStar) {
48971                     var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) {
48972                         var _a, _b;
48973                         return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier &&
48974                             ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
48975                     });
48976                     if (defaultExport) {
48977                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
48978                     }
48979                 }
48980             }
48981         }
48982         function getTargetOfNamespaceImport(node, dontResolveAlias) {
48983             var moduleSpecifier = node.parent.parent.moduleSpecifier;
48984             var immediate = resolveExternalModuleName(node, moduleSpecifier);
48985             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
48986             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
48987             return resolved;
48988         }
48989         function getTargetOfNamespaceExport(node, dontResolveAlias) {
48990             var moduleSpecifier = node.parent.moduleSpecifier;
48991             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
48992             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
48993             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
48994             return resolved;
48995         }
48996         // This function creates a synthetic symbol that combines the value side of one symbol with the
48997         // type/namespace side of another symbol. Consider this example:
48998         //
48999         //   declare module graphics {
49000         //       interface Point {
49001         //           x: number;
49002         //           y: number;
49003         //       }
49004         //   }
49005         //   declare var graphics: {
49006         //       Point: new (x: number, y: number) => graphics.Point;
49007         //   }
49008         //   declare module "graphics" {
49009         //       export = graphics;
49010         //   }
49011         //
49012         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
49013         // property with the type/namespace side interface 'Point'.
49014         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
49015             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
49016                 return unknownSymbol;
49017             }
49018             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
49019                 return valueSymbol;
49020             }
49021             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
49022             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
49023             result.parent = valueSymbol.parent || typeSymbol.parent;
49024             if (valueSymbol.valueDeclaration)
49025                 result.valueDeclaration = valueSymbol.valueDeclaration;
49026             if (typeSymbol.members)
49027                 result.members = new ts.Map(typeSymbol.members);
49028             if (valueSymbol.exports)
49029                 result.exports = new ts.Map(valueSymbol.exports);
49030             return result;
49031         }
49032         function getExportOfModule(symbol, name, specifier, dontResolveAlias) {
49033             if (symbol.flags & 1536 /* Module */) {
49034                 var exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText);
49035                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
49036                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
49037                 return resolved;
49038             }
49039         }
49040         function getPropertyOfVariable(symbol, name) {
49041             if (symbol.flags & 3 /* Variable */) {
49042                 var typeAnnotation = symbol.valueDeclaration.type;
49043                 if (typeAnnotation) {
49044                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
49045                 }
49046             }
49047         }
49048         function getExternalModuleMember(node, specifier, dontResolveAlias) {
49049             var _a, _b;
49050             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
49051             var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier;
49052             var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217
49053             var name = !ts.isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
49054             if (!ts.isIdentifier(name)) {
49055                 return undefined;
49056             }
49057             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || ts.getESModuleInterop(compilerOptions));
49058             var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError);
49059             if (targetSymbol) {
49060                 if (name.escapedText) {
49061                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
49062                         return moduleSymbol;
49063                     }
49064                     var symbolFromVariable = void 0;
49065                     // First check if module was specified with "export=". If so, get the member from the resolved type
49066                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
49067                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText, /*skipObjectFunctionPropertyAugment*/ true);
49068                     }
49069                     else {
49070                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
49071                     }
49072                     // if symbolFromVariable is export - get its final target
49073                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
49074                     var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias);
49075                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
49076                         var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile);
49077                         if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) {
49078                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
49079                         }
49080                     }
49081                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
49082                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
49083                         symbolFromModule || symbolFromVariable;
49084                     if (!symbol) {
49085                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
49086                         var declarationName = ts.declarationNameToString(name);
49087                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
49088                         if (suggestion !== undefined) {
49089                             var suggestionName = symbolToString(suggestion);
49090                             var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
49091                             if (suggestion.valueDeclaration) {
49092                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
49093                             }
49094                         }
49095                         else {
49096                             if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) {
49097                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
49098                             }
49099                             else {
49100                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
49101                             }
49102                         }
49103                     }
49104                     return symbol;
49105                 }
49106             }
49107         }
49108         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
49109             var _a, _b;
49110             var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText);
49111             var exports = moduleSymbol.exports;
49112             if (localSymbol) {
49113                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
49114                 if (exportedEqualsSymbol) {
49115                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
49116                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
49117                 }
49118                 else {
49119                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
49120                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
49121                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
49122                     if (localSymbol.declarations) {
49123                         ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
49124                             return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
49125                         }), false));
49126                     }
49127                 }
49128             }
49129             else {
49130                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
49131             }
49132         }
49133         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
49134             if (moduleKind >= ts.ModuleKind.ES2015) {
49135                 var message = ts.getESModuleInterop(compilerOptions) ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
49136                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
49137                 error(name, message, declarationName);
49138             }
49139             else {
49140                 if (ts.isInJSFile(node)) {
49141                     var message = ts.getESModuleInterop(compilerOptions) ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
49142                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
49143                     error(name, message, declarationName);
49144                 }
49145                 else {
49146                     var message = ts.getESModuleInterop(compilerOptions) ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
49147                         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;
49148                     error(name, message, declarationName, declarationName, moduleName);
49149                 }
49150             }
49151         }
49152         function getTargetOfImportSpecifier(node, dontResolveAlias) {
49153             var root = ts.isBindingElement(node) ? ts.getRootDeclaration(node) : node.parent.parent.parent;
49154             var commonJSPropertyAccess = getCommonJSPropertyAccess(root);
49155             var resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
49156             var name = node.propertyName || node.name;
49157             if (commonJSPropertyAccess && resolved && ts.isIdentifier(name)) {
49158                 return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
49159             }
49160             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
49161             return resolved;
49162         }
49163         function getCommonJSPropertyAccess(node) {
49164             if (ts.isVariableDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) {
49165                 return node.initializer;
49166             }
49167         }
49168         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
49169             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
49170             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
49171             return resolved;
49172         }
49173         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
49174             var resolved = node.parent.parent.moduleSpecifier ?
49175                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
49176                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
49177             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
49178             return resolved;
49179         }
49180         function getTargetOfExportAssignment(node, dontResolveAlias) {
49181             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
49182             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
49183             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
49184             return resolved;
49185         }
49186         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
49187             if (ts.isClassExpression(expression)) {
49188                 return checkExpressionCached(expression).symbol;
49189             }
49190             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
49191                 return undefined;
49192             }
49193             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
49194             if (aliasLike) {
49195                 return aliasLike;
49196             }
49197             checkExpressionCached(expression);
49198             return getNodeLinks(expression).resolvedSymbol;
49199         }
49200         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
49201             var expression = node.initializer;
49202             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
49203         }
49204         function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
49205             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* EqualsToken */)) {
49206                 return undefined;
49207             }
49208             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
49209         }
49210         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
49211             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
49212             switch (node.kind) {
49213                 case 264 /* ImportEqualsDeclaration */:
49214                 case 253 /* VariableDeclaration */:
49215                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
49216                 case 266 /* ImportClause */:
49217                     return getTargetOfImportClause(node, dontRecursivelyResolve);
49218                 case 267 /* NamespaceImport */:
49219                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
49220                 case 273 /* NamespaceExport */:
49221                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
49222                 case 269 /* ImportSpecifier */:
49223                 case 202 /* BindingElement */:
49224                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
49225                 case 274 /* ExportSpecifier */:
49226                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
49227                 case 270 /* ExportAssignment */:
49228                 case 220 /* BinaryExpression */:
49229                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
49230                 case 263 /* NamespaceExportDeclaration */:
49231                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
49232                 case 295 /* ShorthandPropertyAssignment */:
49233                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
49234                 case 294 /* PropertyAssignment */:
49235                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
49236                 case 206 /* ElementAccessExpression */:
49237                 case 205 /* PropertyAccessExpression */:
49238                     return getTargetOfAccessExpression(node, dontRecursivelyResolve);
49239                 default:
49240                     return ts.Debug.fail();
49241             }
49242         }
49243         /**
49244          * Indicates that a symbol is an alias that does not merge with a local declaration.
49245          * OR Is a JSContainer which may merge an alias with a local declaration
49246          */
49247         function isNonLocalAlias(symbol, excludes) {
49248             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
49249             if (!symbol)
49250                 return false;
49251             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
49252         }
49253         function resolveSymbol(symbol, dontResolveAlias) {
49254             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
49255         }
49256         function resolveAlias(symbol) {
49257             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
49258             var links = getSymbolLinks(symbol);
49259             if (!links.target) {
49260                 links.target = resolvingSymbol;
49261                 var node = getDeclarationOfAliasSymbol(symbol);
49262                 if (!node)
49263                     return ts.Debug.fail();
49264                 var target = getTargetOfAliasDeclaration(node);
49265                 if (links.target === resolvingSymbol) {
49266                     links.target = target || unknownSymbol;
49267                 }
49268                 else {
49269                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
49270                 }
49271             }
49272             else if (links.target === resolvingSymbol) {
49273                 links.target = unknownSymbol;
49274             }
49275             return links.target;
49276         }
49277         function tryResolveAlias(symbol) {
49278             var links = getSymbolLinks(symbol);
49279             if (links.target !== resolvingSymbol) {
49280                 return resolveAlias(symbol);
49281             }
49282             return undefined;
49283         }
49284         /**
49285          * Marks a symbol as type-only if its declaration is syntactically type-only.
49286          * If it is not itself marked type-only, but resolves to a type-only alias
49287          * somewhere in its resolution chain, save a reference to the type-only alias declaration
49288          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
49289          *
49290          * This function is called on each alias declaration that could be type-only or resolve to
49291          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
49292          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
49293          * and issue an error if so.
49294          *
49295          * @param aliasDeclaration The alias declaration not marked as type-only
49296          * @param immediateTarget The symbol to which the alias declaration immediately resolves
49297          * @param finalTarget The symbol to which the alias declaration ultimately resolves
49298          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
49299          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
49300          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
49301          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
49302          * must still be checked for a type-only marker, overwriting the previous negative result if found.
49303          */
49304         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
49305             if (!aliasDeclaration || ts.isPropertyAccessExpression(aliasDeclaration))
49306                 return false;
49307             // If the declaration itself is type-only, mark it and return.
49308             // No need to check what it resolves to.
49309             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
49310             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
49311                 var links_1 = getSymbolLinks(sourceSymbol);
49312                 links_1.typeOnlyDeclaration = aliasDeclaration;
49313                 return true;
49314             }
49315             var links = getSymbolLinks(sourceSymbol);
49316             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
49317                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
49318         }
49319         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
49320             var _a, _b, _c;
49321             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
49322                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
49323                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
49324                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
49325             }
49326             return !!aliasDeclarationLinks.typeOnlyDeclaration;
49327         }
49328         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
49329         function getTypeOnlyAliasDeclaration(symbol) {
49330             if (!(symbol.flags & 2097152 /* Alias */)) {
49331                 return undefined;
49332             }
49333             var links = getSymbolLinks(symbol);
49334             return links.typeOnlyDeclaration || undefined;
49335         }
49336         function markExportAsReferenced(node) {
49337             var symbol = getSymbolOfNode(node);
49338             var target = resolveAlias(symbol);
49339             if (target) {
49340                 var markAlias = target === unknownSymbol ||
49341                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
49342                 if (markAlias) {
49343                     markAliasSymbolAsReferenced(symbol);
49344                 }
49345             }
49346         }
49347         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
49348         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
49349         // the alias as an expression (which recursively takes us back here if the target references another alias).
49350         function markAliasSymbolAsReferenced(symbol) {
49351             var links = getSymbolLinks(symbol);
49352             if (!links.referenced) {
49353                 links.referenced = true;
49354                 var node = getDeclarationOfAliasSymbol(symbol);
49355                 if (!node)
49356                     return ts.Debug.fail();
49357                 // We defer checking of the reference of an `import =` until the import itself is referenced,
49358                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
49359                 // position.
49360                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
49361                     var target = resolveSymbol(symbol);
49362                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
49363                         // import foo = <symbol>
49364                         checkExpressionCached(node.moduleReference);
49365                     }
49366                 }
49367             }
49368         }
49369         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
49370         // but their usage in value positions must be tracked to determine if the import can be type-only.
49371         function markConstEnumAliasAsReferenced(symbol) {
49372             var links = getSymbolLinks(symbol);
49373             if (!links.constEnumReferenced) {
49374                 links.constEnumReferenced = true;
49375             }
49376         }
49377         // This function is only for imports with entity names
49378         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
49379             // There are three things we might try to look for. In the following examples,
49380             // the search term is enclosed in |...|:
49381             //
49382             //     import a = |b|; // Namespace
49383             //     import a = |b.c|; // Value, type, namespace
49384             //     import a = |b.c|.d; // Namespace
49385             if (entityName.kind === 79 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
49386                 entityName = entityName.parent;
49387             }
49388             // Check for case 1 and 3 in the above example
49389             if (entityName.kind === 79 /* Identifier */ || entityName.parent.kind === 160 /* QualifiedName */) {
49390                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
49391             }
49392             else {
49393                 // Case 2 in above example
49394                 // entityName.kind could be a QualifiedName or a Missing identifier
49395                 ts.Debug.assert(entityName.parent.kind === 264 /* ImportEqualsDeclaration */);
49396                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
49397             }
49398         }
49399         function getFullyQualifiedName(symbol, containingLocation) {
49400             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
49401         }
49402         function getContainingQualifiedNameNode(node) {
49403             while (ts.isQualifiedName(node.parent)) {
49404                 node = node.parent;
49405             }
49406             return node;
49407         }
49408         function tryGetQualifiedNameAsValue(node) {
49409             var left = ts.getFirstIdentifier(node);
49410             var symbol = resolveName(left, left.escapedText, 111551 /* Value */, undefined, left, /*isUse*/ true);
49411             if (!symbol) {
49412                 return undefined;
49413             }
49414             while (ts.isQualifiedName(left.parent)) {
49415                 var type = getTypeOfSymbol(symbol);
49416                 symbol = getPropertyOfType(type, left.parent.right.escapedText);
49417                 if (!symbol) {
49418                     return undefined;
49419                 }
49420                 left = left.parent;
49421             }
49422             return symbol;
49423         }
49424         /**
49425          * Resolves a qualified name and any involved aliases.
49426          */
49427         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
49428             if (ts.nodeIsMissing(name)) {
49429                 return undefined;
49430             }
49431             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
49432             var symbol;
49433             if (name.kind === 79 /* Identifier */) {
49434                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
49435                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
49436                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false));
49437                 if (!symbol) {
49438                     return getMergedSymbol(symbolFromJSPrototype);
49439                 }
49440             }
49441             else if (name.kind === 160 /* QualifiedName */ || name.kind === 205 /* PropertyAccessExpression */) {
49442                 var left = name.kind === 160 /* QualifiedName */ ? name.left : name.expression;
49443                 var right = name.kind === 160 /* QualifiedName */ ? name.right : name.name;
49444                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
49445                 if (!namespace || ts.nodeIsMissing(right)) {
49446                     return undefined;
49447                 }
49448                 else if (namespace === unknownSymbol) {
49449                     return namespace;
49450                 }
49451                 if (namespace.valueDeclaration &&
49452                     ts.isInJSFile(namespace.valueDeclaration) &&
49453                     ts.isVariableDeclaration(namespace.valueDeclaration) &&
49454                     namespace.valueDeclaration.initializer &&
49455                     isCommonJsRequire(namespace.valueDeclaration.initializer)) {
49456                     var moduleName = namespace.valueDeclaration.initializer.arguments[0];
49457                     var moduleSym = resolveExternalModuleName(moduleName, moduleName);
49458                     if (moduleSym) {
49459                         var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
49460                         if (resolvedModuleSymbol) {
49461                             namespace = resolvedModuleSymbol;
49462                         }
49463                     }
49464                 }
49465                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
49466                 if (!symbol) {
49467                     if (!ignoreErrors) {
49468                         var namespaceName = getFullyQualifiedName(namespace);
49469                         var declarationName = ts.declarationNameToString(right);
49470                         var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace);
49471                         if (suggestionForNonexistentModule) {
49472                             error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule));
49473                             return undefined;
49474                         }
49475                         var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name);
49476                         var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet
49477                             && (meaning & 788968 /* Type */)
49478                             && containingQualifiedName
49479                             && !ts.isTypeOfExpression(containingQualifiedName.parent)
49480                             && tryGetQualifiedNameAsValue(containingQualifiedName);
49481                         if (canSuggestTypeof) {
49482                             error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName));
49483                             return undefined;
49484                         }
49485                         if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) {
49486                             var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */));
49487                             if (exportedTypeSymbol) {
49488                                 error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText));
49489                                 return undefined;
49490                             }
49491                         }
49492                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
49493                     }
49494                     return undefined;
49495                 }
49496             }
49497             else {
49498                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
49499             }
49500             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
49501             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 270 /* ExportAssignment */)) {
49502                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
49503             }
49504             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
49505         }
49506         /**
49507          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
49508          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
49509          * name resolution won't work either.
49510          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
49511          */
49512         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
49513             if (isJSDocTypeReference(name.parent)) {
49514                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
49515                 if (secondaryLocation) {
49516                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
49517                 }
49518             }
49519         }
49520         function getAssignmentDeclarationLocation(node) {
49521             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
49522             if (typeAlias) {
49523                 return;
49524             }
49525             var host = ts.getJSDocHost(node);
49526             if (host &&
49527                 ts.isExpressionStatement(host) &&
49528                 ts.isBinaryExpression(host.expression) &&
49529                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
49530                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
49531                 var symbol = getSymbolOfNode(host.expression.left);
49532                 if (symbol) {
49533                     return getDeclarationOfJSPrototypeContainer(symbol);
49534                 }
49535             }
49536             if (host && (ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
49537                 ts.isBinaryExpression(host.parent.parent) &&
49538                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
49539                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
49540                 var symbol = getSymbolOfNode(host.parent.parent.left);
49541                 if (symbol) {
49542                     return getDeclarationOfJSPrototypeContainer(symbol);
49543                 }
49544             }
49545             var sig = ts.getEffectiveJSDocHost(node);
49546             if (sig && ts.isFunctionLike(sig)) {
49547                 var symbol = getSymbolOfNode(sig);
49548                 return symbol && symbol.valueDeclaration;
49549             }
49550         }
49551         function getDeclarationOfJSPrototypeContainer(symbol) {
49552             var decl = symbol.parent.valueDeclaration;
49553             if (!decl) {
49554                 return undefined;
49555             }
49556             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
49557                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
49558                     undefined;
49559             return initializer || decl;
49560         }
49561         /**
49562          * Get the real symbol of a declaration with an expando initializer.
49563          *
49564          * Normally, declarations have an associated symbol, but when a declaration has an expando
49565          * initializer, the expando's symbol is the one that has all the members merged into it.
49566          */
49567         function getExpandoSymbol(symbol) {
49568             var decl = symbol.valueDeclaration;
49569             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
49570                 return undefined;
49571             }
49572             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
49573             if (init) {
49574                 var initSymbol = getSymbolOfNode(init);
49575                 if (initSymbol) {
49576                     return mergeJSSymbols(initSymbol, symbol);
49577                 }
49578             }
49579         }
49580         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
49581             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
49582             var errorMessage = isClassic ?
49583                 ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
49584                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
49585             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage);
49586         }
49587         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
49588             if (isForAugmentation === void 0) { isForAugmentation = false; }
49589             return ts.isStringLiteralLike(moduleReferenceExpression)
49590                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
49591                 : undefined;
49592         }
49593         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
49594             var _a, _b, _c, _d, _e, _f, _g;
49595             if (isForAugmentation === void 0) { isForAugmentation = false; }
49596             if (ts.startsWith(moduleReference, "@types/")) {
49597                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
49598                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
49599                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
49600             }
49601             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
49602             if (ambientModule) {
49603                 return ambientModule;
49604             }
49605             var currentSourceFile = ts.getSourceFileOfNode(location);
49606             var contextSpecifier = ts.isStringLiteralLike(location)
49607                 ? location
49608                 : ((_a = ts.findAncestor(location, ts.isImportCall)) === null || _a === void 0 ? void 0 : _a.arguments[0]) ||
49609                     ((_b = ts.findAncestor(location, ts.isImportDeclaration)) === null || _b === void 0 ? void 0 : _b.moduleSpecifier) ||
49610                     ((_c = ts.findAncestor(location, ts.isExternalModuleImportEqualsDeclaration)) === null || _c === void 0 ? void 0 : _c.moduleReference.expression) ||
49611                     ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) ||
49612                     ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) ||
49613                     ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal);
49614             var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat;
49615             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode);
49616             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
49617             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
49618             if (sourceFile) {
49619                 if (sourceFile.symbol) {
49620                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
49621                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
49622                     }
49623                     if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeNext) {
49624                         var isSyncImport = (currentSourceFile.impliedNodeFormat === ts.ModuleKind.CommonJS && !ts.findAncestor(location, ts.isImportCall)) || !!ts.findAncestor(location, ts.isImportEqualsDeclaration);
49625                         if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) {
49626                             error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference);
49627                         }
49628                         if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) {
49629                             error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports);
49630                         }
49631                     }
49632                     // merged symbol is module declaration symbol combined with all augmentations
49633                     return getMergedSymbol(sourceFile.symbol);
49634                 }
49635                 if (moduleNotFoundError) {
49636                     // report errors only if it was requested
49637                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
49638                 }
49639                 return undefined;
49640             }
49641             if (patternAmbientModules) {
49642                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
49643                 if (pattern) {
49644                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
49645                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
49646                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
49647                     // from a.foo.
49648                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
49649                     if (augmentation) {
49650                         return getMergedSymbol(augmentation);
49651                     }
49652                     return getMergedSymbol(pattern.symbol);
49653                 }
49654             }
49655             // May be an untyped module. If so, ignore resolutionDiagnostic.
49656             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) {
49657                 if (isForAugmentation) {
49658                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
49659                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
49660                 }
49661                 else {
49662                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
49663                 }
49664                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
49665                 return undefined;
49666             }
49667             if (moduleNotFoundError) {
49668                 // See if this was possibly a projectReference redirect
49669                 if (resolvedModule) {
49670                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
49671                     if (redirect) {
49672                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
49673                         return undefined;
49674                     }
49675                 }
49676                 if (resolutionDiagnostic) {
49677                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
49678                 }
49679                 else {
49680                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
49681                     var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference);
49682                     var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
49683                     var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 ||
49684                         moduleResolutionKind === ts.ModuleResolutionKind.NodeNext;
49685                     if (tsExtension) {
49686                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
49687                         var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension);
49688                         var replacedImportSource = importSourceWithoutExtension;
49689                         /**
49690                          * Direct users to import source with .js extension if outputting an ES module.
49691                          * @see https://github.com/microsoft/TypeScript/issues/42151
49692                          */
49693                         if (moduleKind >= ts.ModuleKind.ES2015) {
49694                             replacedImportSource += tsExtension === ".mts" /* Mts */ ? ".mjs" : tsExtension === ".cts" /* Cts */ ? ".cjs" : ".js";
49695                         }
49696                         error(errorNode, diag, tsExtension, replacedImportSource);
49697                     }
49698                     else if (!compilerOptions.resolveJsonModule &&
49699                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
49700                         ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Classic &&
49701                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
49702                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
49703                     }
49704                     else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) {
49705                         var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path));
49706                         var suggestedExt = (_g = suggestedExtensions.find(function (_a) {
49707                             var actualExt = _a[0], _importExt = _a[1];
49708                             return host.fileExists(absoluteRef_1 + actualExt);
49709                         })) === null || _g === void 0 ? void 0 : _g[1];
49710                         if (suggestedExt) {
49711                             error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt);
49712                         }
49713                         else {
49714                             error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path);
49715                         }
49716                     }
49717                     else {
49718                         error(errorNode, moduleNotFoundError, moduleReference);
49719                     }
49720                 }
49721             }
49722             return undefined;
49723         }
49724         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
49725             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
49726             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
49727                 ? typesPackageExists(packageId.name)
49728                     ? ts.chainDiagnosticMessages(
49729                     /*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))
49730                     : packageBundlesTypes(packageId.name)
49731                         ? ts.chainDiagnosticMessages(
49732                         /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, packageId.name, moduleReference)
49733                         : ts.chainDiagnosticMessages(
49734                         /*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))
49735                 : undefined;
49736             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));
49737         }
49738         function typesPackageExists(packageName) {
49739             return getPackagesMap().has(ts.getTypesPackageName(packageName));
49740         }
49741         function packageBundlesTypes(packageName) {
49742             return !!getPackagesMap().get(packageName);
49743         }
49744         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
49745             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
49746                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
49747                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
49748                 return getMergedSymbol(exported) || moduleSymbol;
49749             }
49750             return undefined;
49751         }
49752         function getCommonJsExportEquals(exported, moduleSymbol) {
49753             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
49754                 return exported;
49755             }
49756             var links = getSymbolLinks(exported);
49757             if (links.cjsExportMerged) {
49758                 return links.cjsExportMerged;
49759             }
49760             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
49761             merged.flags = merged.flags | 512 /* ValueModule */;
49762             if (merged.exports === undefined) {
49763                 merged.exports = ts.createSymbolTable();
49764             }
49765             moduleSymbol.exports.forEach(function (s, name) {
49766                 if (name === "export=" /* ExportEquals */)
49767                     return;
49768                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
49769             });
49770             getSymbolLinks(merged).cjsExportMerged = merged;
49771             return links.cjsExportMerged = merged;
49772         }
49773         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
49774         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
49775         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
49776         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
49777             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
49778             if (!dontResolveAlias && symbol) {
49779                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 303 /* SourceFile */)) {
49780                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
49781                         ? "allowSyntheticDefaultImports"
49782                         : "esModuleInterop";
49783                     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);
49784                     return symbol;
49785                 }
49786                 var referenceParent = referencingLocation.parent;
49787                 if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
49788                     ts.isImportCall(referenceParent)) {
49789                     var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier;
49790                     var type = getTypeOfSymbol(symbol);
49791                     var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference);
49792                     if (defaultOnlyType) {
49793                         return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent);
49794                     }
49795                     if (ts.getESModuleInterop(compilerOptions)) {
49796                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
49797                         if (!sigs || !sigs.length) {
49798                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
49799                         }
49800                         if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) {
49801                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference);
49802                             return cloneTypeAsModuleType(symbol, moduleType, referenceParent);
49803                         }
49804                     }
49805                 }
49806             }
49807             return symbol;
49808         }
49809         /**
49810          * Create a new symbol which has the module's type less the call and construct signatures
49811          */
49812         function cloneTypeAsModuleType(symbol, moduleType, referenceParent) {
49813             var result = createSymbol(symbol.flags, symbol.escapedName);
49814             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
49815             result.parent = symbol.parent;
49816             result.target = symbol;
49817             result.originatingImport = referenceParent;
49818             if (symbol.valueDeclaration)
49819                 result.valueDeclaration = symbol.valueDeclaration;
49820             if (symbol.constEnumOnlyModule)
49821                 result.constEnumOnlyModule = true;
49822             if (symbol.members)
49823                 result.members = new ts.Map(symbol.members);
49824             if (symbol.exports)
49825                 result.exports = new ts.Map(symbol.exports);
49826             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
49827             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.indexInfos);
49828             return result;
49829         }
49830         function hasExportAssignmentSymbol(moduleSymbol) {
49831             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
49832         }
49833         function getExportsOfModuleAsArray(moduleSymbol) {
49834             return symbolsToArray(getExportsOfModule(moduleSymbol));
49835         }
49836         function getExportsAndPropertiesOfModule(moduleSymbol) {
49837             var exports = getExportsOfModuleAsArray(moduleSymbol);
49838             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
49839             if (exportEquals !== moduleSymbol) {
49840                 var type = getTypeOfSymbol(exportEquals);
49841                 if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
49842                     ts.addRange(exports, getPropertiesOfType(type));
49843                 }
49844             }
49845             return exports;
49846         }
49847         function forEachExportAndPropertyOfModule(moduleSymbol, cb) {
49848             var exports = getExportsOfModule(moduleSymbol);
49849             exports.forEach(function (symbol, key) {
49850                 if (!isReservedMemberName(key)) {
49851                     cb(symbol, key);
49852                 }
49853             });
49854             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
49855             if (exportEquals !== moduleSymbol) {
49856                 var type = getTypeOfSymbol(exportEquals);
49857                 if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
49858                     forEachPropertyOfType(type, function (symbol, escapedName) {
49859                         cb(symbol, escapedName);
49860                     });
49861                 }
49862             }
49863         }
49864         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
49865             var symbolTable = getExportsOfModule(moduleSymbol);
49866             if (symbolTable) {
49867                 return symbolTable.get(memberName);
49868             }
49869         }
49870         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
49871             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
49872             if (symbol) {
49873                 return symbol;
49874             }
49875             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
49876             if (exportEquals === moduleSymbol) {
49877                 return undefined;
49878             }
49879             var type = getTypeOfSymbol(exportEquals);
49880             return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined;
49881         }
49882         function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) {
49883             return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ ||
49884                 ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ ||
49885                 // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path
49886                 isArrayType(resolvedExternalModuleType) ||
49887                 isTupleType(resolvedExternalModuleType));
49888         }
49889         function getExportsOfSymbol(symbol) {
49890             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
49891                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
49892                     symbol.exports || emptySymbols;
49893         }
49894         function getExportsOfModule(moduleSymbol) {
49895             var links = getSymbolLinks(moduleSymbol);
49896             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
49897         }
49898         /**
49899          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
49900          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
49901          */
49902         function extendExportSymbols(target, source, lookupTable, exportNode) {
49903             if (!source)
49904                 return;
49905             source.forEach(function (sourceSymbol, id) {
49906                 if (id === "default" /* Default */)
49907                     return;
49908                 var targetSymbol = target.get(id);
49909                 if (!targetSymbol) {
49910                     target.set(id, sourceSymbol);
49911                     if (lookupTable && exportNode) {
49912                         lookupTable.set(id, {
49913                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
49914                         });
49915                     }
49916                 }
49917                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
49918                     var collisionTracker = lookupTable.get(id);
49919                     if (!collisionTracker.exportsWithDuplicate) {
49920                         collisionTracker.exportsWithDuplicate = [exportNode];
49921                     }
49922                     else {
49923                         collisionTracker.exportsWithDuplicate.push(exportNode);
49924                     }
49925                 }
49926             });
49927         }
49928         function getExportsOfModuleWorker(moduleSymbol) {
49929             var visitedSymbols = [];
49930             // A module defined by an 'export=' consists of one export that needs to be resolved
49931             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
49932             return visit(moduleSymbol) || emptySymbols;
49933             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
49934             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
49935             function visit(symbol) {
49936                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
49937                     return;
49938                 }
49939                 var symbols = new ts.Map(symbol.exports);
49940                 // All export * declarations are collected in an __export symbol by the binder
49941                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
49942                 if (exportStars) {
49943                     var nestedSymbols = ts.createSymbolTable();
49944                     var lookupTable_1 = new ts.Map();
49945                     if (exportStars.declarations) {
49946                         for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
49947                             var node = _a[_i];
49948                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
49949                             var exportedSymbols = visit(resolvedModule);
49950                             extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
49951                         }
49952                     }
49953                     lookupTable_1.forEach(function (_a, id) {
49954                         var exportsWithDuplicate = _a.exportsWithDuplicate;
49955                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
49956                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
49957                             return;
49958                         }
49959                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
49960                             var node = exportsWithDuplicate_1[_i];
49961                             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)));
49962                         }
49963                     });
49964                     extendExportSymbols(symbols, nestedSymbols);
49965                 }
49966                 return symbols;
49967             }
49968         }
49969         function getMergedSymbol(symbol) {
49970             var merged;
49971             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
49972         }
49973         function getSymbolOfNode(node) {
49974             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
49975         }
49976         function getParentOfSymbol(symbol) {
49977             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
49978         }
49979         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
49980             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
49981             var id = getNodeId(containingFile);
49982             var links = getSymbolLinks(symbol);
49983             var results;
49984             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
49985                 return results;
49986             }
49987             if (containingFile && containingFile.imports) {
49988                 // Try to make an import using an import already in the enclosing file, if possible
49989                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
49990                     var importRef = _a[_i];
49991                     if (ts.nodeIsSynthesized(importRef))
49992                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
49993                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
49994                     if (!resolvedModule)
49995                         continue;
49996                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
49997                     if (!ref)
49998                         continue;
49999                     results = ts.append(results, resolvedModule);
50000                 }
50001                 if (ts.length(results)) {
50002                     (links.extendedContainersByFile || (links.extendedContainersByFile = new ts.Map())).set(id, results);
50003                     return results;
50004                 }
50005             }
50006             if (links.extendedContainers) {
50007                 return links.extendedContainers;
50008             }
50009             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
50010             var otherFiles = host.getSourceFiles();
50011             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
50012                 var file = otherFiles_1[_b];
50013                 if (!ts.isExternalModule(file))
50014                     continue;
50015                 var sym = getSymbolOfNode(file);
50016                 var ref = getAliasForSymbolInContainer(sym, symbol);
50017                 if (!ref)
50018                     continue;
50019                 results = ts.append(results, sym);
50020             }
50021             return links.extendedContainers = results || ts.emptyArray;
50022         }
50023         /**
50024          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
50025          * is just its' `.parent`, but for locals, this value is `undefined`
50026          */
50027         function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
50028             var container = getParentOfSymbol(symbol);
50029             // Type parameters end up in the `members` lists but are not externally visible
50030             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
50031                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
50032                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
50033                 var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning);
50034                 if (enclosingDeclaration &&
50035                     container.flags & getQualifiedLeftMeaning(meaning) &&
50036                     getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
50037                     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
50038                 }
50039                 // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type
50040                 // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`)
50041                 var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning))
50042                     && container.flags & 788968 /* Type */
50043                     && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */
50044                     && meaning === 111551 /* Value */
50045                     ? forEachSymbolTableInScope(enclosingDeclaration, function (t) {
50046                         return ts.forEachEntry(t, function (s) {
50047                             if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) {
50048                                 return s;
50049                             }
50050                         });
50051                     }) : undefined;
50052                 var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers, true), [container], false) : __spreadArray(__spreadArray([], additionalContainers, true), [container], false);
50053                 res = ts.append(res, objectLiteralContainer);
50054                 res = ts.addRange(res, reexportContainers);
50055                 return res;
50056             }
50057             var candidates = ts.mapDefined(symbol.declarations, function (d) {
50058                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
50059                     return getSymbolOfNode(d.parent);
50060                 }
50061                 if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 63 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
50062                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
50063                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
50064                     }
50065                     checkExpressionCached(d.parent.left.expression);
50066                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
50067                 }
50068             });
50069             if (!ts.length(candidates)) {
50070                 return undefined;
50071             }
50072             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
50073             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
50074                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
50075             }
50076         }
50077         function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
50078             // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
50079             // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
50080             // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
50081             var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
50082             if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent)) {
50083                 if (ts.isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || ts.isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
50084                     return getSymbolOfNode(firstDecl.parent);
50085                 }
50086             }
50087         }
50088         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
50089             var fileSymbol = getExternalModuleContainer(d);
50090             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
50091             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
50092         }
50093         function getAliasForSymbolInContainer(container, symbol) {
50094             if (container === getParentOfSymbol(symbol)) {
50095                 // fast path, `symbol` is either already the alias or isn't aliased
50096                 return symbol;
50097             }
50098             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
50099             // the container itself as the alias for the symbol
50100             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
50101             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
50102                 return container;
50103             }
50104             var exports = getExportsOfSymbol(container);
50105             var quick = exports.get(symbol.escapedName);
50106             if (quick && getSymbolIfSameReference(quick, symbol)) {
50107                 return quick;
50108             }
50109             return ts.forEachEntry(exports, function (exported) {
50110                 if (getSymbolIfSameReference(exported, symbol)) {
50111                     return exported;
50112                 }
50113             });
50114         }
50115         /**
50116          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
50117          */
50118         function getSymbolIfSameReference(s1, s2) {
50119             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
50120                 return s1;
50121             }
50122         }
50123         function getExportSymbolOfValueSymbolIfExported(symbol) {
50124             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
50125         }
50126         function symbolIsValue(symbol) {
50127             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
50128         }
50129         function findConstructorDeclaration(node) {
50130             var members = node.members;
50131             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
50132                 var member = members_3[_i];
50133                 if (member.kind === 170 /* Constructor */ && ts.nodeIsPresent(member.body)) {
50134                     return member;
50135                 }
50136             }
50137         }
50138         function createType(flags) {
50139             var result = new Type(checker, flags);
50140             typeCount++;
50141             result.id = typeCount;
50142             if (produceDiagnostics) { // Only record types from one checker
50143                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result);
50144             }
50145             return result;
50146         }
50147         function createOriginType(flags) {
50148             return new Type(checker, flags);
50149         }
50150         function createIntrinsicType(kind, intrinsicName, objectFlags) {
50151             if (objectFlags === void 0) { objectFlags = 0; }
50152             var type = createType(kind);
50153             type.intrinsicName = intrinsicName;
50154             type.objectFlags = objectFlags;
50155             return type;
50156         }
50157         function createObjectType(objectFlags, symbol) {
50158             var type = createType(524288 /* Object */);
50159             type.objectFlags = objectFlags;
50160             type.symbol = symbol;
50161             type.members = undefined;
50162             type.properties = undefined;
50163             type.callSignatures = undefined;
50164             type.constructSignatures = undefined;
50165             type.indexInfos = undefined;
50166             return type;
50167         }
50168         function createTypeofType() {
50169             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType));
50170         }
50171         function createTypeParameter(symbol) {
50172             var type = createType(262144 /* TypeParameter */);
50173             if (symbol)
50174                 type.symbol = symbol;
50175             return type;
50176         }
50177         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
50178         // @, or #. A third underscore indicates an escaped form of an identifier that started
50179         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
50180         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
50181         function isReservedMemberName(name) {
50182             return name.charCodeAt(0) === 95 /* _ */ &&
50183                 name.charCodeAt(1) === 95 /* _ */ &&
50184                 name.charCodeAt(2) !== 95 /* _ */ &&
50185                 name.charCodeAt(2) !== 64 /* at */ &&
50186                 name.charCodeAt(2) !== 35 /* hash */;
50187         }
50188         function getNamedMembers(members) {
50189             var result;
50190             members.forEach(function (symbol, id) {
50191                 if (isNamedMember(symbol, id)) {
50192                     (result || (result = [])).push(symbol);
50193                 }
50194             });
50195             return result || ts.emptyArray;
50196         }
50197         function isNamedMember(member, escapedName) {
50198             return !isReservedMemberName(escapedName) && symbolIsValue(member);
50199         }
50200         function getNamedOrIndexSignatureMembers(members) {
50201             var result = getNamedMembers(members);
50202             var index = getIndexSymbolFromSymbolTable(members);
50203             return index ? ts.concatenate(result, [index]) : result;
50204         }
50205         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos) {
50206             var resolved = type;
50207             resolved.members = members;
50208             resolved.properties = ts.emptyArray;
50209             resolved.callSignatures = callSignatures;
50210             resolved.constructSignatures = constructSignatures;
50211             resolved.indexInfos = indexInfos;
50212             // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized.
50213             if (members !== emptySymbols)
50214                 resolved.properties = getNamedMembers(members);
50215             return resolved;
50216         }
50217         function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) {
50218             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos);
50219         }
50220         function getResolvedTypeWithoutAbstractConstructSignatures(type) {
50221             if (type.constructSignatures.length === 0)
50222                 return type;
50223             if (type.objectTypeWithoutAbstractConstructSignatures)
50224                 return type.objectTypeWithoutAbstractConstructSignatures;
50225             var constructSignatures = ts.filter(type.constructSignatures, function (signature) { return !(signature.flags & 4 /* Abstract */); });
50226             if (type.constructSignatures === constructSignatures)
50227                 return type;
50228             var typeCopy = createAnonymousType(type.symbol, type.members, type.callSignatures, ts.some(constructSignatures) ? constructSignatures : ts.emptyArray, type.indexInfos);
50229             type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
50230             typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
50231             return typeCopy;
50232         }
50233         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
50234             var result;
50235             var _loop_8 = function (location) {
50236                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
50237                 if (location.locals && !isGlobalSourceFile(location)) {
50238                     if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true, location)) {
50239                         return { value: result };
50240                     }
50241                 }
50242                 switch (location.kind) {
50243                     case 303 /* SourceFile */:
50244                         if (!ts.isExternalOrCommonJsModule(location)) {
50245                             break;
50246                         }
50247                     // falls through
50248                     case 260 /* ModuleDeclaration */:
50249                         var sym = getSymbolOfNode(location);
50250                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
50251                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
50252                         // to one another anyway)
50253                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true, location)) {
50254                             return { value: result };
50255                         }
50256                         break;
50257                     case 256 /* ClassDeclaration */:
50258                     case 225 /* ClassExpression */:
50259                     case 257 /* InterfaceDeclaration */:
50260                         // Type parameters are bound into `members` lists so they can merge across declarations
50261                         // This is troublesome, since in all other respects, they behave like locals :cries:
50262                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
50263                         // lookup logic in terms of `resolveName` would be nice
50264                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
50265                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
50266                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
50267                         var table_1;
50268                         // TODO: Should this filtered table be cached in some way?
50269                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
50270                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
50271                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
50272                             }
50273                         });
50274                         if (table_1 && (result = callback(table_1, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ false, location))) {
50275                             return { value: result };
50276                         }
50277                         break;
50278                 }
50279             };
50280             for (var location = enclosingDeclaration; location; location = location.parent) {
50281                 var state_2 = _loop_8(location);
50282                 if (typeof state_2 === "object")
50283                     return state_2.value;
50284             }
50285             return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true);
50286         }
50287         function getQualifiedLeftMeaning(rightMeaning) {
50288             // If we are looking in value space, the parent meaning is value, other wise it is namespace
50289             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
50290         }
50291         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
50292             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = new ts.Map(); }
50293             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
50294                 return undefined;
50295             }
50296             var links = getSymbolLinks(symbol);
50297             var cache = (links.accessibleChainCache || (links.accessibleChainCache = new ts.Map()));
50298             // Go from enclosingDeclaration to the first scope we check, so the cache is keyed off the scope and thus shared more
50299             var firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, function (_, __, ___, node) { return node; });
50300             var key = "".concat(useOnlyExternalAliasing ? 0 : 1, "|").concat(firstRelevantLocation && getNodeId(firstRelevantLocation), "|").concat(meaning);
50301             if (cache.has(key)) {
50302                 return cache.get(key);
50303             }
50304             var id = getSymbolId(symbol);
50305             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
50306             if (!visitedSymbolTables) {
50307                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
50308             }
50309             var result = forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
50310             cache.set(key, result);
50311             return result;
50312             /**
50313              * @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)
50314              */
50315             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
50316                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
50317                     return undefined;
50318                 }
50319                 var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup);
50320                 visitedSymbolTables.pop();
50321                 return result;
50322             }
50323             function canQualifySymbol(symbolFromSymbolTable, meaning) {
50324                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
50325                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
50326                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
50327                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
50328             }
50329             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
50330                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
50331                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
50332                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
50333                     // check the symbol can be qualified, it is only then this symbol is accessible
50334                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
50335                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
50336             }
50337             function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
50338                 // If symbol is directly available by its name in the symbol table
50339                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
50340                     return [symbol];
50341                 }
50342                 // Check if symbol is any of the aliases in scope
50343                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
50344                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
50345                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
50346                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
50347                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
50348                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
50349                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
50350                         // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it
50351                         && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true)
50352                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
50353                         // See similar comment in `resolveName` for details
50354                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 274 /* ExportSpecifier */))) {
50355                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
50356                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
50357                         if (candidate) {
50358                             return candidate;
50359                         }
50360                     }
50361                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
50362                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
50363                             return [symbol];
50364                         }
50365                     }
50366                 });
50367                 // 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
50368                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
50369             }
50370             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
50371                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
50372                     return [symbolFromSymbolTable];
50373                 }
50374                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
50375                 // but only if the symbolFromSymbolTable can be qualified
50376                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
50377                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
50378                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
50379                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
50380                 }
50381             }
50382         }
50383         function needsQualification(symbol, enclosingDeclaration, meaning) {
50384             var qualify = false;
50385             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
50386                 // If symbol of this name is not available in the symbol table we are ok
50387                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
50388                 if (!symbolFromSymbolTable) {
50389                     // Continue to the next symbol table
50390                     return false;
50391                 }
50392                 // If the symbol with this name is present it should refer to the symbol
50393                 if (symbolFromSymbolTable === symbol) {
50394                     // No need to qualify
50395                     return true;
50396                 }
50397                 // Qualify if the symbol from symbol table has same meaning as expected
50398                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 274 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
50399                 if (symbolFromSymbolTable.flags & meaning) {
50400                     qualify = true;
50401                     return true;
50402                 }
50403                 // Continue to the next symbol table
50404                 return false;
50405             });
50406             return qualify;
50407         }
50408         function isPropertyOrMethodDeclarationSymbol(symbol) {
50409             if (symbol.declarations && symbol.declarations.length) {
50410                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50411                     var declaration = _a[_i];
50412                     switch (declaration.kind) {
50413                         case 166 /* PropertyDeclaration */:
50414                         case 168 /* MethodDeclaration */:
50415                         case 171 /* GetAccessor */:
50416                         case 172 /* SetAccessor */:
50417                             continue;
50418                         default:
50419                             return false;
50420                     }
50421                 }
50422                 return true;
50423             }
50424             return false;
50425         }
50426         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
50427             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
50428             return access.accessibility === 0 /* Accessible */;
50429         }
50430         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
50431             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
50432             return access.accessibility === 0 /* Accessible */;
50433         }
50434         function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
50435             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ false);
50436             return access.accessibility === 0 /* Accessible */;
50437         }
50438         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
50439             if (!ts.length(symbols))
50440                 return;
50441             var hadAccessibleChain;
50442             var earlyModuleBail = false;
50443             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
50444                 var symbol = _a[_i];
50445                 // Symbol is accessible if it by itself is accessible
50446                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
50447                 if (accessibleSymbolChain) {
50448                     hadAccessibleChain = symbol;
50449                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
50450                     if (hasAccessibleDeclarations) {
50451                         return hasAccessibleDeclarations;
50452                     }
50453                 }
50454                 if (allowModules) {
50455                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
50456                         if (shouldComputeAliasesToMakeVisible) {
50457                             earlyModuleBail = true;
50458                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
50459                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
50460                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
50461                             // all other visibility options (in order to capture the possible aliases used to reference the module)
50462                             continue;
50463                         }
50464                         // Any meaning of a module symbol is always accessible via an `import` type
50465                         return {
50466                             accessibility: 0 /* Accessible */
50467                         };
50468                     }
50469                 }
50470                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
50471                 // It could be a qualified symbol and hence verify the path
50472                 // e.g.:
50473                 // module m {
50474                 //     export class c {
50475                 //     }
50476                 // }
50477                 // const x: typeof m.c
50478                 // In the above example when we start with checking if typeof m.c symbol is accessible,
50479                 // we are going to see if c can be accessed in scope directly.
50480                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
50481                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
50482                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
50483                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
50484                 if (parentResult) {
50485                     return parentResult;
50486                 }
50487             }
50488             if (earlyModuleBail) {
50489                 return {
50490                     accessibility: 0 /* Accessible */
50491                 };
50492             }
50493             if (hadAccessibleChain) {
50494                 return {
50495                     accessibility: 1 /* NotAccessible */,
50496                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
50497                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
50498                 };
50499             }
50500         }
50501         /**
50502          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
50503          *
50504          * @param symbol a Symbol to check if accessible
50505          * @param enclosingDeclaration a Node containing reference to the symbol
50506          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
50507          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
50508          */
50509         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
50510             return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ true);
50511         }
50512         function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
50513             if (symbol && enclosingDeclaration) {
50514                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
50515                 if (result) {
50516                     return result;
50517                 }
50518                 // This could be a symbol that is not exported in the external module
50519                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
50520                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
50521                 if (symbolExternalModule) {
50522                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
50523                     if (symbolExternalModule !== enclosingExternalModule) {
50524                         // name from different external module that is not visible
50525                         return {
50526                             accessibility: 2 /* CannotBeNamed */,
50527                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
50528                             errorModuleName: symbolToString(symbolExternalModule),
50529                             errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined,
50530                         };
50531                     }
50532                 }
50533                 // Just a local name that is not accessible
50534                 return {
50535                     accessibility: 1 /* NotAccessible */,
50536                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
50537                 };
50538             }
50539             return { accessibility: 0 /* Accessible */ };
50540         }
50541         function getExternalModuleContainer(declaration) {
50542             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
50543             return node && getSymbolOfNode(node);
50544         }
50545         function hasExternalModuleSymbol(declaration) {
50546             return ts.isAmbientModule(declaration) || (declaration.kind === 303 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
50547         }
50548         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
50549             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 303 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
50550         }
50551         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
50552             var aliasesToMakeVisible;
50553             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 79 /* Identifier */; }), getIsDeclarationVisible)) {
50554                 return undefined;
50555             }
50556             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
50557             function getIsDeclarationVisible(declaration) {
50558                 var _a, _b;
50559                 if (!isDeclarationVisible(declaration)) {
50560                     // Mark the unexported alias as visible if its parent is visible
50561                     // because these kind of aliases can be used to name types in declaration file
50562                     var anyImportSyntax = getAnyImportSyntax(declaration);
50563                     if (anyImportSyntax &&
50564                         !ts.hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
50565                         isDeclarationVisible(anyImportSyntax.parent)) {
50566                         return addVisibleAlias(declaration, anyImportSyntax);
50567                     }
50568                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
50569                         !ts.hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
50570                         isDeclarationVisible(declaration.parent.parent.parent)) {
50571                         return addVisibleAlias(declaration, declaration.parent.parent);
50572                     }
50573                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
50574                         && !ts.hasSyntacticModifier(declaration, 1 /* Export */)
50575                         && isDeclarationVisible(declaration.parent)) {
50576                         return addVisibleAlias(declaration, declaration);
50577                     }
50578                     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
50579                         && ts.isVariableDeclaration(declaration.parent.parent)
50580                         && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent)
50581                         && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */)
50582                         && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file)
50583                         && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
50584                         return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
50585                     }
50586                     // Declaration is not visible
50587                     return false;
50588                 }
50589                 return true;
50590             }
50591             function addVisibleAlias(declaration, aliasingStatement) {
50592                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
50593                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
50594                 // since we will do the emitting later in trackSymbol.
50595                 if (shouldComputeAliasToMakeVisible) {
50596                     getNodeLinks(declaration).isVisible = true;
50597                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
50598                 }
50599                 return true;
50600             }
50601         }
50602         function isEntityNameVisible(entityName, enclosingDeclaration) {
50603             // get symbol of the first identifier of the entityName
50604             var meaning;
50605             if (entityName.parent.kind === 180 /* TypeQuery */ ||
50606                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
50607                 entityName.parent.kind === 161 /* ComputedPropertyName */) {
50608                 // Typeof value
50609                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
50610             }
50611             else if (entityName.kind === 160 /* QualifiedName */ || entityName.kind === 205 /* PropertyAccessExpression */ ||
50612                 entityName.parent.kind === 264 /* ImportEqualsDeclaration */) {
50613                 // Left identifier from type reference or TypeAlias
50614                 // Entity name of the import declaration
50615                 meaning = 1920 /* Namespace */;
50616             }
50617             else {
50618                 // Type Reference or TypeAlias entity = Identifier
50619                 meaning = 788968 /* Type */;
50620             }
50621             var firstIdentifier = ts.getFirstIdentifier(entityName);
50622             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
50623             if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
50624                 return { accessibility: 0 /* Accessible */ };
50625             }
50626             // Verify if the symbol is accessible
50627             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
50628                 accessibility: 1 /* NotAccessible */,
50629                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
50630                 errorNode: firstIdentifier
50631             };
50632         }
50633         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
50634             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
50635             var nodeFlags = 70221824 /* IgnoreErrors */;
50636             if (flags & 2 /* UseOnlyExternalAliasing */) {
50637                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
50638             }
50639             if (flags & 1 /* WriteTypeParametersOrArguments */) {
50640                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
50641             }
50642             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
50643                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
50644             }
50645             if (flags & 16 /* DoNotIncludeSymbolChain */) {
50646                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
50647             }
50648             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
50649             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
50650             function symbolToStringWorker(writer) {
50651                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
50652                 // add neverAsciiEscape for GH#39027
50653                 var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 303 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true });
50654                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
50655                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
50656                 return writer;
50657             }
50658         }
50659         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
50660             if (flags === void 0) { flags = 0 /* None */; }
50661             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
50662             function signatureToStringWorker(writer) {
50663                 var sigOutput;
50664                 if (flags & 262144 /* WriteArrowStyleSignature */) {
50665                     sigOutput = kind === 1 /* Construct */ ? 179 /* ConstructorType */ : 178 /* FunctionType */;
50666                 }
50667                 else {
50668                     sigOutput = kind === 1 /* Construct */ ? 174 /* ConstructSignature */ : 173 /* CallSignature */;
50669                 }
50670                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
50671                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
50672                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
50673                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
50674                 return writer;
50675             }
50676         }
50677         function typeToString(type, enclosingDeclaration, flags, writer) {
50678             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
50679             if (writer === void 0) { writer = ts.createTextWriter(""); }
50680             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
50681             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
50682             if (typeNode === undefined)
50683                 return ts.Debug.fail("should always get typenode");
50684             // The unresolved type gets a synthesized comment on `any` to hint to users that it's not a plain `any`.
50685             // Otherwise, we always strip comments out.
50686             var options = { removeComments: type !== unresolvedType };
50687             var printer = ts.createPrinter(options);
50688             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
50689             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
50690             var result = writer.getText();
50691             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
50692             if (maxLength && result && result.length >= maxLength) {
50693                 return result.substr(0, maxLength - "...".length) + "...";
50694             }
50695             return result;
50696         }
50697         function getTypeNamesForErrorDisplay(left, right) {
50698             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
50699             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
50700             if (leftStr === rightStr) {
50701                 leftStr = getTypeNameForErrorDisplay(left);
50702                 rightStr = getTypeNameForErrorDisplay(right);
50703             }
50704             return [leftStr, rightStr];
50705         }
50706         function getTypeNameForErrorDisplay(type) {
50707             return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
50708         }
50709         function symbolValueDeclarationIsContextSensitive(symbol) {
50710             return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
50711         }
50712         function toNodeBuilderFlags(flags) {
50713             if (flags === void 0) { flags = 0 /* None */; }
50714             return flags & 814775659 /* NodeBuilderFlagsMask */;
50715         }
50716         function isClassInstanceSide(type) {
50717             return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */)));
50718         }
50719         function createNodeBuilder() {
50720             return {
50721                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
50722                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
50723                 },
50724                 indexInfoToIndexSignatureDeclaration: function (indexInfo, enclosingDeclaration, flags, tracker) {
50725                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, /*typeNode*/ undefined); });
50726                 },
50727                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
50728                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
50729                 },
50730                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
50731                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
50732                 },
50733                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
50734                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
50735                 },
50736                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
50737                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
50738                 },
50739                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
50740                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
50741                 },
50742                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
50743                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
50744                 },
50745                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
50746                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
50747                 },
50748             };
50749             function withContext(enclosingDeclaration, flags, tracker, cb) {
50750                 var _a, _b;
50751                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
50752                 var context = {
50753                     enclosingDeclaration: enclosingDeclaration,
50754                     flags: flags || 0 /* None */,
50755                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
50756                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: function () { return false; }, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
50757                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
50758                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
50759                             getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache),
50760                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
50761                             redirectTargetsMap: host.redirectTargetsMap,
50762                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
50763                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
50764                             fileExists: function (fileName) { return host.fileExists(fileName); },
50765                             getFileIncludeReasons: function () { return host.getFileIncludeReasons(); },
50766                             readFile: host.readFile ? (function (fileName) { return host.readFile(fileName); }) : undefined,
50767                         } : undefined },
50768                     encounteredError: false,
50769                     reportedDiagnostic: false,
50770                     visitedTypes: undefined,
50771                     symbolDepth: undefined,
50772                     inferTypeParameters: undefined,
50773                     approximateLength: 0
50774                 };
50775                 context.tracker = wrapSymbolTrackerToReportForContext(context, context.tracker);
50776                 var resultingNode = cb(context);
50777                 if (context.truncating && context.flags & 1 /* NoTruncation */) {
50778                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportTruncationError) === null || _b === void 0 ? void 0 : _b.call(_a);
50779                 }
50780                 return context.encounteredError ? undefined : resultingNode;
50781             }
50782             function wrapSymbolTrackerToReportForContext(context, tracker) {
50783                 var oldTrackSymbol = tracker.trackSymbol;
50784                 return __assign(__assign({}, tracker), { reportCyclicStructureError: wrapReportedDiagnostic(tracker.reportCyclicStructureError), reportInaccessibleThisError: wrapReportedDiagnostic(tracker.reportInaccessibleThisError), reportInaccessibleUniqueSymbolError: wrapReportedDiagnostic(tracker.reportInaccessibleUniqueSymbolError), reportLikelyUnsafeImportRequiredError: wrapReportedDiagnostic(tracker.reportLikelyUnsafeImportRequiredError), reportNonlocalAugmentation: wrapReportedDiagnostic(tracker.reportNonlocalAugmentation), reportPrivateInBaseOfClassExpression: wrapReportedDiagnostic(tracker.reportPrivateInBaseOfClassExpression), reportNonSerializableProperty: wrapReportedDiagnostic(tracker.reportNonSerializableProperty), trackSymbol: oldTrackSymbol && (function () {
50785                         var args = [];
50786                         for (var _i = 0; _i < arguments.length; _i++) {
50787                             args[_i] = arguments[_i];
50788                         }
50789                         var result = oldTrackSymbol.apply(void 0, args);
50790                         if (result) {
50791                             context.reportedDiagnostic = true;
50792                         }
50793                         return result;
50794                     }) });
50795                 function wrapReportedDiagnostic(method) {
50796                     if (!method) {
50797                         return method;
50798                     }
50799                     return (function () {
50800                         var args = [];
50801                         for (var _i = 0; _i < arguments.length; _i++) {
50802                             args[_i] = arguments[_i];
50803                         }
50804                         context.reportedDiagnostic = true;
50805                         return method.apply(void 0, args);
50806                     });
50807                 }
50808             }
50809             function checkTruncationLength(context) {
50810                 if (context.truncating)
50811                     return context.truncating;
50812                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
50813             }
50814             function typeToTypeNodeHelper(type, context) {
50815                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
50816                     cancellationToken.throwIfCancellationRequested();
50817                 }
50818                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
50819                 context.flags &= ~8388608 /* InTypeAlias */;
50820                 if (!type) {
50821                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
50822                         context.encounteredError = true;
50823                         return undefined; // TODO: GH#18217
50824                     }
50825                     context.approximateLength += 3;
50826                     return ts.factory.createKeywordTypeNode(130 /* AnyKeyword */);
50827                 }
50828                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
50829                     type = getReducedType(type);
50830                 }
50831                 if (type.flags & 1 /* Any */) {
50832                     if (type.aliasSymbol) {
50833                         return ts.factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context));
50834                     }
50835                     if (type === unresolvedType) {
50836                         return ts.addSyntheticLeadingComment(ts.factory.createKeywordTypeNode(130 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "unresolved");
50837                     }
50838                     context.approximateLength += 3;
50839                     return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 138 /* IntrinsicKeyword */ : 130 /* AnyKeyword */);
50840                 }
50841                 if (type.flags & 2 /* Unknown */) {
50842                     return ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */);
50843                 }
50844                 if (type.flags & 4 /* String */) {
50845                     context.approximateLength += 6;
50846                     return ts.factory.createKeywordTypeNode(149 /* StringKeyword */);
50847                 }
50848                 if (type.flags & 8 /* Number */) {
50849                     context.approximateLength += 6;
50850                     return ts.factory.createKeywordTypeNode(146 /* NumberKeyword */);
50851                 }
50852                 if (type.flags & 64 /* BigInt */) {
50853                     context.approximateLength += 6;
50854                     return ts.factory.createKeywordTypeNode(157 /* BigIntKeyword */);
50855                 }
50856                 if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) {
50857                     context.approximateLength += 7;
50858                     return ts.factory.createKeywordTypeNode(133 /* BooleanKeyword */);
50859                 }
50860                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
50861                     var parentSymbol = getParentOfSymbol(type.symbol);
50862                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
50863                     if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
50864                         return parentName;
50865                     }
50866                     var memberName = ts.symbolName(type.symbol);
50867                     if (ts.isIdentifierText(memberName, 0 /* ES3 */)) {
50868                         return appendReferenceToType(parentName, ts.factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined));
50869                     }
50870                     if (ts.isImportTypeNode(parentName)) {
50871                         parentName.isTypeOf = true; // mutably update, node is freshly manufactured anyhow
50872                         return ts.factory.createIndexedAccessTypeNode(parentName, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
50873                     }
50874                     else if (ts.isTypeReferenceNode(parentName)) {
50875                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeQueryNode(parentName.typeName), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
50876                     }
50877                     else {
50878                         return ts.Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
50879                     }
50880                 }
50881                 if (type.flags & 1056 /* EnumLike */) {
50882                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
50883                 }
50884                 if (type.flags & 128 /* StringLiteral */) {
50885                     context.approximateLength += (type.value.length + 2);
50886                     return ts.factory.createLiteralTypeNode(ts.setEmitFlags(ts.factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
50887                 }
50888                 if (type.flags & 256 /* NumberLiteral */) {
50889                     var value = type.value;
50890                     context.approximateLength += ("" + value).length;
50891                     return ts.factory.createLiteralTypeNode(value < 0 ? ts.factory.createPrefixUnaryExpression(40 /* MinusToken */, ts.factory.createNumericLiteral(-value)) : ts.factory.createNumericLiteral(value));
50892                 }
50893                 if (type.flags & 2048 /* BigIntLiteral */) {
50894                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
50895                     return ts.factory.createLiteralTypeNode((ts.factory.createBigIntLiteral(type.value)));
50896                 }
50897                 if (type.flags & 512 /* BooleanLiteral */) {
50898                     context.approximateLength += type.intrinsicName.length;
50899                     return ts.factory.createLiteralTypeNode(type.intrinsicName === "true" ? ts.factory.createTrue() : ts.factory.createFalse());
50900                 }
50901                 if (type.flags & 8192 /* UniqueESSymbol */) {
50902                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
50903                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
50904                             context.approximateLength += 6;
50905                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
50906                         }
50907                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
50908                             context.tracker.reportInaccessibleUniqueSymbolError();
50909                         }
50910                     }
50911                     context.approximateLength += 13;
50912                     return ts.factory.createTypeOperatorNode(153 /* UniqueKeyword */, ts.factory.createKeywordTypeNode(150 /* SymbolKeyword */));
50913                 }
50914                 if (type.flags & 16384 /* Void */) {
50915                     context.approximateLength += 4;
50916                     return ts.factory.createKeywordTypeNode(114 /* VoidKeyword */);
50917                 }
50918                 if (type.flags & 32768 /* Undefined */) {
50919                     context.approximateLength += 9;
50920                     return ts.factory.createKeywordTypeNode(152 /* UndefinedKeyword */);
50921                 }
50922                 if (type.flags & 65536 /* Null */) {
50923                     context.approximateLength += 4;
50924                     return ts.factory.createLiteralTypeNode(ts.factory.createNull());
50925                 }
50926                 if (type.flags & 131072 /* Never */) {
50927                     context.approximateLength += 5;
50928                     return ts.factory.createKeywordTypeNode(143 /* NeverKeyword */);
50929                 }
50930                 if (type.flags & 4096 /* ESSymbol */) {
50931                     context.approximateLength += 6;
50932                     return ts.factory.createKeywordTypeNode(150 /* SymbolKeyword */);
50933                 }
50934                 if (type.flags & 67108864 /* NonPrimitive */) {
50935                     context.approximateLength += 6;
50936                     return ts.factory.createKeywordTypeNode(147 /* ObjectKeyword */);
50937                 }
50938                 if (isThisTypeParameter(type)) {
50939                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
50940                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
50941                             context.encounteredError = true;
50942                         }
50943                         if (context.tracker.reportInaccessibleThisError) {
50944                             context.tracker.reportInaccessibleThisError();
50945                         }
50946                     }
50947                     context.approximateLength += 4;
50948                     return ts.factory.createThisTypeNode();
50949                 }
50950                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
50951                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
50952                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
50953                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes);
50954                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
50955                 }
50956                 var objectFlags = ts.getObjectFlags(type);
50957                 if (objectFlags & 4 /* Reference */) {
50958                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
50959                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
50960                 }
50961                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
50962                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
50963                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
50964                         return ts.factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
50965                     }
50966                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
50967                         type.flags & 262144 /* TypeParameter */ &&
50968                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
50969                         var name = typeParameterToName(type, context);
50970                         context.approximateLength += ts.idText(name).length;
50971                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
50972                     }
50973                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
50974                     return type.symbol
50975                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
50976                         : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
50977                 }
50978                 if (type.flags & 1048576 /* Union */ && type.origin) {
50979                     type = type.origin;
50980                 }
50981                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
50982                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
50983                     if (ts.length(types) === 1) {
50984                         return typeToTypeNodeHelper(types[0], context);
50985                     }
50986                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
50987                     if (typeNodes && typeNodes.length > 0) {
50988                         return type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
50989                     }
50990                     else {
50991                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
50992                             context.encounteredError = true;
50993                         }
50994                         return undefined; // TODO: GH#18217
50995                     }
50996                 }
50997                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
50998                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
50999                     // The type is an object literal type.
51000                     return createAnonymousTypeNode(type);
51001                 }
51002                 if (type.flags & 4194304 /* Index */) {
51003                     var indexedType = type.type;
51004                     context.approximateLength += 6;
51005                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
51006                     return ts.factory.createTypeOperatorNode(140 /* KeyOfKeyword */, indexTypeNode);
51007                 }
51008                 if (type.flags & 134217728 /* TemplateLiteral */) {
51009                     var texts_1 = type.texts;
51010                     var types_1 = type.types;
51011                     var templateHead = ts.factory.createTemplateHead(texts_1[0]);
51012                     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])); }));
51013                     context.approximateLength += 2;
51014                     return ts.factory.createTemplateLiteralType(templateHead, templateSpans);
51015                 }
51016                 if (type.flags & 268435456 /* StringMapping */) {
51017                     var typeNode = typeToTypeNodeHelper(type.type, context);
51018                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
51019                 }
51020                 if (type.flags & 8388608 /* IndexedAccess */) {
51021                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
51022                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
51023                     context.approximateLength += 2;
51024                     return ts.factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
51025                 }
51026                 if (type.flags & 16777216 /* Conditional */) {
51027                     return visitAndTransformType(type, function (type) { return conditionalTypeToTypeNode(type); });
51028                 }
51029                 if (type.flags & 33554432 /* Substitution */) {
51030                     return typeToTypeNodeHelper(type.baseType, context);
51031                 }
51032                 return ts.Debug.fail("Should be unreachable.");
51033                 function conditionalTypeToTypeNode(type) {
51034                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
51035                     var saveInferTypeParameters = context.inferTypeParameters;
51036                     context.inferTypeParameters = type.root.inferTypeParameters;
51037                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
51038                     context.inferTypeParameters = saveInferTypeParameters;
51039                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
51040                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
51041                     context.approximateLength += 15;
51042                     return ts.factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
51043                 }
51044                 function typeToTypeNodeOrCircularityElision(type) {
51045                     var _a, _b, _c;
51046                     if (type.flags & 1048576 /* Union */) {
51047                         if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(getTypeId(type))) {
51048                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
51049                                 context.encounteredError = true;
51050                                 (_c = (_b = context.tracker) === null || _b === void 0 ? void 0 : _b.reportCyclicStructureError) === null || _c === void 0 ? void 0 : _c.call(_b);
51051                             }
51052                             return createElidedInformationPlaceholder(context);
51053                         }
51054                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
51055                     }
51056                     return typeToTypeNodeHelper(type, context);
51057                 }
51058                 function createMappedTypeNodeFromType(type) {
51059                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
51060                     var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined;
51061                     var questionToken = type.declaration.questionToken ? ts.factory.createToken(type.declaration.questionToken.kind) : undefined;
51062                     var appropriateConstraintTypeNode;
51063                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
51064                         // We have a { [P in keyof T]: X }
51065                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
51066                         appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(140 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
51067                     }
51068                     else {
51069                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
51070                     }
51071                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
51072                     var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined;
51073                     var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context);
51074                     var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined);
51075                     context.approximateLength += 10;
51076                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
51077                 }
51078                 function createAnonymousTypeNode(type) {
51079                     var _a;
51080                     var typeId = type.id;
51081                     var symbol = type.symbol;
51082                     if (symbol) {
51083                         var isInstanceType = isClassInstanceSide(type) ? 788968 /* Type */ : 111551 /* Value */;
51084                         if (isJSConstructor(symbol.valueDeclaration)) {
51085                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
51086                             return symbolToTypeNode(symbol, context, isInstanceType);
51087                         }
51088                         // Always use 'typeof T' for type of class, enum, and module objects
51089                         else if (symbol.flags & 32 /* Class */
51090                             && !getBaseTypeVariableOfClass(symbol)
51091                             && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 225 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
51092                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
51093                             shouldWriteTypeOfFunctionSymbol()) {
51094                             return symbolToTypeNode(symbol, context, isInstanceType);
51095                         }
51096                         else if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId)) {
51097                             // If type is an anonymous type literal in a type alias declaration, use type alias name
51098                             var typeAlias = getTypeAliasForTypeLiteral(type);
51099                             if (typeAlias) {
51100                                 // The specified symbol flags need to be reinterpreted as type flags
51101                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
51102                             }
51103                             else {
51104                                 return createElidedInformationPlaceholder(context);
51105                             }
51106                         }
51107                         else {
51108                             return visitAndTransformType(type, createTypeNodeFromObjectType);
51109                         }
51110                     }
51111                     else {
51112                         // Anonymous types without a symbol are never circular.
51113                         return createTypeNodeFromObjectType(type);
51114                     }
51115                     function shouldWriteTypeOfFunctionSymbol() {
51116                         var _a;
51117                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
51118                             ts.some(symbol.declarations, function (declaration) { return ts.isStatic(declaration); });
51119                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
51120                             (symbol.parent || // is exported function symbol
51121                                 ts.forEach(symbol.declarations, function (declaration) {
51122                                     return declaration.parent.kind === 303 /* SourceFile */ || declaration.parent.kind === 261 /* ModuleBlock */;
51123                                 }));
51124                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
51125                             // typeof is allowed only for static/non local functions
51126                             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
51127                                 (!(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
51128                         }
51129                     }
51130                 }
51131                 function visitAndTransformType(type, transform) {
51132                     var _a, _b;
51133                     var typeId = type.id;
51134                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
51135                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
51136                         type.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type.root.node) :
51137                             type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
51138                                 undefined;
51139                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
51140                     // of types allows us to catch circular references to instantiations of the same anonymous type
51141                     if (!context.visitedTypes) {
51142                         context.visitedTypes = new ts.Set();
51143                     }
51144                     if (id && !context.symbolDepth) {
51145                         context.symbolDepth = new ts.Map();
51146                     }
51147                     var links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration);
51148                     var key = "".concat(getTypeId(type), "|").concat(context.flags);
51149                     if (links) {
51150                         links.serializedTypes || (links.serializedTypes = new ts.Map());
51151                     }
51152                     var cachedResult = (_a = links === null || links === void 0 ? void 0 : links.serializedTypes) === null || _a === void 0 ? void 0 : _a.get(key);
51153                     if (cachedResult) {
51154                         if (cachedResult.truncating) {
51155                             context.truncating = true;
51156                         }
51157                         context.approximateLength += cachedResult.addedLength;
51158                         return deepCloneOrReuseNode(cachedResult);
51159                     }
51160                     var depth;
51161                     if (id) {
51162                         depth = context.symbolDepth.get(id) || 0;
51163                         if (depth > 10) {
51164                             return createElidedInformationPlaceholder(context);
51165                         }
51166                         context.symbolDepth.set(id, depth + 1);
51167                     }
51168                     context.visitedTypes.add(typeId);
51169                     var startLength = context.approximateLength;
51170                     var result = transform(type);
51171                     var addedLength = context.approximateLength - startLength;
51172                     if (!context.reportedDiagnostic && !context.encounteredError) {
51173                         if (context.truncating) {
51174                             result.truncating = true;
51175                         }
51176                         result.addedLength = addedLength;
51177                         (_b = links === null || links === void 0 ? void 0 : links.serializedTypes) === null || _b === void 0 ? void 0 : _b.set(key, result);
51178                     }
51179                     context.visitedTypes.delete(typeId);
51180                     if (id) {
51181                         context.symbolDepth.set(id, depth);
51182                     }
51183                     return result;
51184                     function deepCloneOrReuseNode(node) {
51185                         if (!ts.nodeIsSynthesized(node) && ts.getParseTreeNode(node) === node) {
51186                             return node;
51187                         }
51188                         return ts.setTextRange(ts.factory.cloneNode(ts.visitEachChild(node, deepCloneOrReuseNode, ts.nullTransformationContext)), node);
51189                     }
51190                 }
51191                 function createTypeNodeFromObjectType(type) {
51192                     if (isGenericMappedType(type) || type.containsError) {
51193                         return createMappedTypeNodeFromType(type);
51194                     }
51195                     var resolved = resolveStructuredTypeMembers(type);
51196                     if (!resolved.properties.length && !resolved.indexInfos.length) {
51197                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
51198                             context.approximateLength += 2;
51199                             return ts.setEmitFlags(ts.factory.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
51200                         }
51201                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
51202                             var signature = resolved.callSignatures[0];
51203                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 178 /* FunctionType */, context);
51204                             return signatureNode;
51205                         }
51206                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
51207                             var signature = resolved.constructSignatures[0];
51208                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 179 /* ConstructorType */, context);
51209                             return signatureNode;
51210                         }
51211                     }
51212                     var abstractSignatures = ts.filter(resolved.constructSignatures, function (signature) { return !!(signature.flags & 4 /* Abstract */); });
51213                     if (ts.some(abstractSignatures)) {
51214                         var types = ts.map(abstractSignatures, getOrCreateTypeFromSignature);
51215                         // count the number of type elements excluding abstract constructors
51216                         var typeElementCount = resolved.callSignatures.length +
51217                             (resolved.constructSignatures.length - abstractSignatures.length) +
51218                             resolved.indexInfos.length +
51219                             // exclude `prototype` when writing a class expression as a type literal, as per
51220                             // the logic in `createTypeNodesFromResolvedType`.
51221                             (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ?
51222                                 ts.countWhere(resolved.properties, function (p) { return !(p.flags & 4194304 /* Prototype */); }) :
51223                                 ts.length(resolved.properties));
51224                         // don't include an empty object literal if there were no other static-side
51225                         // properties to write, i.e. `abstract class C { }` becomes `abstract new () => {}`
51226                         // and not `(abstract new () => {}) & {}`
51227                         if (typeElementCount) {
51228                             // create a copy of the object type without any abstract construct signatures.
51229                             types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
51230                         }
51231                         return typeToTypeNodeHelper(getIntersectionType(types), context);
51232                     }
51233                     var savedFlags = context.flags;
51234                     context.flags |= 4194304 /* InObjectTypeLiteral */;
51235                     var members = createTypeNodesFromResolvedType(resolved);
51236                     context.flags = savedFlags;
51237                     var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
51238                     context.approximateLength += 2;
51239                     ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
51240                     return typeLiteralNode;
51241                 }
51242                 function typeReferenceToTypeNode(type) {
51243                     var typeArguments = getTypeArguments(type);
51244                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
51245                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
51246                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
51247                             return ts.factory.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
51248                         }
51249                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
51250                         var arrayType = ts.factory.createArrayTypeNode(elementType);
51251                         return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(144 /* ReadonlyKeyword */, arrayType);
51252                     }
51253                     else if (type.target.objectFlags & 8 /* Tuple */) {
51254                         typeArguments = ts.sameMap(typeArguments, function (t, i) { return removeMissingType(t, !!(type.target.elementFlags[i] & 2 /* Optional */)); });
51255                         if (typeArguments.length > 0) {
51256                             var arity = getTypeReferenceArity(type);
51257                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
51258                             if (tupleConstituentNodes) {
51259                                 if (type.target.labeledElementDeclarations) {
51260                                     for (var i = 0; i < tupleConstituentNodes.length; i++) {
51261                                         var flags = type.target.elementFlags[i];
51262                                         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]) :
51263                                             tupleConstituentNodes[i]);
51264                                     }
51265                                 }
51266                                 else {
51267                                     for (var i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++) {
51268                                         var flags = type.target.elementFlags[i];
51269                                         tupleConstituentNodes[i] =
51270                                             flags & 12 /* Variable */ ? ts.factory.createRestTypeNode(flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) :
51271                                                 flags & 2 /* Optional */ ? ts.factory.createOptionalTypeNode(tupleConstituentNodes[i]) :
51272                                                     tupleConstituentNodes[i];
51273                                     }
51274                                 }
51275                                 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
51276                                 return type.target.readonly ? ts.factory.createTypeOperatorNode(144 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
51277                             }
51278                         }
51279                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
51280                             var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* SingleLine */);
51281                             return type.target.readonly ? ts.factory.createTypeOperatorNode(144 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
51282                         }
51283                         context.encounteredError = true;
51284                         return undefined; // TODO: GH#18217
51285                     }
51286                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
51287                         type.symbol.valueDeclaration &&
51288                         ts.isClassLike(type.symbol.valueDeclaration) &&
51289                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
51290                         return createAnonymousTypeNode(type);
51291                     }
51292                     else {
51293                         var outerTypeParameters = type.target.outerTypeParameters;
51294                         var i = 0;
51295                         var resultType = void 0;
51296                         if (outerTypeParameters) {
51297                             var length_2 = outerTypeParameters.length;
51298                             while (i < length_2) {
51299                                 // Find group of type arguments for type parameters with the same declaring container.
51300                                 var start = i;
51301                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
51302                                 do {
51303                                     i++;
51304                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
51305                                 // When type parameters are their own type arguments for the whole group (i.e. we have
51306                                 // the default outer type arguments), we don't show the group.
51307                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
51308                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
51309                                     var flags_3 = context.flags;
51310                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
51311                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
51312                                     context.flags = flags_3;
51313                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
51314                                 }
51315                             }
51316                         }
51317                         var typeArgumentNodes = void 0;
51318                         if (typeArguments.length > 0) {
51319                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
51320                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
51321                         }
51322                         var flags = context.flags;
51323                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
51324                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
51325                         context.flags = flags;
51326                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
51327                     }
51328                 }
51329                 function appendReferenceToType(root, ref) {
51330                     if (ts.isImportTypeNode(root)) {
51331                         // first shift type arguments
51332                         var typeArguments = root.typeArguments;
51333                         var qualifier = root.qualifier;
51334                         if (qualifier) {
51335                             if (ts.isIdentifier(qualifier)) {
51336                                 qualifier = ts.factory.updateIdentifier(qualifier, typeArguments);
51337                             }
51338                             else {
51339                                 qualifier = ts.factory.updateQualifiedName(qualifier, qualifier.left, ts.factory.updateIdentifier(qualifier.right, typeArguments));
51340                             }
51341                         }
51342                         typeArguments = ref.typeArguments;
51343                         // then move qualifiers
51344                         var ids = getAccessStack(ref);
51345                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
51346                             var id = ids_1[_i];
51347                             qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id;
51348                         }
51349                         return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf);
51350                     }
51351                     else {
51352                         // first shift type arguments
51353                         var typeArguments = root.typeArguments;
51354                         var typeName = root.typeName;
51355                         if (ts.isIdentifier(typeName)) {
51356                             typeName = ts.factory.updateIdentifier(typeName, typeArguments);
51357                         }
51358                         else {
51359                             typeName = ts.factory.updateQualifiedName(typeName, typeName.left, ts.factory.updateIdentifier(typeName.right, typeArguments));
51360                         }
51361                         typeArguments = ref.typeArguments;
51362                         // then move qualifiers
51363                         var ids = getAccessStack(ref);
51364                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
51365                             var id = ids_2[_a];
51366                             typeName = ts.factory.createQualifiedName(typeName, id);
51367                         }
51368                         return ts.factory.updateTypeReferenceNode(root, typeName, typeArguments);
51369                     }
51370                 }
51371                 function getAccessStack(ref) {
51372                     var state = ref.typeName;
51373                     var ids = [];
51374                     while (!ts.isIdentifier(state)) {
51375                         ids.unshift(state.right);
51376                         state = state.left;
51377                     }
51378                     ids.unshift(state);
51379                     return ids;
51380                 }
51381                 function createTypeNodesFromResolvedType(resolvedType) {
51382                     if (checkTruncationLength(context)) {
51383                         return [ts.factory.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined)];
51384                     }
51385                     var typeElements = [];
51386                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
51387                         var signature = _a[_i];
51388                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 173 /* CallSignature */, context));
51389                     }
51390                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
51391                         var signature = _c[_b];
51392                         if (signature.flags & 4 /* Abstract */)
51393                             continue;
51394                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 174 /* ConstructSignature */, context));
51395                     }
51396                     for (var _d = 0, _e = resolvedType.indexInfos; _d < _e.length; _d++) {
51397                         var info = _e[_d];
51398                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(info, context, resolvedType.objectFlags & 1024 /* ReverseMapped */ ? createElidedInformationPlaceholder(context) : undefined));
51399                     }
51400                     var properties = resolvedType.properties;
51401                     if (!properties) {
51402                         return typeElements;
51403                     }
51404                     var i = 0;
51405                     for (var _f = 0, properties_1 = properties; _f < properties_1.length; _f++) {
51406                         var propertySymbol = properties_1[_f];
51407                         i++;
51408                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
51409                             if (propertySymbol.flags & 4194304 /* Prototype */) {
51410                                 continue;
51411                             }
51412                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
51413                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
51414                             }
51415                         }
51416                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
51417                             typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... ".concat(properties.length - i, " more ..."), /*questionToken*/ undefined, /*type*/ undefined));
51418                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
51419                             break;
51420                         }
51421                         addPropertyToElementList(propertySymbol, context, typeElements);
51422                     }
51423                     return typeElements.length ? typeElements : undefined;
51424                 }
51425             }
51426             function createElidedInformationPlaceholder(context) {
51427                 context.approximateLength += 3;
51428                 if (!(context.flags & 1 /* NoTruncation */)) {
51429                     return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined);
51430                 }
51431                 return ts.factory.createKeywordTypeNode(130 /* AnyKeyword */);
51432             }
51433             function shouldUsePlaceholderForProperty(propertySymbol, context) {
51434                 var _a;
51435                 // Use placeholders for reverse mapped types we've either already descended into, or which
51436                 // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to
51437                 // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`.
51438                 // Since anonymous types usually come from expressions, this allows us to preserve the output
51439                 // for deep mappings which likely come from expressions, while truncating those parts which
51440                 // come from mappings over library functions.
51441                 return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */)
51442                     && (ts.contains(context.reverseMappedStack, propertySymbol)
51443                         || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0])
51444                             && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */)));
51445             }
51446             function addPropertyToElementList(propertySymbol, context, typeElements) {
51447                 var _a, _b;
51448                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
51449                 var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ?
51450                     anyType : getNonMissingTypeOfSymbol(propertySymbol);
51451                 var saveEnclosingDeclaration = context.enclosingDeclaration;
51452                 context.enclosingDeclaration = undefined;
51453                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) {
51454                     if (propertySymbol.declarations) {
51455                         var decl = ts.first(propertySymbol.declarations);
51456                         if (hasLateBindableName(decl)) {
51457                             if (ts.isBinaryExpression(decl)) {
51458                                 var name = ts.getNameOfDeclaration(decl);
51459                                 if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
51460                                     trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
51461                                 }
51462                             }
51463                             else {
51464                                 trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
51465                             }
51466                         }
51467                     }
51468                     else if ((_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonSerializableProperty) {
51469                         context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol));
51470                     }
51471                 }
51472                 context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_b = propertySymbol.declarations) === null || _b === void 0 ? void 0 : _b[0]) || saveEnclosingDeclaration;
51473                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
51474                 context.enclosingDeclaration = saveEnclosingDeclaration;
51475                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
51476                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
51477                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
51478                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
51479                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
51480                         var signature = signatures_1[_i];
51481                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 167 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
51482                         typeElements.push(preserveCommentsOn(methodDeclaration));
51483                     }
51484                 }
51485                 else {
51486                     var propertyTypeNode = void 0;
51487                     if (shouldUsePlaceholderForProperty(propertySymbol, context)) {
51488                         propertyTypeNode = createElidedInformationPlaceholder(context);
51489                     }
51490                     else {
51491                         if (propertyIsReverseMapped) {
51492                             context.reverseMappedStack || (context.reverseMappedStack = []);
51493                             context.reverseMappedStack.push(propertySymbol);
51494                         }
51495                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(130 /* AnyKeyword */);
51496                         if (propertyIsReverseMapped) {
51497                             context.reverseMappedStack.pop();
51498                         }
51499                     }
51500                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(144 /* ReadonlyKeyword */)] : undefined;
51501                     if (modifiers) {
51502                         context.approximateLength += 9;
51503                     }
51504                     var propertySignature = ts.factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode);
51505                     typeElements.push(preserveCommentsOn(propertySignature));
51506                 }
51507                 function preserveCommentsOn(node) {
51508                     var _a;
51509                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 345 /* JSDocPropertyTag */; })) {
51510                         var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 345 /* JSDocPropertyTag */; });
51511                         var commentText = ts.getTextOfJSDocComment(d.comment);
51512                         if (commentText) {
51513                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
51514                         }
51515                     }
51516                     else if (propertySymbol.valueDeclaration) {
51517                         // Copy comments to node for declaration emit
51518                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
51519                     }
51520                     return node;
51521                 }
51522             }
51523             function mapToTypeNodes(types, context, isBareList) {
51524                 if (ts.some(types)) {
51525                     if (checkTruncationLength(context)) {
51526                         if (!isBareList) {
51527                             return [ts.factory.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
51528                         }
51529                         else if (types.length > 2) {
51530                             return [
51531                                 typeToTypeNodeHelper(types[0], context),
51532                                 ts.factory.createTypeReferenceNode("... ".concat(types.length - 2, " more ..."), /*typeArguments*/ undefined),
51533                                 typeToTypeNodeHelper(types[types.length - 1], context)
51534                             ];
51535                         }
51536                     }
51537                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
51538                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
51539                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
51540                     var result_5 = [];
51541                     var i = 0;
51542                     for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
51543                         var type = types_2[_i];
51544                         i++;
51545                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
51546                             result_5.push(ts.factory.createTypeReferenceNode("... ".concat(types.length - i, " more ..."), /*typeArguments*/ undefined));
51547                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
51548                             if (typeNode_1) {
51549                                 result_5.push(typeNode_1);
51550                             }
51551                             break;
51552                         }
51553                         context.approximateLength += 2; // Account for whitespace + separator
51554                         var typeNode = typeToTypeNodeHelper(type, context);
51555                         if (typeNode) {
51556                             result_5.push(typeNode);
51557                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
51558                                 seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]);
51559                             }
51560                         }
51561                     }
51562                     if (seenNames) {
51563                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
51564                         // occurrences of the same name actually come from different
51565                         // namespaces, go through the single-identifier type reference nodes
51566                         // we just generated, and see if any names were generated more than
51567                         // once while referring to different types. If so, regenerate the
51568                         // type node for each entry by that name with the
51569                         // `UseFullyQualifiedType` flag enabled.
51570                         var saveContextFlags = context.flags;
51571                         context.flags |= 64 /* UseFullyQualifiedType */;
51572                         seenNames.forEach(function (types) {
51573                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
51574                                 var a = _a[0];
51575                                 var b = _b[0];
51576                                 return typesAreSameReference(a, b);
51577                             })) {
51578                                 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
51579                                     var _a = types_3[_i], type = _a[0], resultIndex = _a[1];
51580                                     result_5[resultIndex] = typeToTypeNodeHelper(type, context);
51581                                 }
51582                             }
51583                         });
51584                         context.flags = saveContextFlags;
51585                     }
51586                     return result_5;
51587                 }
51588             }
51589             function typesAreSameReference(a, b) {
51590                 return a === b
51591                     || !!a.symbol && a.symbol === b.symbol
51592                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
51593             }
51594             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) {
51595                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
51596                 var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context);
51597                 var indexingParameter = ts.factory.createParameterDeclaration(
51598                 /*decorators*/ undefined, 
51599                 /*modifiers*/ undefined, 
51600                 /*dotDotDotToken*/ undefined, name, 
51601                 /*questionToken*/ undefined, indexerTypeNode, 
51602                 /*initializer*/ undefined);
51603                 if (!typeNode) {
51604                     typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
51605                 }
51606                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
51607                     context.encounteredError = true;
51608                 }
51609                 context.approximateLength += (name.length + 4);
51610                 return ts.factory.createIndexSignature(
51611                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(144 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
51612             }
51613             function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
51614                 var _a, _b, _c, _d;
51615                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
51616                 if (suppressAny)
51617                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
51618                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
51619                 var typeParameters;
51620                 var typeArguments;
51621                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
51622                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
51623                 }
51624                 else {
51625                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
51626                 }
51627                 var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0];
51628                 // If the expanded parameter list had a variadic in a non-trailing position, don't expand it
51629                 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 === 170 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); });
51630                 if (signature.thisParameter) {
51631                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
51632                     parameters.unshift(thisParameter);
51633                 }
51634                 var returnTypeNode;
51635                 var typePredicate = getTypePredicateOfSignature(signature);
51636                 if (typePredicate) {
51637                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
51638                         ts.factory.createToken(128 /* AssertsKeyword */) :
51639                         undefined;
51640                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
51641                         ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
51642                         ts.factory.createThisTypeNode();
51643                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
51644                     returnTypeNode = ts.factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
51645                 }
51646                 else {
51647                     var returnType = getReturnTypeOfSignature(signature);
51648                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
51649                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports);
51650                     }
51651                     else if (!suppressAny) {
51652                         returnTypeNode = ts.factory.createKeywordTypeNode(130 /* AnyKeyword */);
51653                     }
51654                 }
51655                 var modifiers = options === null || options === void 0 ? void 0 : options.modifiers;
51656                 if ((kind === 179 /* ConstructorType */) && signature.flags & 4 /* Abstract */) {
51657                     var flags = ts.modifiersToFlags(modifiers);
51658                     modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */);
51659                 }
51660                 var node = kind === 173 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
51661                     kind === 174 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
51662                         kind === 167 /* MethodSignature */ ? ts.factory.createMethodSignature(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) :
51663                             kind === 168 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, 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) :
51664                                 kind === 170 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) :
51665                                     kind === 171 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) :
51666                                         kind === 172 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) :
51667                                             kind === 175 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) :
51668                                                 kind === 315 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
51669                                                     kind === 178 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
51670                                                         kind === 179 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
51671                                                             kind === 255 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, 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) :
51672                                                                 kind === 212 /* FunctionExpression */ ? ts.factory.createFunctionExpression(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([])) :
51673                                                                     kind === 213 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
51674                                                                         ts.Debug.assertNever(kind);
51675                 if (typeArguments) {
51676                     node.typeArguments = ts.factory.createNodeArray(typeArguments);
51677                 }
51678                 return node;
51679             }
51680             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
51681                 var savedContextFlags = context.flags;
51682                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
51683                 var name = typeParameterToName(type, context);
51684                 var defaultParameter = getDefaultFromTypeParameter(type);
51685                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
51686                 context.flags = savedContextFlags;
51687                 return ts.factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
51688             }
51689             function typeParameterToDeclaration(type, context, constraint) {
51690                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
51691                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
51692                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
51693             }
51694             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
51695                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 163 /* Parameter */);
51696                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
51697                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 338 /* JSDocParameterTag */);
51698                 }
51699                 var parameterType = getTypeOfSymbol(parameterSymbol);
51700                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
51701                     parameterType = getOptionalType(parameterType);
51702                 }
51703                 if ((context.flags & 1073741824 /* NoUndefinedOptionalParameterType */) && parameterDeclaration && !ts.isJSDocParameterTag(parameterDeclaration) && isOptionalUninitializedParameter(parameterDeclaration)) {
51704                     parameterType = getTypeWithFacts(parameterType, 524288 /* NEUndefined */);
51705                 }
51706                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
51707                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined;
51708                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
51709                 var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined;
51710                 var name = parameterDeclaration ? parameterDeclaration.name ?
51711                     parameterDeclaration.name.kind === 79 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
51712                         parameterDeclaration.name.kind === 160 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
51713                             cloneBindingName(parameterDeclaration.name) :
51714                     ts.symbolName(parameterSymbol) :
51715                     ts.symbolName(parameterSymbol);
51716                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
51717                 var questionToken = isOptional ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
51718                 var parameterNode = ts.factory.createParameterDeclaration(
51719                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
51720                 /*initializer*/ undefined);
51721                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
51722                 return parameterNode;
51723                 function cloneBindingName(node) {
51724                     return elideInitializerAndSetEmitFlags(node);
51725                     function elideInitializerAndSetEmitFlags(node) {
51726                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
51727                             trackComputedName(node.expression, context.enclosingDeclaration, context);
51728                         }
51729                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
51730                         if (ts.isBindingElement(visited)) {
51731                             visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, 
51732                             /*initializer*/ undefined);
51733                         }
51734                         if (!ts.nodeIsSynthesized(visited)) {
51735                             visited = ts.factory.cloneNode(visited);
51736                         }
51737                         return ts.setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
51738                     }
51739                 }
51740             }
51741             function trackComputedName(accessExpression, enclosingDeclaration, context) {
51742                 if (!context.tracker.trackSymbol)
51743                     return;
51744                 // get symbol of the first identifier of the entityName
51745                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
51746                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
51747                 if (name) {
51748                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
51749                 }
51750             }
51751             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
51752                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
51753                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
51754             }
51755             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
51756                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
51757                 var chain;
51758                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
51759                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
51760                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
51761                     ts.Debug.assert(chain && chain.length > 0);
51762                 }
51763                 else {
51764                     chain = [symbol];
51765                 }
51766                 return chain;
51767                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
51768                 function getSymbolChain(symbol, meaning, endOfChain) {
51769                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
51770                     var parentSpecifiers;
51771                     if (!accessibleSymbolChain ||
51772                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
51773                         // Go up and add our parent.
51774                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning);
51775                         if (ts.length(parents_1)) {
51776                             parentSpecifiers = parents_1.map(function (symbol) {
51777                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
51778                                     ? getSpecifierForModuleSymbol(symbol, context)
51779                                     : undefined;
51780                             });
51781                             var indices = parents_1.map(function (_, i) { return i; });
51782                             indices.sort(sortByBestName);
51783                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
51784                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
51785                                 var parent = sortedParents_1[_i];
51786                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
51787                                 if (parentChain) {
51788                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
51789                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
51790                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
51791                                         // No need to lookup an alias for the symbol in itself
51792                                         accessibleSymbolChain = parentChain;
51793                                         break;
51794                                     }
51795                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
51796                                     break;
51797                                 }
51798                             }
51799                         }
51800                     }
51801                     if (accessibleSymbolChain) {
51802                         return accessibleSymbolChain;
51803                     }
51804                     if (
51805                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
51806                     endOfChain ||
51807                         // If a parent symbol is an anonymous type, don't write it.
51808                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
51809                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
51810                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
51811                             return;
51812                         }
51813                         return [symbol];
51814                     }
51815                     function sortByBestName(a, b) {
51816                         var specifierA = parentSpecifiers[a];
51817                         var specifierB = parentSpecifiers[b];
51818                         if (specifierA && specifierB) {
51819                             var isBRelative = ts.pathIsRelative(specifierB);
51820                             if (ts.pathIsRelative(specifierA) === isBRelative) {
51821                                 // Both relative or both non-relative, sort by number of parts
51822                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
51823                             }
51824                             if (isBRelative) {
51825                                 // A is non-relative, B is relative: prefer A
51826                                 return -1;
51827                             }
51828                             // A is relative, B is non-relative: prefer B
51829                             return 1;
51830                         }
51831                         return 0;
51832                     }
51833                 }
51834             }
51835             function typeParametersToTypeParameterDeclarations(symbol, context) {
51836                 var typeParameterNodes;
51837                 var targetSymbol = getTargetSymbol(symbol);
51838                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
51839                     typeParameterNodes = ts.factory.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
51840                 }
51841                 return typeParameterNodes;
51842             }
51843             function lookupTypeParameterNodes(chain, index, context) {
51844                 var _a;
51845                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
51846                 var symbol = chain[index];
51847                 var symbolId = getSymbolId(symbol);
51848                 if ((_a = context.typeParameterSymbolList) === null || _a === void 0 ? void 0 : _a.has(symbolId)) {
51849                     return undefined;
51850                 }
51851                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = new ts.Set())).add(symbolId);
51852                 var typeParameterNodes;
51853                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
51854                     var parentSymbol = symbol;
51855                     var nextSymbol_1 = chain[index + 1];
51856                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
51857                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
51858                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
51859                     }
51860                     else {
51861                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
51862                     }
51863                 }
51864                 return typeParameterNodes;
51865             }
51866             /**
51867              * Given A[B][C][D], finds A[B]
51868              */
51869             function getTopmostIndexedAccessType(top) {
51870                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
51871                     return getTopmostIndexedAccessType(top.objectType);
51872                 }
51873                 return top;
51874             }
51875             function getSpecifierForModuleSymbol(symbol, context) {
51876                 var _a;
51877                 var file = ts.getDeclarationOfKind(symbol, 303 /* SourceFile */);
51878                 if (!file) {
51879                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
51880                     if (equivalentFileSymbol) {
51881                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 303 /* SourceFile */);
51882                     }
51883                 }
51884                 if (file && file.moduleName !== undefined) {
51885                     // Use the amd name if it is available
51886                     return file.moduleName;
51887                 }
51888                 if (!file) {
51889                     if (context.tracker.trackReferencedAmbientModule) {
51890                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
51891                         if (ts.length(ambientDecls)) {
51892                             for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) {
51893                                 var decl = _b[_i];
51894                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
51895                             }
51896                         }
51897                     }
51898                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
51899                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
51900                     }
51901                 }
51902                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
51903                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
51904                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
51905                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
51906                     }
51907                     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
51908                 }
51909                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
51910                 var links = getSymbolLinks(symbol);
51911                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
51912                 if (!specifier) {
51913                     var isBundle_1 = !!ts.outFile(compilerOptions);
51914                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
51915                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
51916                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
51917                     // specifier preference
51918                     var moduleResolverHost = context.tracker.moduleResolverHost;
51919                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
51920                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
51921                     (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
51922                     links.specifierCache.set(contextFile.path, specifier);
51923                 }
51924                 return specifier;
51925             }
51926             function symbolToEntityNameNode(symbol) {
51927                 var identifier = ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(symbol.escapedName));
51928                 return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier;
51929             }
51930             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
51931                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
51932                 var isTypeOf = meaning === 111551 /* Value */;
51933                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
51934                     // module is root, must use `ImportTypeNode`
51935                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
51936                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
51937                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
51938                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Classic && specifier.indexOf("/node_modules/") >= 0) {
51939                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
51940                         // since declaration files with these kinds of references are liable to fail when published :(
51941                         context.encounteredError = true;
51942                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
51943                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
51944                         }
51945                     }
51946                     var lit = ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier));
51947                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
51948                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
51949                     context.approximateLength += specifier.length + 10; // specifier + import("")
51950                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
51951                         if (nonRootParts) {
51952                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
51953                             lastId.typeArguments = undefined;
51954                         }
51955                         return ts.factory.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
51956                     }
51957                     else {
51958                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
51959                         var qualifier = splitNode.objectType.typeName;
51960                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
51961                     }
51962                 }
51963                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
51964                 if (ts.isIndexedAccessTypeNode(entityName)) {
51965                     return entityName; // Indexed accesses can never be `typeof`
51966                 }
51967                 if (isTypeOf) {
51968                     return ts.factory.createTypeQueryNode(entityName);
51969                 }
51970                 else {
51971                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
51972                     var lastTypeArgs = lastId.typeArguments;
51973                     lastId.typeArguments = undefined;
51974                     return ts.factory.createTypeReferenceNode(entityName, lastTypeArgs);
51975                 }
51976                 function createAccessFromSymbolChain(chain, index, stopper) {
51977                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
51978                     var symbol = chain[index];
51979                     var parent = chain[index - 1];
51980                     var symbolName;
51981                     if (index === 0) {
51982                         context.flags |= 16777216 /* InInitialEntityName */;
51983                         symbolName = getNameOfSymbolAsWritten(symbol, context);
51984                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
51985                         context.flags ^= 16777216 /* InInitialEntityName */;
51986                     }
51987                     else {
51988                         if (parent && getExportsOfSymbol(parent)) {
51989                             var exports_1 = getExportsOfSymbol(parent);
51990                             ts.forEachEntry(exports_1, function (ex, name) {
51991                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
51992                                     symbolName = ts.unescapeLeadingUnderscores(name);
51993                                     return true;
51994                                 }
51995                             });
51996                         }
51997                     }
51998                     if (!symbolName) {
51999                         symbolName = getNameOfSymbolAsWritten(symbol, context);
52000                     }
52001                     context.approximateLength += symbolName.length + 1;
52002                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
52003                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
52004                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
52005                         // Should use an indexed access
52006                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
52007                         if (ts.isIndexedAccessTypeNode(LHS)) {
52008                             return ts.factory.createIndexedAccessTypeNode(LHS, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
52009                         }
52010                         else {
52011                             return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(LHS, typeParameterNodes), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
52012                         }
52013                     }
52014                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
52015                     identifier.symbol = symbol;
52016                     if (index > stopper) {
52017                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
52018                         if (!ts.isEntityName(LHS)) {
52019                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
52020                         }
52021                         return ts.factory.createQualifiedName(LHS, identifier);
52022                     }
52023                     return identifier;
52024                 }
52025             }
52026             function typeParameterShadowsNameInScope(escapedName, context, type) {
52027                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
52028                 if (result) {
52029                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
52030                         return false;
52031                     }
52032                     return true;
52033                 }
52034                 return false;
52035             }
52036             function typeParameterToName(type, context) {
52037                 var _a, _b;
52038                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
52039                     var cached = context.typeParameterNames.get(getTypeId(type));
52040                     if (cached) {
52041                         return cached;
52042                     }
52043                 }
52044                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
52045                 if (!(result.kind & 79 /* Identifier */)) {
52046                     return ts.factory.createIdentifier("(Missing type parameter)");
52047                 }
52048                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
52049                     var rawtext = result.escapedText;
52050                     var i = ((_a = context.typeParameterNamesByTextNextNameCount) === null || _a === void 0 ? void 0 : _a.get(rawtext)) || 0;
52051                     var text = rawtext;
52052                     while (((_b = context.typeParameterNamesByText) === null || _b === void 0 ? void 0 : _b.has(text)) || typeParameterShadowsNameInScope(text, context, type)) {
52053                         i++;
52054                         text = "".concat(rawtext, "_").concat(i);
52055                     }
52056                     if (text !== rawtext) {
52057                         result = ts.factory.createIdentifier(text, result.typeArguments);
52058                     }
52059                     // avoiding iterations of the above loop turns out to be worth it when `i` starts to get large, so we cache the max
52060                     // `i` we've used thus far, to save work later
52061                     (context.typeParameterNamesByTextNextNameCount || (context.typeParameterNamesByTextNextNameCount = new ts.Map())).set(rawtext, i);
52062                     (context.typeParameterNames || (context.typeParameterNames = new ts.Map())).set(getTypeId(type), result);
52063                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = new ts.Set())).add(rawtext);
52064                 }
52065                 return result;
52066             }
52067             function symbolToName(symbol, context, meaning, expectsIdentifier) {
52068                 var chain = lookupSymbolChain(symbol, context, meaning);
52069                 if (expectsIdentifier && chain.length !== 1
52070                     && !context.encounteredError
52071                     && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) {
52072                     context.encounteredError = true;
52073                 }
52074                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
52075                 function createEntityNameFromSymbolChain(chain, index) {
52076                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
52077                     var symbol = chain[index];
52078                     if (index === 0) {
52079                         context.flags |= 16777216 /* InInitialEntityName */;
52080                     }
52081                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
52082                     if (index === 0) {
52083                         context.flags ^= 16777216 /* InInitialEntityName */;
52084                     }
52085                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
52086                     identifier.symbol = symbol;
52087                     return index > 0 ? ts.factory.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
52088                 }
52089             }
52090             function symbolToExpression(symbol, context, meaning) {
52091                 var chain = lookupSymbolChain(symbol, context, meaning);
52092                 return createExpressionFromSymbolChain(chain, chain.length - 1);
52093                 function createExpressionFromSymbolChain(chain, index) {
52094                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
52095                     var symbol = chain[index];
52096                     if (index === 0) {
52097                         context.flags |= 16777216 /* InInitialEntityName */;
52098                     }
52099                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
52100                     if (index === 0) {
52101                         context.flags ^= 16777216 /* InInitialEntityName */;
52102                     }
52103                     var firstChar = symbolName.charCodeAt(0);
52104                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
52105                         return ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context));
52106                     }
52107                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
52108                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
52109                         ts.isIdentifierStart(firstChar, languageVersion);
52110                     if (index === 0 || canUsePropertyAccess) {
52111                         var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
52112                         identifier.symbol = symbol;
52113                         return index > 0 ? ts.factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
52114                     }
52115                     else {
52116                         if (firstChar === 91 /* openBracket */) {
52117                             symbolName = symbolName.substring(1, symbolName.length - 1);
52118                             firstChar = symbolName.charCodeAt(0);
52119                         }
52120                         var expression = void 0;
52121                         if (ts.isSingleOrDoubleQuote(firstChar)) {
52122                             expression = ts.factory.createStringLiteral(symbolName
52123                                 .substring(1, symbolName.length - 1)
52124                                 .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */);
52125                         }
52126                         else if (("" + +symbolName) === symbolName) {
52127                             expression = ts.factory.createNumericLiteral(+symbolName);
52128                         }
52129                         if (!expression) {
52130                             expression = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
52131                             expression.symbol = symbol;
52132                         }
52133                         return ts.factory.createElementAccessExpression(createExpressionFromSymbolChain(chain, index - 1), expression);
52134                     }
52135                 }
52136             }
52137             function isStringNamed(d) {
52138                 var name = ts.getNameOfDeclaration(d);
52139                 return !!name && ts.isStringLiteral(name);
52140             }
52141             function isSingleQuotedStringNamed(d) {
52142                 var name = ts.getNameOfDeclaration(d);
52143                 return !!(name && ts.isStringLiteral(name) && (name.singleQuote || !ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")));
52144             }
52145             function getPropertyNameNodeForSymbol(symbol, context) {
52146                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
52147                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
52148                 if (fromNameType) {
52149                     return fromNameType;
52150                 }
52151                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
52152                 var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed);
52153                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote);
52154             }
52155             // See getNameForSymbolFromNameType for a stringy equivalent
52156             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
52157                 var nameType = getSymbolLinks(symbol).nameType;
52158                 if (nameType) {
52159                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
52160                         var name = "" + nameType.value;
52161                         if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) {
52162                             return ts.factory.createStringLiteral(name, !!singleQuote);
52163                         }
52164                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
52165                             return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name));
52166                         }
52167                         return createPropertyNameNodeForIdentifierOrLiteral(name);
52168                     }
52169                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
52170                         return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
52171                     }
52172                 }
52173             }
52174             function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) {
52175                 return ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) ? ts.factory.createIdentifier(name) :
52176                     !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) :
52177                         ts.factory.createStringLiteral(name, !!singleQuote);
52178             }
52179             function cloneNodeBuilderContext(context) {
52180                 var initial = __assign({}, context);
52181                 // Make type parameters created within this context not consume the name outside this context
52182                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
52183                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
52184                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
52185                 // were multiple generic overloads with similar generated type parameter names
52186                 // The effect:
52187                 // When we write out
52188                 // export const x: <T>(x: T) => T
52189                 // export const y: <T>(x: T) => T
52190                 // we write it out like that, rather than as
52191                 // export const x: <T>(x: T) => T
52192                 // export const y: <T_1>(x: T_1) => T_1
52193                 if (initial.typeParameterNames) {
52194                     initial.typeParameterNames = new ts.Map(initial.typeParameterNames);
52195                 }
52196                 if (initial.typeParameterNamesByText) {
52197                     initial.typeParameterNamesByText = new ts.Set(initial.typeParameterNamesByText);
52198                 }
52199                 if (initial.typeParameterSymbolList) {
52200                     initial.typeParameterSymbolList = new ts.Set(initial.typeParameterSymbolList);
52201                 }
52202                 initial.tracker = wrapSymbolTrackerToReportForContext(initial, initial.tracker);
52203                 return initial;
52204             }
52205             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
52206                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
52207             }
52208             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
52209                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
52210             }
52211             /**
52212              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
52213              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
52214              */
52215             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
52216                 if (!isErrorType(type) && enclosingDeclaration) {
52217                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
52218                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) {
52219                         // try to reuse the existing annotation
52220                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
52221                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
52222                             var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
52223                             if (result_6) {
52224                                 return result_6;
52225                             }
52226                         }
52227                     }
52228                 }
52229                 var oldFlags = context.flags;
52230                 if (type.flags & 8192 /* UniqueESSymbol */ &&
52231                     type.symbol === symbol && (!context.enclosingDeclaration || ts.some(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration); }))) {
52232                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
52233                 }
52234                 var result = typeToTypeNodeHelper(type, context);
52235                 context.flags = oldFlags;
52236                 return result;
52237             }
52238             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
52239                 if (!isErrorType(type) && context.enclosingDeclaration) {
52240                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
52241                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) {
52242                         var annotated = getTypeFromTypeNode(annotation);
52243                         var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated;
52244                         if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
52245                             var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
52246                             if (result) {
52247                                 return result;
52248                             }
52249                         }
52250                     }
52251                 }
52252                 return typeToTypeNodeHelper(type, context);
52253             }
52254             function trackExistingEntityName(node, context, includePrivateSymbol) {
52255                 var _a, _b;
52256                 var introducesError = false;
52257                 var leftmost = ts.getFirstIdentifier(node);
52258                 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)))) {
52259                     introducesError = true;
52260                     return { introducesError: introducesError, node: node };
52261                 }
52262                 var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
52263                 if (sym) {
52264                     if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
52265                         introducesError = true;
52266                     }
52267                     else {
52268                         (_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 */);
52269                         includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
52270                     }
52271                     if (ts.isIdentifier(node)) {
52272                         var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
52273                         name.symbol = sym; // for quickinfo, which uses identifier symbol information
52274                         return { introducesError: introducesError, node: ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) };
52275                     }
52276                 }
52277                 return { introducesError: introducesError, node: node };
52278             }
52279             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
52280                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
52281                     cancellationToken.throwIfCancellationRequested();
52282                 }
52283                 var hadError = false;
52284                 var file = ts.getSourceFileOfNode(existing);
52285                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
52286                 if (hadError) {
52287                     return undefined;
52288                 }
52289                 return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
52290                 function visitExistingNodeTreeSymbols(node) {
52291                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
52292                     if (ts.isJSDocAllType(node) || node.kind === 317 /* JSDocNamepathType */) {
52293                         return ts.factory.createKeywordTypeNode(130 /* AnyKeyword */);
52294                     }
52295                     if (ts.isJSDocUnknownType(node)) {
52296                         return ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */);
52297                     }
52298                     if (ts.isJSDocNullableType(node)) {
52299                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]);
52300                     }
52301                     if (ts.isJSDocOptionalType(node)) {
52302                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(152 /* UndefinedKeyword */)]);
52303                     }
52304                     if (ts.isJSDocNonNullableType(node)) {
52305                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
52306                     }
52307                     if (ts.isJSDocVariadicType(node)) {
52308                         return ts.factory.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
52309                     }
52310                     if (ts.isJSDocTypeLiteral(node)) {
52311                         return ts.factory.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
52312                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
52313                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
52314                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
52315                             return ts.factory.createPropertySignature(
52316                             /*modifiers*/ undefined, name, t.isBracketed || 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(130 /* AnyKeyword */));
52317                         }));
52318                     }
52319                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
52320                         return ts.setOriginalNode(ts.factory.createKeywordTypeNode(130 /* AnyKeyword */), node);
52321                     }
52322                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
52323                         return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(
52324                             /*decorators*/ undefined, 
52325                             /*modifiers*/ undefined, [ts.factory.createParameterDeclaration(
52326                                 /*decorators*/ undefined, 
52327                                 /*modifiers*/ undefined, 
52328                                 /*dotdotdotToken*/ undefined, "x", 
52329                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
52330                     }
52331                     if (ts.isJSDocFunctionType(node)) {
52332                         if (ts.isJSDocConstructSignature(node)) {
52333                             var newTypeNode_1;
52334                             return ts.factory.createConstructorTypeNode(node.modifiers, 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(
52335                             /*decorators*/ undefined, 
52336                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
52337                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* AnyKeyword */));
52338                         }
52339                         else {
52340                             return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(
52341                             /*decorators*/ undefined, 
52342                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
52343                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* AnyKeyword */));
52344                         }
52345                     }
52346                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(node, 788968 /* Type */, /*ignoreErrors*/ true))) {
52347                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
52348                     }
52349                     if (ts.isLiteralImportTypeNode(node)) {
52350                         var nodeSymbol = getNodeLinks(node).resolvedSymbol;
52351                         if (ts.isInJSDoc(node) &&
52352                             nodeSymbol &&
52353                             (
52354                             // The import type resolved using jsdoc fallback logic
52355                             (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */)) ||
52356                                 // The import type had type arguments autofilled by js fallback logic
52357                                 !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) {
52358                             return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
52359                         }
52360                         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);
52361                     }
52362                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
52363                         var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node;
52364                         hadError = hadError || introducesError;
52365                         if (result !== node) {
52366                             return result;
52367                         }
52368                     }
52369                     if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
52370                         ts.setEmitFlags(node, 1 /* SingleLine */);
52371                     }
52372                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
52373                     function getEffectiveDotDotDotForParameter(p) {
52374                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined);
52375                     }
52376                     /** Note that `new:T` parameters are not handled, but should be before calling this function. */
52377                     function getNameForJSDocFunctionParameter(p, index) {
52378                         return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this"
52379                             : getEffectiveDotDotDotForParameter(p) ? "args"
52380                                 : "arg".concat(index);
52381                     }
52382                     function rewriteModuleSpecifier(parent, lit) {
52383                         if (bundled) {
52384                             if (context.tracker && context.tracker.moduleResolverHost) {
52385                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
52386                                 if (targetFile) {
52387                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
52388                                     var resolverHost = {
52389                                         getCanonicalFileName: getCanonicalFileName,
52390                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
52391                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
52392                                     };
52393                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
52394                                     return ts.factory.createStringLiteral(newName);
52395                                 }
52396                             }
52397                         }
52398                         else {
52399                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
52400                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
52401                                 if (moduleSym) {
52402                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
52403                                 }
52404                             }
52405                         }
52406                         return lit;
52407                     }
52408                 }
52409             }
52410             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
52411                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 168 /* MethodDeclaration */, /*useAcessors*/ true);
52412                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 167 /* MethodSignature */, /*useAcessors*/ false);
52413                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
52414                 // declaration mapping
52415                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
52416                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
52417                 // we're trying to emit from later on)
52418                 var enclosingDeclaration = context.enclosingDeclaration;
52419                 var results = [];
52420                 var visitedSymbols = new ts.Set();
52421                 var deferredPrivatesStack = [];
52422                 var oldcontext = context;
52423                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
52424                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false);
52425                             if (accessibleResult.accessibility === 0 /* Accessible */) {
52426                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
52427                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
52428                                 if (!(sym.flags & 4 /* Property */)) {
52429                                     includePrivateSymbol(chain[0]);
52430                                 }
52431                             }
52432                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
52433                                 return oldcontext.tracker.trackSymbol(sym, decl, meaning);
52434                             }
52435                             return false;
52436                         } }) });
52437                 context.tracker = wrapSymbolTrackerToReportForContext(context, context.tracker);
52438                 ts.forEachEntry(symbolTable, function (symbol, name) {
52439                     var baseName = ts.unescapeLeadingUnderscores(name);
52440                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
52441                 });
52442                 var addingDeclare = !bundled;
52443                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
52444                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
52445                     symbolTable = ts.createSymbolTable();
52446                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
52447                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
52448                 }
52449                 visitSymbolTable(symbolTable);
52450                 return mergeRedundantStatements(results);
52451                 function isIdentifierAndNotUndefined(node) {
52452                     return !!node && node.kind === 79 /* Identifier */;
52453                 }
52454                 function getNamesOfDeclaration(statement) {
52455                     if (ts.isVariableStatement(statement)) {
52456                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
52457                     }
52458                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
52459                 }
52460                 function flattenExportAssignedNamespace(statements) {
52461                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
52462                     var nsIndex = ts.findIndex(statements, ts.isModuleDeclaration);
52463                     var ns = nsIndex !== -1 ? statements[nsIndex] : undefined;
52464                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
52465                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
52466                         ns.body && ts.isModuleBlock(ns.body)) {
52467                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
52468                         //  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
52469                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getEffectiveModifierFlags(s) & 1 /* Export */); });
52470                         var name_2 = ns.name;
52471                         var body = ns.body;
52472                         if (ts.length(excessExports)) {
52473                             ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration(
52474                                 /*decorators*/ undefined, 
52475                                 /*modifiers*/ undefined, 
52476                                 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), 
52477                                 /*moduleSpecifier*/ undefined)], false))));
52478                             statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, nsIndex), true), [ns], false), statements.slice(nsIndex + 1), true);
52479                         }
52480                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
52481                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
52482                             results = [];
52483                             // If the namespace contains no export assignments or declarations, and no declarations flagged with `export`, then _everything_ is exported -
52484                             // to respect this as the top level, we need to add an `export` modifier to everything
52485                             var mixinExportFlag_1 = !ts.some(body.statements, function (s) { return ts.hasSyntacticModifier(s, 1 /* Export */) || ts.isExportAssignment(s) || ts.isExportDeclaration(s); });
52486                             ts.forEach(body.statements, function (s) {
52487                                 addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
52488                             });
52489                             statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), true), results, true);
52490                         }
52491                     }
52492                     return statements;
52493                 }
52494                 function mergeExportDeclarations(statements) {
52495                     // Pass 2: Combine all `export {}` declarations
52496                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
52497                     if (ts.length(exports) > 1) {
52498                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
52499                         statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration(
52500                             /*decorators*/ undefined, 
52501                             /*modifiers*/ undefined, 
52502                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
52503                             /*moduleSpecifier*/ undefined)], false);
52504                     }
52505                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
52506                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
52507                     if (ts.length(reexports) > 1) {
52508                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
52509                         if (groups.length !== reexports.length) {
52510                             var _loop_9 = function (group_1) {
52511                                 if (group_1.length > 1) {
52512                                     // remove group members from statements and then merge group members and add back to statements
52513                                     statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [
52514                                         ts.factory.createExportDeclaration(
52515                                         /*decorators*/ undefined, 
52516                                         /*modifiers*/ undefined, 
52517                                         /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
52518                                     ], false);
52519                                 }
52520                             };
52521                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
52522                                 var group_1 = groups_1[_i];
52523                                 _loop_9(group_1);
52524                             }
52525                         }
52526                     }
52527                     return statements;
52528                 }
52529                 function inlineExportModifiers(statements) {
52530                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
52531                     var index = ts.findIndex(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !d.assertClause && !!d.exportClause && ts.isNamedExports(d.exportClause); });
52532                     if (index >= 0) {
52533                         var exportDecl = statements[index];
52534                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
52535                             if (!e.propertyName) {
52536                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
52537                                 var indices = ts.indicesOf(statements);
52538                                 var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); });
52539                                 if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) {
52540                                     for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) {
52541                                         var index_1 = associatedIndices_1[_i];
52542                                         statements[index_1] = addExportModifier(statements[index_1]);
52543                                     }
52544                                     return undefined;
52545                                 }
52546                             }
52547                             return e;
52548                         });
52549                         if (!ts.length(replacements)) {
52550                             // all clauses removed, remove the export declaration
52551                             ts.orderedRemoveItemAt(statements, index);
52552                         }
52553                         else {
52554                             // some items filtered, others not - update the export declaration
52555                             statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause);
52556                         }
52557                     }
52558                     return statements;
52559                 }
52560                 function mergeRedundantStatements(statements) {
52561                     statements = flattenExportAssignedNamespace(statements);
52562                     statements = mergeExportDeclarations(statements);
52563                     statements = inlineExportModifiers(statements);
52564                     // 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
52565                     // declaration privacy is respected.
52566                     if (enclosingDeclaration &&
52567                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
52568                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
52569                         statements.push(ts.createEmptyExports(ts.factory));
52570                     }
52571                     return statements;
52572                 }
52573                 function canHaveExportModifier(node) {
52574                     return ts.isEnumDeclaration(node) ||
52575                         ts.isVariableStatement(node) ||
52576                         ts.isFunctionDeclaration(node) ||
52577                         ts.isClassDeclaration(node) ||
52578                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
52579                         ts.isInterfaceDeclaration(node) ||
52580                         isTypeDeclaration(node);
52581                 }
52582                 function addExportModifier(node) {
52583                     var flags = (ts.getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */;
52584                     return ts.factory.updateModifiers(node, flags);
52585                 }
52586                 function removeExportModifier(node) {
52587                     var flags = ts.getEffectiveModifierFlags(node) & ~1 /* Export */;
52588                     return ts.factory.updateModifiers(node, flags);
52589                 }
52590                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
52591                     if (!suppressNewPrivateContext) {
52592                         deferredPrivatesStack.push(new ts.Map());
52593                     }
52594                     symbolTable.forEach(function (symbol) {
52595                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
52596                     });
52597                     if (!suppressNewPrivateContext) {
52598                         // deferredPrivates will be filled up by visiting the symbol table
52599                         // And will continue to iterate as elements are added while visited `deferredPrivates`
52600                         // (As that's how a map iterator is defined to work)
52601                         deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(function (symbol) {
52602                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
52603                         });
52604                         deferredPrivatesStack.pop();
52605                     }
52606                 }
52607                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
52608                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
52609                     // still skip reserializing it if we encounter the merged product later on
52610                     var visitedSym = getMergedSymbol(symbol);
52611                     if (visitedSymbols.has(getSymbolId(visitedSym))) {
52612                         return; // Already printed
52613                     }
52614                     visitedSymbols.add(getSymbolId(visitedSym));
52615                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
52616                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
52617                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
52618                         var oldContext = context;
52619                         context = cloneNodeBuilderContext(context);
52620                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
52621                         if (context.reportedDiagnostic) {
52622                             oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context
52623                         }
52624                         context = oldContext;
52625                         return result;
52626                     }
52627                 }
52628                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
52629                 // or a merge of some number of those.
52630                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
52631                 // each symbol in only one of the representations
52632                 // Also, synthesizing a default export of some kind
52633                 // If it's an alias: emit `export default ref`
52634                 // If it's a property: emit `export default _default` with a `_default` prop
52635                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
52636                 // These forms can merge, eg (`export default 12; export default interface A {}`)
52637                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
52638                     var _a, _b;
52639                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
52640                     var isDefault = symbol.escapedName === "default" /* Default */;
52641                     if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
52642                         // 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` :(
52643                         context.encounteredError = true;
52644                         // TODO: Issue error via symbol tracker?
52645                         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
52646                     }
52647                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
52648                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
52649                     var needsExportDeclaration = !needsPostExportDefault && !isPrivate && ts.isStringANonContextualKeyword(symbolName) && !isDefault;
52650                     // `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
52651                     if (needsPostExportDefault || needsExportDeclaration) {
52652                         isPrivate = true;
52653                     }
52654                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
52655                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
52656                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
52657                         symbol.escapedName !== "export=" /* ExportEquals */;
52658                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
52659                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
52660                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
52661                     }
52662                     if (symbol.flags & 524288 /* TypeAlias */) {
52663                         serializeTypeAlias(symbol, symbolName, modifierFlags);
52664                     }
52665                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
52666                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
52667                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
52668                         && symbol.escapedName !== "export=" /* ExportEquals */
52669                         && !(symbol.flags & 4194304 /* Prototype */)
52670                         && !(symbol.flags & 32 /* Class */)
52671                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
52672                         if (propertyAsAlias) {
52673                             var createdExport = serializeMaybeAliasAssignment(symbol);
52674                             if (createdExport) {
52675                                 needsExportDeclaration = false;
52676                                 needsPostExportDefault = false;
52677                             }
52678                         }
52679                         else {
52680                             var type = getTypeOfSymbol(symbol);
52681                             var localName = getInternalSymbolName(symbol, symbolName);
52682                             if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
52683                                 // 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
52684                                 serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
52685                             }
52686                             else {
52687                                 // 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!_
52688                                 // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
52689                                 var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
52690                                     : isConstVariable(symbol) ? 2 /* Const */
52691                                         : 1 /* Let */;
52692                                 var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
52693                                 var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
52694                                 if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
52695                                     textRange = textRange.parent.parent;
52696                                 }
52697                                 var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression);
52698                                 if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right)
52699                                     && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) {
52700                                     var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right;
52701                                     addResult(ts.factory.createExportDeclaration(
52702                                     /*decorators*/ undefined, 
52703                                     /*modifiers*/ undefined, 
52704                                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* None */);
52705                                     context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
52706                                 }
52707                                 else {
52708                                     var statement = ts.setTextRange(ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
52709                                         ts.factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
52710                                     ], flags)), textRange);
52711                                     addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
52712                                     if (name !== localName && !isPrivate) {
52713                                         // We rename the variable declaration we generate for Property symbols since they may have a name which
52714                                         // conflicts with a local declaration. For example, given input:
52715                                         // ```
52716                                         // function g() {}
52717                                         // module.exports.g = g
52718                                         // ```
52719                                         // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
52720                                         // Naively, we would emit
52721                                         // ```
52722                                         // function g() {}
52723                                         // export const g: typeof g;
52724                                         // ```
52725                                         // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
52726                                         // the export declaration shadows it.
52727                                         // To work around that, we instead write
52728                                         // ```
52729                                         // function g() {}
52730                                         // const g_1: typeof g;
52731                                         // export { g_1 as g };
52732                                         // ```
52733                                         // To create an export named `g` that does _not_ shadow the local `g`
52734                                         addResult(ts.factory.createExportDeclaration(
52735                                         /*decorators*/ undefined, 
52736                                         /*modifiers*/ undefined, 
52737                                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* None */);
52738                                         needsExportDeclaration = false;
52739                                         needsPostExportDefault = false;
52740                                     }
52741                                 }
52742                             }
52743                         }
52744                     }
52745                     if (symbol.flags & 384 /* Enum */) {
52746                         serializeEnum(symbol, symbolName, modifierFlags);
52747                     }
52748                     if (symbol.flags & 32 /* Class */) {
52749                         if (symbol.flags & 4 /* Property */
52750                             && symbol.valueDeclaration
52751                             && ts.isBinaryExpression(symbol.valueDeclaration.parent)
52752                             && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
52753                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
52754                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
52755                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
52756                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
52757                         }
52758                         else {
52759                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
52760                         }
52761                     }
52762                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
52763                         serializeModule(symbol, symbolName, modifierFlags);
52764                     }
52765                     // The class meaning serialization should handle serializing all interface members
52766                     if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
52767                         serializeInterface(symbol, symbolName, modifierFlags);
52768                     }
52769                     if (symbol.flags & 2097152 /* Alias */) {
52770                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
52771                     }
52772                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
52773                         serializeMaybeAliasAssignment(symbol);
52774                     }
52775                     if (symbol.flags & 8388608 /* ExportStar */) {
52776                         // synthesize export * from "moduleReference"
52777                         // Straightforward - only one thing to do - make an export declaration
52778                         if (symbol.declarations) {
52779                             for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) {
52780                                 var node = _c[_i];
52781                                 var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
52782                                 if (!resolvedModule)
52783                                     continue;
52784                                 addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
52785                             }
52786                         }
52787                     }
52788                     if (needsPostExportDefault) {
52789                         addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
52790                     }
52791                     else if (needsExportDeclaration) {
52792                         addResult(ts.factory.createExportDeclaration(
52793                         /*decorators*/ undefined, 
52794                         /*modifiers*/ undefined, 
52795                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* None */);
52796                     }
52797                 }
52798                 function includePrivateSymbol(symbol) {
52799                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
52800                         return;
52801                     ts.Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
52802                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
52803                     // Blanket moving (import) aliases into the root private context should work, since imports are not valid within namespaces
52804                     // (so they must have been in the root to begin with if they were real imports) cjs `require` aliases (an upcoming feature)
52805                     // will throw a wrench in this, since those may have been nested, but we'll need to synthesize them in the outer scope
52806                     // 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
52807                     // for the moved import; which hopefully the above `getUnusedName` call should produce.
52808                     var isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !ts.some(symbol.declarations, function (d) {
52809                         return !!ts.findAncestor(d, ts.isExportDeclaration) ||
52810                             ts.isNamespaceExport(d) ||
52811                             (ts.isImportEqualsDeclaration(d) && !ts.isExternalModuleReference(d.moduleReference));
52812                     });
52813                     deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol);
52814                 }
52815                 function isExportingScope(enclosingDeclaration) {
52816                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
52817                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
52818                 }
52819                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
52820                 function addResult(node, additionalModifierFlags) {
52821                     if (ts.canHaveModifiers(node)) {
52822                         var newModifierFlags = 0 /* None */;
52823                         var enclosingDeclaration_1 = context.enclosingDeclaration &&
52824                             (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
52825                         if (additionalModifierFlags & 1 /* Export */ &&
52826                             enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) &&
52827                             canHaveExportModifier(node)) {
52828                             // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
52829                             newModifierFlags |= 1 /* Export */;
52830                         }
52831                         if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
52832                             (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) &&
52833                             (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
52834                             // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
52835                             newModifierFlags |= 2 /* Ambient */;
52836                         }
52837                         if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
52838                             newModifierFlags |= 512 /* Default */;
52839                         }
52840                         if (newModifierFlags) {
52841                             node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node));
52842                         }
52843                     }
52844                     results.push(node);
52845                 }
52846                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
52847                     var _a;
52848                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
52849                     var typeParams = getSymbolLinks(symbol).typeParameters;
52850                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
52851                     var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias);
52852                     var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined);
52853                     var oldFlags = context.flags;
52854                     context.flags |= 8388608 /* InTypeAlias */;
52855                     var oldEnclosingDecl = context.enclosingDeclaration;
52856                     context.enclosingDeclaration = jsdocAliasDecl;
52857                     var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression
52858                         && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression)
52859                         && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled)
52860                         || typeToTypeNodeHelper(aliasType, context);
52861                     addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
52862                     context.flags = oldFlags;
52863                     context.enclosingDeclaration = oldEnclosingDecl;
52864                 }
52865                 function serializeInterface(symbol, symbolName, modifierFlags) {
52866                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
52867                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
52868                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
52869                     var baseTypes = getBaseTypes(interfaceType);
52870                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
52871                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
52872                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 173 /* CallSignature */);
52873                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 174 /* ConstructSignature */);
52874                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
52875                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
52876                     addResult(ts.factory.createInterfaceDeclaration(
52877                     /*decorators*/ undefined, 
52878                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags);
52879                 }
52880                 function getNamespaceMembersForSerialization(symbol) {
52881                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
52882                 }
52883                 function isTypeOnlyNamespace(symbol) {
52884                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
52885                 }
52886                 function serializeModule(symbol, symbolName, modifierFlags) {
52887                     var members = getNamespaceMembersForSerialization(symbol);
52888                     // 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)
52889                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
52890                     var realMembers = locationMap.get("real") || ts.emptyArray;
52891                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
52892                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
52893                     // 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,
52894                     // so we don't even have placeholders to fill in.
52895                     if (ts.length(realMembers)) {
52896                         var localName = getInternalSymbolName(symbol, symbolName);
52897                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
52898                     }
52899                     if (ts.length(mergedMembers)) {
52900                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
52901                         var localName = getInternalSymbolName(symbol, symbolName);
52902                         var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(
52903                             /*decorators*/ undefined, 
52904                             /*modifiers*/ undefined, 
52905                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
52906                                 var _a, _b;
52907                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
52908                                 var localName = getInternalSymbolName(s, name);
52909                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
52910                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
52911                                     (_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);
52912                                     return undefined;
52913                                 }
52914                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
52915                                 includePrivateSymbol(target || s);
52916                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
52917                                 return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name);
52918                             })))]);
52919                         addResult(ts.factory.createModuleDeclaration(
52920                         /*decorators*/ undefined, 
52921                         /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
52922                     }
52923                 }
52924                 function serializeEnum(symbol, symbolName, modifierFlags) {
52925                     addResult(ts.factory.createEnumDeclaration(
52926                     /*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) {
52927                         // TODO: Handle computed names
52928                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
52929                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
52930                         // _on the declaration_, not on the declaration's symbol...
52931                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined;
52932                         return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined :
52933                             typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) :
52934                                 ts.factory.createNumericLiteral(initializedValue));
52935                     })), modifierFlags);
52936                 }
52937                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
52938                     var signatures = getSignaturesOfType(type, 0 /* Call */);
52939                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
52940                         var sig = signatures_2[_i];
52941                         // Each overload becomes a separate function declaration, in order
52942                         var decl = signatureToSignatureDeclarationHelper(sig, 255 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled });
52943                         addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags);
52944                     }
52945                     // Module symbol emit will take care of module-y members, provided it has exports
52946                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
52947                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
52948                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
52949                     }
52950                 }
52951                 function getSignatureTextRangeLocation(signature) {
52952                     if (signature.declaration && signature.declaration.parent) {
52953                         if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) {
52954                             return signature.declaration.parent;
52955                         }
52956                         // for expressions assigned to `var`s, use the `var` as the text range
52957                         if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) {
52958                             return signature.declaration.parent.parent;
52959                         }
52960                     }
52961                     return signature.declaration;
52962                 }
52963                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
52964                     if (ts.length(props)) {
52965                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
52966                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
52967                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
52968                             }) ? "local" : "remote";
52969                         });
52970                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
52971                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
52972                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
52973                         // Example:
52974                         // import Foo_1 = require("./exporter");
52975                         // export namespace ns {
52976                         //     import Foo = Foo_1.Foo;
52977                         //     export { Foo };
52978                         //     export const c: number;
52979                         // }
52980                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
52981                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
52982                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
52983                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
52984                         // emit akin to the above would be needed.
52985                         // Add a namespace
52986                         // Create namespace as non-synthetic so it is usable as an enclosing declaration
52987                         var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* Namespace */);
52988                         ts.setParent(fakespace, enclosingDeclaration);
52989                         fakespace.locals = ts.createSymbolTable(props);
52990                         fakespace.symbol = props[0].parent;
52991                         var oldResults = results;
52992                         results = [];
52993                         var oldAddingDeclare = addingDeclare;
52994                         addingDeclare = false;
52995                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
52996                         var oldContext = context;
52997                         context = subcontext;
52998                         // 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
52999                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
53000                         context = oldContext;
53001                         addingDeclare = oldAddingDeclare;
53002                         var declarations = results;
53003                         results = oldResults;
53004                         // replace namespace with synthetic version
53005                         var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(
53006                         /*decorators*/ undefined, 
53007                         /*modifiers*/ undefined, 
53008                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* Default */))])) : d; });
53009                         var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced;
53010                         fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped));
53011                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
53012                     }
53013                 }
53014                 function isNamespaceMember(p) {
53015                     return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
53016                         !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isStatic(p.valueDeclaration) && ts.isClassLike(p.valueDeclaration.parent));
53017                 }
53018                 function sanitizeJSDocImplements(clauses) {
53019                     var result = ts.mapDefined(clauses, function (e) {
53020                         var _a;
53021                         var oldEnclosing = context.enclosingDeclaration;
53022                         context.enclosingDeclaration = e;
53023                         var expr = e.expression;
53024                         if (ts.isEntityNameExpression(expr)) {
53025                             if (ts.isIdentifier(expr) && ts.idText(expr) === "") {
53026                                 return cleanup(/*result*/ undefined); // Empty heritage clause, should be an error, but prefer emitting no heritage clauses to reemitting the empty one
53027                             }
53028                             var introducesError = void 0;
53029                             (_a = trackExistingEntityName(expr, context, includePrivateSymbol), introducesError = _a.introducesError, expr = _a.node);
53030                             if (introducesError) {
53031                                 return cleanup(/*result*/ undefined);
53032                             }
53033                         }
53034                         return cleanup(ts.factory.createExpressionWithTypeArguments(expr, ts.map(e.typeArguments, function (a) {
53035                             return serializeExistingTypeNode(context, a, includePrivateSymbol, bundled)
53036                                 || typeToTypeNodeHelper(getTypeFromTypeNode(a), context);
53037                         })));
53038                         function cleanup(result) {
53039                             context.enclosingDeclaration = oldEnclosing;
53040                             return result;
53041                         }
53042                     });
53043                     if (result.length === clauses.length) {
53044                         return result;
53045                     }
53046                     return undefined;
53047                 }
53048                 function serializeAsClass(symbol, localName, modifierFlags) {
53049                     var _a, _b;
53050                     var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike);
53051                     var oldEnclosing = context.enclosingDeclaration;
53052                     context.enclosingDeclaration = originalDecl || oldEnclosing;
53053                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
53054                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
53055                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
53056                     var baseTypes = getBaseTypes(classType);
53057                     var originalImplements = originalDecl && ts.getEffectiveImplementsTypeNodes(originalDecl);
53058                     var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements)
53059                         || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
53060                     var staticType = getTypeOfSymbol(symbol);
53061                     var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
53062                     var staticBaseType = isClass
53063                         ? getBaseConstructorTypeOfClass(staticType)
53064                         : anyType;
53065                     var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* ImplementsKeyword */, implementsExpressions)], true);
53066                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
53067                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
53068                         // `valueDeclaration` could be undefined if inherited from
53069                         // a union/intersection base type, but inherited properties
53070                         // don't matter here.
53071                         var valueDecl = s.valueDeclaration;
53072                         return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
53073                     });
53074                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
53075                         // `valueDeclaration` could be undefined if inherited from
53076                         // a union/intersection base type, but inherited properties
53077                         // don't matter here.
53078                         var valueDecl = s.valueDeclaration;
53079                         return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
53080                     });
53081                     // Boil down all private properties into a single one.
53082                     var privateProperties = hasPrivateIdentifier ?
53083                         [ts.factory.createPropertyDeclaration(
53084                             /*decorators*/ undefined, 
53085                             /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), 
53086                             /*questionOrExclamationToken*/ undefined, 
53087                             /*type*/ undefined, 
53088                             /*initializer*/ undefined)] :
53089                         ts.emptyArray;
53090                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
53091                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
53092                     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); });
53093                     // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether
53094                     // the value is ever initialized with a class or function-like value. For cases where `X` could never be
53095                     // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable.
53096                     var isNonConstructableClassLikeInJsFile = !isClass &&
53097                         !!symbol.valueDeclaration &&
53098                         ts.isInJSFile(symbol.valueDeclaration) &&
53099                         !ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
53100                     var constructors = isNonConstructableClassLikeInJsFile ?
53101                         [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
53102                         serializeSignatures(1 /* Construct */, staticType, staticBaseType, 170 /* Constructor */);
53103                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
53104                     context.enclosingDeclaration = oldEnclosing;
53105                     addResult(ts.setTextRange(ts.factory.createClassDeclaration(
53106                     /*decorators*/ undefined, 
53107                     /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
53108                 }
53109                 function getSomeTargetNameFromDeclarations(declarations) {
53110                     return ts.firstDefined(declarations, function (d) {
53111                         if (ts.isImportSpecifier(d) || ts.isExportSpecifier(d)) {
53112                             return ts.idText(d.propertyName || d.name);
53113                         }
53114                         if (ts.isBinaryExpression(d) || ts.isExportAssignment(d)) {
53115                             var expression = ts.isExportAssignment(d) ? d.expression : d.right;
53116                             if (ts.isPropertyAccessExpression(expression)) {
53117                                 return ts.idText(expression.name);
53118                             }
53119                         }
53120                         if (isAliasSymbolDeclaration(d)) {
53121                             // This is... heuristic, at best. But it's probably better than always printing the name of the shorthand ambient module.
53122                             var name = ts.getNameOfDeclaration(d);
53123                             if (name && ts.isIdentifier(name)) {
53124                                 return ts.idText(name);
53125                             }
53126                         }
53127                         return undefined;
53128                     });
53129                 }
53130                 function serializeAsAlias(symbol, localName, modifierFlags) {
53131                     var _a, _b, _c, _d, _e;
53132                     // synthesize an alias, eg `export { symbolName as Name }`
53133                     // need to mark the alias `symbol` points at
53134                     // as something we need to serialize as a private declaration as well
53135                     var node = getDeclarationOfAliasSymbol(symbol);
53136                     if (!node)
53137                         return ts.Debug.fail();
53138                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
53139                     if (!target) {
53140                         return;
53141                     }
53142                     // If `target` refers to a shorthand module symbol, the name we're trying to pull out isn;t recoverable from the target symbol
53143                     // In such a scenario, we must fall back to looking for an alias declaration on `symbol` and pulling the target name from that
53144                     var verbatimTargetName = ts.isShorthandAmbientModuleSymbol(target) && getSomeTargetNameFromDeclarations(symbol.declarations) || ts.unescapeLeadingUnderscores(target.escapedName);
53145                     if (verbatimTargetName === "export=" /* ExportEquals */ && (ts.getESModuleInterop(compilerOptions) || compilerOptions.allowSyntheticDefaultImports)) {
53146                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
53147                         verbatimTargetName = "default" /* Default */;
53148                     }
53149                     var targetName = getInternalSymbolName(target, verbatimTargetName);
53150                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
53151                     switch (node.kind) {
53152                         case 202 /* BindingElement */:
53153                             if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 253 /* VariableDeclaration */) {
53154                                 // const { SomeClass } = require('./lib');
53155                                 var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib'
53156                                 var propertyName = node.propertyName;
53157                                 addResult(ts.factory.createImportDeclaration(
53158                                 /*decorators*/ undefined, 
53159                                 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(
53160                                     /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), 
53161                                 /*importClause*/ undefined), 0 /* None */);
53162                                 break;
53163                             }
53164                             // We don't know how to serialize this (nested?) binding element
53165                             ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
53166                             break;
53167                         case 295 /* ShorthandPropertyAssignment */:
53168                             if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 220 /* BinaryExpression */) {
53169                                 // module.exports = { SomeClass }
53170                                 serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName);
53171                             }
53172                             break;
53173                         case 253 /* VariableDeclaration */:
53174                             // commonjs require: const x = require('y')
53175                             if (ts.isPropertyAccessExpression(node.initializer)) {
53176                                 // const x = require('y').z
53177                                 var initializer = node.initializer; // require('y').z
53178                                 var uniqueName = ts.factory.createUniqueName(localName); // _x
53179                                 var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y'
53180                                 // import _x = require('y');
53181                                 addResult(ts.factory.createImportEqualsDeclaration(
53182                                 /*decorators*/ undefined, 
53183                                 /*modifiers*/ undefined, 
53184                                 /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
53185                                 // import x = _x.z
53186                                 addResult(ts.factory.createImportEqualsDeclaration(
53187                                 /*decorators*/ undefined, 
53188                                 /*modifiers*/ undefined, 
53189                                 /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
53190                                 break;
53191                             }
53192                         // else fall through and treat commonjs require just like import=
53193                         case 264 /* ImportEqualsDeclaration */:
53194                             // This _specifically_ only exists to handle json declarations - where we make aliases, but since
53195                             // we emit no declarations for the json document, must not refer to it in the declarations
53196                             if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) {
53197                                 serializeMaybeAliasAssignment(symbol);
53198                                 break;
53199                             }
53200                             // Could be a local `import localName = ns.member` or
53201                             // an external `import localName = require("whatever")`
53202                             var isLocalImport = !(target.flags & 512 /* ValueModule */) && !ts.isVariableDeclaration(node);
53203                             addResult(ts.factory.createImportEqualsDeclaration(
53204                             /*decorators*/ undefined, 
53205                             /*modifiers*/ undefined, 
53206                             /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport
53207                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
53208                                 : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */);
53209                             break;
53210                         case 263 /* NamespaceExportDeclaration */:
53211                             // export as namespace foo
53212                             // TODO: Not part of a file's local or export symbol tables
53213                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
53214                             addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
53215                             break;
53216                         case 266 /* ImportClause */:
53217                             addResult(ts.factory.createImportDeclaration(
53218                             /*decorators*/ undefined, 
53219                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), 
53220                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
53221                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
53222                             // In such cases, the `target` refers to the module itself already
53223                             ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), 
53224                             /*assertClause*/ undefined), 0 /* None */);
53225                             break;
53226                         case 267 /* NamespaceImport */:
53227                             addResult(ts.factory.createImportDeclaration(
53228                             /*decorators*/ undefined, 
53229                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), 
53230                             /*assertClause*/ undefined), 0 /* None */);
53231                             break;
53232                         case 273 /* NamespaceExport */:
53233                             addResult(ts.factory.createExportDeclaration(
53234                             /*decorators*/ undefined, 
53235                             /*modifiers*/ undefined, 
53236                             /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
53237                             break;
53238                         case 269 /* ImportSpecifier */:
53239                             addResult(ts.factory.createImportDeclaration(
53240                             /*decorators*/ undefined, 
53241                             /*modifiers*/ undefined, ts.factory.createImportClause(
53242                             /*isTypeOnly*/ false, 
53243                             /*importClause*/ undefined, ts.factory.createNamedImports([
53244                                 ts.factory.createImportSpecifier(
53245                                 /*isTypeOnly*/ false, localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName))
53246                             ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), 
53247                             /*assertClause*/ undefined), 0 /* None */);
53248                             break;
53249                         case 274 /* ExportSpecifier */:
53250                             // does not use localName because the symbol name in this case refers to the name in the exports table,
53251                             // which we must exactly preserve
53252                             var specifier = node.parent.parent.moduleSpecifier;
53253                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
53254                             // another file
53255                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined);
53256                             break;
53257                         case 270 /* ExportAssignment */:
53258                             serializeMaybeAliasAssignment(symbol);
53259                             break;
53260                         case 220 /* BinaryExpression */:
53261                         case 205 /* PropertyAccessExpression */:
53262                         case 206 /* ElementAccessExpression */:
53263                             // Could be best encoded as though an export specifier or as though an export assignment
53264                             // If name is default or export=, do an export assignment
53265                             // Otherwise do an export specifier
53266                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
53267                                 serializeMaybeAliasAssignment(symbol);
53268                             }
53269                             else {
53270                                 serializeExportSpecifier(localName, targetName);
53271                             }
53272                             break;
53273                         default:
53274                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
53275                     }
53276                 }
53277                 function serializeExportSpecifier(localName, targetName, specifier) {
53278                     addResult(ts.factory.createExportDeclaration(
53279                     /*decorators*/ undefined, 
53280                     /*modifiers*/ undefined, 
53281                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
53282                 }
53283                 /**
53284                  * Returns `true` if an export assignment or declaration was produced for the symbol
53285                  */
53286                 function serializeMaybeAliasAssignment(symbol) {
53287                     if (symbol.flags & 4194304 /* Prototype */) {
53288                         return false;
53289                     }
53290                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
53291                     var isExportEquals = name === "export=" /* ExportEquals */;
53292                     var isDefault = name === "default" /* Default */;
53293                     var isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
53294                     // synthesize export = ref
53295                     // ref should refer to either be a locally scoped symbol which we need to emit, or
53296                     // a reference to another namespace/module which we may need to emit an `import` statement for
53297                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
53298                     // serialize what the alias points to, preserve the declaration's initializer
53299                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
53300                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
53301                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
53302                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
53303                         // eg, `namespace A { export class B {} }; exports = A.B;`
53304                         // Technically, this is all that's required in the case where the assignment is an entity name expression
53305                         var expr = aliasDecl && ((ts.isExportAssignment(aliasDecl) || ts.isBinaryExpression(aliasDecl)) ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl));
53306                         var first_1 = expr && ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
53307                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
53308                         if (referenced || target) {
53309                             includePrivateSymbol(referenced || target);
53310                         }
53311                         // We disable the context's symbol tracker for the duration of this name serialization
53312                         // as, by virtue of being here, the name is required to print something, and we don't want to
53313                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
53314                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
53315                         // into the containing scope anyway, so we want to skip the visibility checks.
53316                         var oldTrack = context.tracker.trackSymbol;
53317                         context.tracker.trackSymbol = function () { return false; };
53318                         if (isExportAssignmentCompatibleSymbolName) {
53319                             results.push(ts.factory.createExportAssignment(
53320                             /*decorators*/ undefined, 
53321                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
53322                         }
53323                         else {
53324                             if (first_1 === expr && first_1) {
53325                                 // serialize as `export {target as name}`
53326                                 serializeExportSpecifier(name, ts.idText(first_1));
53327                             }
53328                             else if (expr && ts.isClassExpression(expr)) {
53329                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
53330                             }
53331                             else {
53332                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
53333                                 var varName = getUnusedName(name, symbol);
53334                                 addResult(ts.factory.createImportEqualsDeclaration(
53335                                 /*decorators*/ undefined, 
53336                                 /*modifiers*/ undefined, 
53337                                 /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
53338                                 serializeExportSpecifier(name, varName);
53339                             }
53340                         }
53341                         context.tracker.trackSymbol = oldTrack;
53342                         return true;
53343                     }
53344                     else {
53345                         // serialize as an anonymous property declaration
53346                         var varName = getUnusedName(name, symbol);
53347                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
53348                         // (Unwidened types can only exist in expression contexts and should never be serialized)
53349                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
53350                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
53351                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
53352                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 1 /* Export */);
53353                         }
53354                         else {
53355                             var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
53356                                 ts.factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
53357                             ], 2 /* Const */));
53358                             // Inlined JSON types exported with [module.]exports= will already emit an export=, so should use `declare`.
53359                             // Otherwise, the type itself should be exported.
53360                             addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */
53361                                 : name === varName ? 1 /* Export */
53362                                     : 0 /* None */);
53363                         }
53364                         if (isExportAssignmentCompatibleSymbolName) {
53365                             results.push(ts.factory.createExportAssignment(
53366                             /*decorators*/ undefined, 
53367                             /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName)));
53368                             return true;
53369                         }
53370                         else if (name !== varName) {
53371                             serializeExportSpecifier(name, varName);
53372                             return true;
53373                         }
53374                         return false;
53375                     }
53376                 }
53377                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
53378                     // Only object types which are not constructable, or indexable, whose members all come from the
53379                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
53380                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
53381                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
53382                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
53383                         !ts.length(getIndexInfosOfType(typeToSerialize)) &&
53384                         !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
53385                         !!(ts.length(ts.filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
53386                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
53387                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
53388                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
53389                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
53390                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
53391                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion); });
53392                 }
53393                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
53394                     return function serializePropertySymbol(p, isStatic, baseType) {
53395                         var _a, _b, _c, _d, _e;
53396                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
53397                         var isPrivate = !!(modifierFlags & 8 /* Private */);
53398                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
53399                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
53400                             // need to be merged namespace members
53401                             return [];
53402                         }
53403                         if (p.flags & 4194304 /* Prototype */ ||
53404                             (baseType && getPropertyOfType(baseType, p.escapedName)
53405                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
53406                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
53407                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
53408                             return [];
53409                         }
53410                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
53411                         var name = getPropertyNameNodeForSymbol(p, context);
53412                         var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
53413                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
53414                             var result = [];
53415                             if (p.flags & 65536 /* SetAccessor */) {
53416                                 result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(
53417                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(
53418                                     /*decorators*/ undefined, 
53419                                     /*modifiers*/ undefined, 
53420                                     /*dotDotDotToken*/ undefined, "arg", 
53421                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
53422                                 /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl));
53423                             }
53424                             if (p.flags & 32768 /* GetAccessor */) {
53425                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
53426                                 result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(
53427                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
53428                                 /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl));
53429                             }
53430                             return result;
53431                         }
53432                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
53433                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
53434                         else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
53435                             return ts.setTextRange(createProperty(
53436                             /*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), 
53437                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
53438                             // interface members can't have initializers, however class members _can_
53439                             /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl);
53440                         }
53441                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
53442                             var type = getTypeOfSymbol(p);
53443                             var signatures = getSignaturesOfType(type, 0 /* Call */);
53444                             if (flag & 8 /* Private */) {
53445                                 return ts.setTextRange(createProperty(
53446                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, 
53447                                 /*type*/ undefined, 
53448                                 /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]);
53449                             }
53450                             var results_1 = [];
53451                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
53452                                 var sig = signatures_3[_i];
53453                                 // Each overload becomes a separate method declaration, in order
53454                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, {
53455                                     name: name,
53456                                     questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
53457                                     modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined
53458                                 });
53459                                 var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration;
53460                                 results_1.push(ts.setTextRange(decl, location));
53461                             }
53462                             return results_1;
53463                         }
53464                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
53465                         return ts.Debug.fail("Unhandled class member kind! ".concat(p.__debugFlags || p.flags));
53466                     };
53467                 }
53468                 function serializePropertySymbolForInterface(p, baseType) {
53469                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
53470                 }
53471                 function serializeSignatures(kind, input, baseType, outputKind) {
53472                     var signatures = getSignaturesOfType(input, kind);
53473                     if (kind === 1 /* Construct */) {
53474                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
53475                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
53476                         }
53477                         if (baseType) {
53478                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
53479                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
53480                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
53481                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
53482                             }
53483                             if (baseSigs.length === signatures.length) {
53484                                 var failed = false;
53485                                 for (var i = 0; i < baseSigs.length; i++) {
53486                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
53487                                         failed = true;
53488                                         break;
53489                                     }
53490                                 }
53491                                 if (!failed) {
53492                                     return []; // Every signature was identical - elide constructor list as it is inherited
53493                                 }
53494                             }
53495                         }
53496                         var privateProtected = 0;
53497                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
53498                             var s = signatures_4[_i];
53499                             if (s.declaration) {
53500                                 privateProtected |= ts.getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
53501                             }
53502                         }
53503                         if (privateProtected) {
53504                             return [ts.setTextRange(ts.factory.createConstructorDeclaration(
53505                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), 
53506                                 /*parameters*/ [], 
53507                                 /*body*/ undefined), signatures[0].declaration)];
53508                         }
53509                     }
53510                     var results = [];
53511                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
53512                         var sig = signatures_5[_a];
53513                         // Each overload becomes a separate constructor declaration, in order
53514                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
53515                         results.push(ts.setTextRange(decl, sig.declaration));
53516                     }
53517                     return results;
53518                 }
53519                 function serializeIndexSignatures(input, baseType) {
53520                     var results = [];
53521                     for (var _i = 0, _a = getIndexInfosOfType(input); _i < _a.length; _i++) {
53522                         var info = _a[_i];
53523                         if (baseType) {
53524                             var baseInfo = getIndexInfoOfType(baseType, info.keyType);
53525                             if (baseInfo) {
53526                                 if (isTypeIdenticalTo(info.type, baseInfo.type)) {
53527                                     continue; // elide identical index signatures
53528                                 }
53529                             }
53530                         }
53531                         results.push(indexInfoToIndexSignatureDeclarationHelper(info, context, /*typeNode*/ undefined));
53532                     }
53533                     return results;
53534                 }
53535                 function serializeBaseType(t, staticType, rootName) {
53536                     var ref = trySerializeAsTypeReference(t, 111551 /* Value */);
53537                     if (ref) {
53538                         return ref;
53539                     }
53540                     var tempName = getUnusedName("".concat(rootName, "_base"));
53541                     var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
53542                         ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context))
53543                     ], 2 /* Const */));
53544                     addResult(statement, 0 /* None */);
53545                     return ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier(tempName), /*typeArgs*/ undefined);
53546                 }
53547                 function trySerializeAsTypeReference(t, flags) {
53548                     var typeArgs;
53549                     var reference;
53550                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
53551                     // which we can't write out in a syntactically valid way as an expression
53552                     if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
53553                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
53554                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
53555                     }
53556                     else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
53557                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
53558                     }
53559                     if (reference) {
53560                         return ts.factory.createExpressionWithTypeArguments(reference, typeArgs);
53561                     }
53562                 }
53563                 function serializeImplementedType(t) {
53564                     var ref = trySerializeAsTypeReference(t, 788968 /* Type */);
53565                     if (ref) {
53566                         return ref;
53567                     }
53568                     if (t.symbol) {
53569                         return ts.factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArgs*/ undefined);
53570                     }
53571                 }
53572                 function getUnusedName(input, symbol) {
53573                     var _a, _b;
53574                     var id = symbol ? getSymbolId(symbol) : undefined;
53575                     if (id) {
53576                         if (context.remappedSymbolNames.has(id)) {
53577                             return context.remappedSymbolNames.get(id);
53578                         }
53579                     }
53580                     if (symbol) {
53581                         input = getNameCandidateWorker(symbol, input);
53582                     }
53583                     var i = 0;
53584                     var original = input;
53585                     while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) {
53586                         i++;
53587                         input = "".concat(original, "_").concat(i);
53588                     }
53589                     (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input);
53590                     if (id) {
53591                         context.remappedSymbolNames.set(id, input);
53592                     }
53593                     return input;
53594                 }
53595                 function getNameCandidateWorker(symbol, localName) {
53596                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
53597                         var flags = context.flags;
53598                         context.flags |= 16777216 /* InInitialEntityName */;
53599                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
53600                         context.flags = flags;
53601                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
53602                     }
53603                     if (localName === "default" /* Default */) {
53604                         localName = "_default";
53605                     }
53606                     else if (localName === "export=" /* ExportEquals */) {
53607                         localName = "_exports";
53608                     }
53609                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
53610                     return localName;
53611                 }
53612                 function getInternalSymbolName(symbol, localName) {
53613                     var id = getSymbolId(symbol);
53614                     if (context.remappedSymbolNames.has(id)) {
53615                         return context.remappedSymbolNames.get(id);
53616                     }
53617                     localName = getNameCandidateWorker(symbol, localName);
53618                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
53619                     context.remappedSymbolNames.set(id, localName);
53620                     return localName;
53621                 }
53622             }
53623         }
53624         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
53625             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
53626             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
53627             function typePredicateToStringWorker(writer) {
53628                 var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createToken(128 /* 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
53629                 );
53630                 var printer = ts.createPrinter({ removeComments: true });
53631                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
53632                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
53633                 return writer;
53634             }
53635         }
53636         function formatUnionTypes(types) {
53637             var result = [];
53638             var flags = 0;
53639             for (var i = 0; i < types.length; i++) {
53640                 var t = types[i];
53641                 flags |= t.flags;
53642                 if (!(t.flags & 98304 /* Nullable */)) {
53643                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
53644                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
53645                         if (baseType.flags & 1048576 /* Union */) {
53646                             var count = baseType.types.length;
53647                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
53648                                 result.push(baseType);
53649                                 i += count - 1;
53650                                 continue;
53651                             }
53652                         }
53653                     }
53654                     result.push(t);
53655                 }
53656             }
53657             if (flags & 65536 /* Null */)
53658                 result.push(nullType);
53659             if (flags & 32768 /* Undefined */)
53660                 result.push(undefinedType);
53661             return result || types;
53662         }
53663         function visibilityToString(flags) {
53664             if (flags === 8 /* Private */) {
53665                 return "private";
53666             }
53667             if (flags === 16 /* Protected */) {
53668                 return "protected";
53669             }
53670             return "public";
53671         }
53672         function getTypeAliasForTypeLiteral(type) {
53673             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) {
53674                 var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
53675                 if (node.kind === 258 /* TypeAliasDeclaration */) {
53676                     return getSymbolOfNode(node);
53677                 }
53678             }
53679             return undefined;
53680         }
53681         function isTopLevelInExternalModuleAugmentation(node) {
53682             return node && node.parent &&
53683                 node.parent.kind === 261 /* ModuleBlock */ &&
53684                 ts.isExternalModuleAugmentation(node.parent.parent);
53685         }
53686         function isDefaultBindingContext(location) {
53687             return location.kind === 303 /* SourceFile */ || ts.isAmbientModule(location);
53688         }
53689         function getNameOfSymbolFromNameType(symbol, context) {
53690             var nameType = getSymbolLinks(symbol).nameType;
53691             if (nameType) {
53692                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
53693                     var name = "" + nameType.value;
53694                     if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) {
53695                         return "\"".concat(ts.escapeString(name, 34 /* doubleQuote */), "\"");
53696                     }
53697                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
53698                         return "[".concat(name, "]");
53699                     }
53700                     return name;
53701                 }
53702                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
53703                     return "[".concat(getNameOfSymbolAsWritten(nameType.symbol, context), "]");
53704                 }
53705             }
53706         }
53707         /**
53708          * Gets a human-readable name for a symbol.
53709          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
53710          *
53711          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
53712          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
53713          */
53714         function getNameOfSymbolAsWritten(symbol, context) {
53715             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
53716                 // If it's not the first part of an entity name, it must print as `default`
53717                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
53718                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
53719                     !symbol.declarations ||
53720                     // if not in the same binding context (source file, module declaration), it must print as `default`
53721                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
53722                 return "default";
53723             }
53724             if (symbol.declarations && symbol.declarations.length) {
53725                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
53726                 var name_3 = declaration && ts.getNameOfDeclaration(declaration);
53727                 if (declaration && name_3) {
53728                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
53729                         return ts.symbolName(symbol);
53730                     }
53731                     if (ts.isComputedPropertyName(name_3) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
53732                         var nameType = getSymbolLinks(symbol).nameType;
53733                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
53734                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
53735                             var result = getNameOfSymbolFromNameType(symbol, context);
53736                             if (result !== undefined) {
53737                                 return result;
53738                             }
53739                         }
53740                     }
53741                     return ts.declarationNameToString(name_3);
53742                 }
53743                 if (!declaration) {
53744                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
53745                 }
53746                 if (declaration.parent && declaration.parent.kind === 253 /* VariableDeclaration */) {
53747                     return ts.declarationNameToString(declaration.parent.name);
53748                 }
53749                 switch (declaration.kind) {
53750                     case 225 /* ClassExpression */:
53751                     case 212 /* FunctionExpression */:
53752                     case 213 /* ArrowFunction */:
53753                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
53754                             context.encounteredError = true;
53755                         }
53756                         return declaration.kind === 225 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
53757                 }
53758             }
53759             var name = getNameOfSymbolFromNameType(symbol, context);
53760             return name !== undefined ? name : ts.symbolName(symbol);
53761         }
53762         function isDeclarationVisible(node) {
53763             if (node) {
53764                 var links = getNodeLinks(node);
53765                 if (links.isVisible === undefined) {
53766                     links.isVisible = !!determineIfDeclarationIsVisible();
53767                 }
53768                 return links.isVisible;
53769             }
53770             return false;
53771             function determineIfDeclarationIsVisible() {
53772                 switch (node.kind) {
53773                     case 336 /* JSDocCallbackTag */:
53774                     case 343 /* JSDocTypedefTag */:
53775                     case 337 /* JSDocEnumTag */:
53776                         // Top-level jsdoc type aliases are considered exported
53777                         // 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
53778                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
53779                     case 202 /* BindingElement */:
53780                         return isDeclarationVisible(node.parent.parent);
53781                     case 253 /* VariableDeclaration */:
53782                         if (ts.isBindingPattern(node.name) &&
53783                             !node.name.elements.length) {
53784                             // If the binding pattern is empty, this variable declaration is not visible
53785                             return false;
53786                         }
53787                     // falls through
53788                     case 260 /* ModuleDeclaration */:
53789                     case 256 /* ClassDeclaration */:
53790                     case 257 /* InterfaceDeclaration */:
53791                     case 258 /* TypeAliasDeclaration */:
53792                     case 255 /* FunctionDeclaration */:
53793                     case 259 /* EnumDeclaration */:
53794                     case 264 /* ImportEqualsDeclaration */:
53795                         // external module augmentation is always visible
53796                         if (ts.isExternalModuleAugmentation(node)) {
53797                             return true;
53798                         }
53799                         var parent = getDeclarationContainer(node);
53800                         // If the node is not exported or it is not ambient module element (except import declaration)
53801                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
53802                             !(node.kind !== 264 /* ImportEqualsDeclaration */ && parent.kind !== 303 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
53803                             return isGlobalSourceFile(parent);
53804                         }
53805                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
53806                         return isDeclarationVisible(parent);
53807                     case 166 /* PropertyDeclaration */:
53808                     case 165 /* PropertySignature */:
53809                     case 171 /* GetAccessor */:
53810                     case 172 /* SetAccessor */:
53811                     case 168 /* MethodDeclaration */:
53812                     case 167 /* MethodSignature */:
53813                         if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) {
53814                             // Private/protected properties/methods are not visible
53815                             return false;
53816                         }
53817                     // Public properties/methods are visible if its parents are visible, so:
53818                     // falls through
53819                     case 170 /* Constructor */:
53820                     case 174 /* ConstructSignature */:
53821                     case 173 /* CallSignature */:
53822                     case 175 /* IndexSignature */:
53823                     case 163 /* Parameter */:
53824                     case 261 /* ModuleBlock */:
53825                     case 178 /* FunctionType */:
53826                     case 179 /* ConstructorType */:
53827                     case 181 /* TypeLiteral */:
53828                     case 177 /* TypeReference */:
53829                     case 182 /* ArrayType */:
53830                     case 183 /* TupleType */:
53831                     case 186 /* UnionType */:
53832                     case 187 /* IntersectionType */:
53833                     case 190 /* ParenthesizedType */:
53834                     case 196 /* NamedTupleMember */:
53835                         return isDeclarationVisible(node.parent);
53836                     // Default binding, import specifier and namespace import is visible
53837                     // only on demand so by default it is not visible
53838                     case 266 /* ImportClause */:
53839                     case 267 /* NamespaceImport */:
53840                     case 269 /* ImportSpecifier */:
53841                         return false;
53842                     // Type parameters are always visible
53843                     case 162 /* TypeParameter */:
53844                     // Source file and namespace export are always visible
53845                     // falls through
53846                     case 303 /* SourceFile */:
53847                     case 263 /* NamespaceExportDeclaration */:
53848                         return true;
53849                     // Export assignments do not create name bindings outside the module
53850                     case 270 /* ExportAssignment */:
53851                         return false;
53852                     default:
53853                         return false;
53854                 }
53855             }
53856         }
53857         function collectLinkedAliases(node, setVisibility) {
53858             var exportSymbol;
53859             if (node.parent && node.parent.kind === 270 /* ExportAssignment */) {
53860                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
53861             }
53862             else if (node.parent.kind === 274 /* ExportSpecifier */) {
53863                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
53864             }
53865             var result;
53866             var visited;
53867             if (exportSymbol) {
53868                 visited = new ts.Set();
53869                 visited.add(getSymbolId(exportSymbol));
53870                 buildVisibleNodeList(exportSymbol.declarations);
53871             }
53872             return result;
53873             function buildVisibleNodeList(declarations) {
53874                 ts.forEach(declarations, function (declaration) {
53875                     var resultNode = getAnyImportSyntax(declaration) || declaration;
53876                     if (setVisibility) {
53877                         getNodeLinks(declaration).isVisible = true;
53878                     }
53879                     else {
53880                         result = result || [];
53881                         ts.pushIfUnique(result, resultNode);
53882                     }
53883                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
53884                         // Add the referenced top container visible
53885                         var internalModuleReference = declaration.moduleReference;
53886                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
53887                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
53888                         if (importSymbol && visited) {
53889                             if (ts.tryAddToSet(visited, getSymbolId(importSymbol))) {
53890                                 buildVisibleNodeList(importSymbol.declarations);
53891                             }
53892                         }
53893                     }
53894                 });
53895             }
53896         }
53897         /**
53898          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
53899          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
53900          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
53901          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
53902          * In order to see if the same query has already been done before, the target object and the propertyName both
53903          * must match the one passed in.
53904          *
53905          * @param target The symbol, type, or signature whose type is being queried
53906          * @param propertyName The property name that should be used to query the target for its type
53907          */
53908         function pushTypeResolution(target, propertyName) {
53909             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
53910             if (resolutionCycleStartIndex >= 0) {
53911                 // A cycle was found
53912                 var length_3 = resolutionTargets.length;
53913                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
53914                     resolutionResults[i] = false;
53915                 }
53916                 return false;
53917             }
53918             resolutionTargets.push(target);
53919             resolutionResults.push(/*items*/ true);
53920             resolutionPropertyNames.push(propertyName);
53921             return true;
53922         }
53923         function findResolutionCycleStartIndex(target, propertyName) {
53924             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
53925                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
53926                     return -1;
53927                 }
53928                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
53929                     return i;
53930                 }
53931             }
53932             return -1;
53933         }
53934         function hasType(target, propertyName) {
53935             switch (propertyName) {
53936                 case 0 /* Type */:
53937                     return !!getSymbolLinks(target).type;
53938                 case 5 /* EnumTagType */:
53939                     return !!(getNodeLinks(target).resolvedEnumType);
53940                 case 2 /* DeclaredType */:
53941                     return !!getSymbolLinks(target).declaredType;
53942                 case 1 /* ResolvedBaseConstructorType */:
53943                     return !!target.resolvedBaseConstructorType;
53944                 case 3 /* ResolvedReturnType */:
53945                     return !!target.resolvedReturnType;
53946                 case 4 /* ImmediateBaseConstraint */:
53947                     return !!target.immediateBaseConstraint;
53948                 case 6 /* ResolvedTypeArguments */:
53949                     return !!target.resolvedTypeArguments;
53950                 case 7 /* ResolvedBaseTypes */:
53951                     return !!target.baseTypesResolved;
53952             }
53953             return ts.Debug.assertNever(propertyName);
53954         }
53955         /**
53956          * Pop an entry from the type resolution stack and return its associated result value. The result value will
53957          * be true if no circularities were detected, or false if a circularity was found.
53958          */
53959         function popTypeResolution() {
53960             resolutionTargets.pop();
53961             resolutionPropertyNames.pop();
53962             return resolutionResults.pop();
53963         }
53964         function getDeclarationContainer(node) {
53965             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
53966                 switch (node.kind) {
53967                     case 253 /* VariableDeclaration */:
53968                     case 254 /* VariableDeclarationList */:
53969                     case 269 /* ImportSpecifier */:
53970                     case 268 /* NamedImports */:
53971                     case 267 /* NamespaceImport */:
53972                     case 266 /* ImportClause */:
53973                         return false;
53974                     default:
53975                         return true;
53976                 }
53977             }).parent;
53978         }
53979         function getTypeOfPrototypeProperty(prototype) {
53980             // TypeScript 1.0 spec (April 2014): 8.4
53981             // Every class automatically contains a static property member named 'prototype',
53982             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
53983             // It is an error to explicitly declare a static property member with the name 'prototype'.
53984             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
53985             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
53986         }
53987         // Return the type of the given property in the given type, or undefined if no such property exists
53988         function getTypeOfPropertyOfType(type, name) {
53989             var prop = getPropertyOfType(type, name);
53990             return prop ? getTypeOfSymbol(prop) : undefined;
53991         }
53992         function getTypeOfPropertyOrIndexSignature(type, name) {
53993             var _a;
53994             return getTypeOfPropertyOfType(type, name) || ((_a = getApplicableIndexInfoForName(type, name)) === null || _a === void 0 ? void 0 : _a.type) || unknownType;
53995         }
53996         function isTypeAny(type) {
53997             return type && (type.flags & 1 /* Any */) !== 0;
53998         }
53999         function isErrorType(type) {
54000             // The only 'any' types that have alias symbols are those manufactured by getTypeFromTypeAliasReference for
54001             // a reference to an unresolved symbol. We want those to behave like the errorType.
54002             return type === errorType || !!(type.flags & 1 /* Any */ && type.aliasSymbol);
54003         }
54004         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
54005         // assigned by contextual typing.
54006         function getTypeForBindingElementParent(node) {
54007             var symbol = getSymbolOfNode(node);
54008             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
54009         }
54010         function getRestType(source, properties, symbol) {
54011             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
54012             if (source.flags & 131072 /* Never */) {
54013                 return emptyObjectType;
54014             }
54015             if (source.flags & 1048576 /* Union */) {
54016                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
54017             }
54018             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
54019             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
54020                 if (omitKeyType.flags & 131072 /* Never */) {
54021                     return source;
54022                 }
54023                 var omitTypeAlias = getGlobalOmitSymbol();
54024                 if (!omitTypeAlias) {
54025                     return errorType;
54026                 }
54027                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
54028             }
54029             var members = ts.createSymbolTable();
54030             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
54031                 var prop = _a[_i];
54032                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
54033                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
54034                     && isSpreadableProperty(prop)) {
54035                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
54036                 }
54037             }
54038             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfosOfType(source));
54039             result.objectFlags |= 8388608 /* ObjectRestType */;
54040             return result;
54041         }
54042         function isGenericTypeWithUndefinedConstraint(type) {
54043             return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */);
54044         }
54045         function getNonUndefinedType(type) {
54046             var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type;
54047             return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */);
54048         }
54049         // Determine the control flow type associated with a destructuring declaration or assignment. The following
54050         // forms of destructuring are possible:
54051         //   let { x } = obj;  // BindingElement
54052         //   let [ x ] = obj;  // BindingElement
54053         //   { x } = obj;      // ShorthandPropertyAssignment
54054         //   { x: v } = obj;   // PropertyAssignment
54055         //   [ x ] = obj;      // Expression
54056         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
54057         // flow analyzer doesn't have to handle all the different syntactic forms.
54058         function getFlowTypeOfDestructuring(node, declaredType) {
54059             var reference = getSyntheticElementAccess(node);
54060             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
54061         }
54062         function getSyntheticElementAccess(node) {
54063             var parentAccess = getParentElementAccess(node);
54064             if (parentAccess && parentAccess.flowNode) {
54065                 var propName = getDestructuringPropertyName(node);
54066                 if (propName) {
54067                     var literal = ts.setTextRange(ts.parseNodeFactory.createStringLiteral(propName), node);
54068                     var lhsExpr = ts.isLeftHandSideExpression(parentAccess) ? parentAccess : ts.parseNodeFactory.createParenthesizedExpression(parentAccess);
54069                     var result = ts.setTextRange(ts.parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
54070                     ts.setParent(literal, result);
54071                     ts.setParent(result, node);
54072                     if (lhsExpr !== parentAccess) {
54073                         ts.setParent(lhsExpr, result);
54074                     }
54075                     result.flowNode = parentAccess.flowNode;
54076                     return result;
54077                 }
54078             }
54079         }
54080         function getParentElementAccess(node) {
54081             var ancestor = node.parent.parent;
54082             switch (ancestor.kind) {
54083                 case 202 /* BindingElement */:
54084                 case 294 /* PropertyAssignment */:
54085                     return getSyntheticElementAccess(ancestor);
54086                 case 203 /* ArrayLiteralExpression */:
54087                     return getSyntheticElementAccess(node.parent);
54088                 case 253 /* VariableDeclaration */:
54089                     return ancestor.initializer;
54090                 case 220 /* BinaryExpression */:
54091                     return ancestor.right;
54092             }
54093         }
54094         function getDestructuringPropertyName(node) {
54095             var parent = node.parent;
54096             if (node.kind === 202 /* BindingElement */ && parent.kind === 200 /* ObjectBindingPattern */) {
54097                 return getLiteralPropertyNameText(node.propertyName || node.name);
54098             }
54099             if (node.kind === 294 /* PropertyAssignment */ || node.kind === 295 /* ShorthandPropertyAssignment */) {
54100                 return getLiteralPropertyNameText(node.name);
54101             }
54102             return "" + parent.elements.indexOf(node);
54103         }
54104         function getLiteralPropertyNameText(name) {
54105             var type = getLiteralTypeFromPropertyName(name);
54106             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
54107         }
54108         /** Return the inferred type for a binding element */
54109         function getTypeForBindingElement(declaration) {
54110             var pattern = declaration.parent;
54111             var parentType = getTypeForBindingElementParent(pattern.parent);
54112             // If no type or an any type was inferred for parent, infer that for the binding element
54113             if (!parentType || isTypeAny(parentType)) {
54114                 return parentType;
54115             }
54116             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
54117             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
54118                 parentType = getNonNullableType(parentType);
54119             }
54120             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
54121             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
54122                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
54123             }
54124             var type;
54125             if (pattern.kind === 200 /* ObjectBindingPattern */) {
54126                 if (declaration.dotDotDotToken) {
54127                     parentType = getReducedType(parentType);
54128                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
54129                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
54130                         return errorType;
54131                     }
54132                     var literalMembers = [];
54133                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
54134                         var element = _a[_i];
54135                         if (!element.dotDotDotToken) {
54136                             literalMembers.push(element.propertyName || element.name);
54137                         }
54138                     }
54139                     type = getRestType(parentType, literalMembers, declaration.symbol);
54140                 }
54141                 else {
54142                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
54143                     var name = declaration.propertyName || declaration.name;
54144                     var indexType = getLiteralTypeFromPropertyName(name);
54145                     var declaredType = getIndexedAccessType(parentType, indexType, 32 /* ExpressionPosition */, name);
54146                     type = getFlowTypeOfDestructuring(declaration, declaredType);
54147                 }
54148             }
54149             else {
54150                 // This elementType will be used if the specific property corresponding to this index is not
54151                 // present (aka the tuple element property). This call also checks that the parentType is in
54152                 // fact an iterable or array (depending on target language).
54153                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
54154                 var index_2 = pattern.elements.indexOf(declaration);
54155                 if (declaration.dotDotDotToken) {
54156                     // If the parent is a tuple type, the rest element has a tuple type of the
54157                     // remaining tuple element types. Otherwise, the rest element has an array type with same
54158                     // element type as the parent type.
54159                     type = everyType(parentType, isTupleType) ?
54160                         mapType(parentType, function (t) { return sliceTupleType(t, index_2); }) :
54161                         createArrayType(elementType);
54162                 }
54163                 else if (isArrayLikeType(parentType)) {
54164                     var indexType = getNumberLiteralType(index_2);
54165                     var accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(declaration) ? 16 /* NoTupleBoundsCheck */ : 0);
54166                     var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType;
54167                     type = getFlowTypeOfDestructuring(declaration, declaredType);
54168                 }
54169                 else {
54170                     type = elementType;
54171                 }
54172             }
54173             if (!declaration.initializer) {
54174                 return type;
54175             }
54176             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
54177                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
54178                 // undefined from the final type.
54179                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type;
54180             }
54181             return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
54182         }
54183         function getTypeForDeclarationFromJSDocComment(declaration) {
54184             var jsdocType = ts.getJSDocType(declaration);
54185             if (jsdocType) {
54186                 return getTypeFromTypeNode(jsdocType);
54187             }
54188             return undefined;
54189         }
54190         function isNullOrUndefined(node) {
54191             var expr = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true);
54192             return expr.kind === 104 /* NullKeyword */ || expr.kind === 79 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
54193         }
54194         function isEmptyArrayLiteral(node) {
54195             var expr = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true);
54196             return expr.kind === 203 /* ArrayLiteralExpression */ && expr.elements.length === 0;
54197         }
54198         function addOptionality(type, isProperty, isOptional) {
54199             if (isProperty === void 0) { isProperty = false; }
54200             if (isOptional === void 0) { isOptional = true; }
54201             return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type;
54202         }
54203         // Return the inferred type for a variable, parameter, or property declaration
54204         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
54205             // A variable declared in a for..in statement is of type string, or of type keyof T when the
54206             // right hand expression is of a type parameter type.
54207             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 242 /* ForInStatement */) {
54208                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
54209                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
54210             }
54211             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 243 /* ForOfStatement */) {
54212                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
54213                 // missing properties/signatures required to get its iteratedType (like
54214                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
54215                 // or it may have led to an error inside getElementTypeOfIterable.
54216                 var forOfStatement = declaration.parent.parent;
54217                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
54218             }
54219             if (ts.isBindingPattern(declaration.parent)) {
54220                 return getTypeForBindingElement(declaration);
54221             }
54222             var isProperty = ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration);
54223             var isOptional = includeOptionality && (isProperty && !!declaration.questionToken ||
54224                 ts.isParameter(declaration) && (!!declaration.questionToken || isJSDocOptionalParameter(declaration)) ||
54225                 isOptionalJSDocPropertyLikeTag(declaration));
54226             // Use type from type annotation if one is present
54227             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
54228             if (declaredType) {
54229                 return addOptionality(declaredType, isProperty, isOptional);
54230             }
54231             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
54232                 ts.isVariableDeclaration(declaration) && !ts.isBindingPattern(declaration.name) &&
54233                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
54234                 // If --noImplicitAny is on or the declaration is in a Javascript file,
54235                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
54236                 // initializer or a 'null' or 'undefined' initializer.
54237                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
54238                     return autoType;
54239                 }
54240                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
54241                 // literal initializer.
54242                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
54243                     return autoArrayType;
54244                 }
54245             }
54246             if (ts.isParameter(declaration)) {
54247                 var func = declaration.parent;
54248                 // For a parameter of a set accessor, use the type of the get accessor if one is present
54249                 if (func.kind === 172 /* SetAccessor */ && hasBindableName(func)) {
54250                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 171 /* GetAccessor */);
54251                     if (getter) {
54252                         var getterSignature = getSignatureFromDeclaration(getter);
54253                         var thisParameter = getAccessorThisParameter(func);
54254                         if (thisParameter && declaration === thisParameter) {
54255                             // Use the type from the *getter*
54256                             ts.Debug.assert(!thisParameter.type);
54257                             return getTypeOfSymbol(getterSignature.thisParameter);
54258                         }
54259                         return getReturnTypeOfSignature(getterSignature);
54260                     }
54261                 }
54262                 if (ts.isInJSFile(declaration)) {
54263                     var typeTag = ts.getJSDocType(func);
54264                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
54265                         var signature = getSignatureFromDeclaration(typeTag);
54266                         var pos = func.parameters.indexOf(declaration);
54267                         return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
54268                     }
54269                 }
54270                 // Use contextual parameter type if one is available
54271                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
54272                 if (type) {
54273                     return addOptionality(type, /*isProperty*/ false, isOptional);
54274                 }
54275             }
54276             // Use the type of the initializer expression if one is present and the declaration is
54277             // not a parameter of a contextually typed function
54278             if (ts.hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
54279                 if (ts.isInJSFile(declaration) && !ts.isParameter(declaration)) {
54280                     var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
54281                     if (containerObjectType) {
54282                         return containerObjectType;
54283                     }
54284                 }
54285                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
54286                 return addOptionality(type, isProperty, isOptional);
54287             }
54288             if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) {
54289                 // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file.
54290                 // Use control flow analysis of this.xxx assignments in the constructor or static block to determine the type of the property.
54291                 if (!ts.hasStaticModifier(declaration)) {
54292                     var constructor = findConstructorDeclaration(declaration.parent);
54293                     var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
54294                         ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
54295                             undefined;
54296                     return type && addOptionality(type, /*isProperty*/ true, isOptional);
54297                 }
54298                 else {
54299                     var staticBlocks = ts.filter(declaration.parent.members, ts.isClassStaticBlockDeclaration);
54300                     var type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) :
54301                         ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
54302                             undefined;
54303                     return type && addOptionality(type, /*isProperty*/ true, isOptional);
54304                 }
54305             }
54306             if (ts.isJsxAttribute(declaration)) {
54307                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
54308                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
54309                 return trueType;
54310             }
54311             // If the declaration specifies a binding pattern and is not a parameter of a contextually
54312             // typed function, use the type implied by the binding pattern
54313             if (ts.isBindingPattern(declaration.name)) {
54314                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
54315             }
54316             // No type specified and nothing can be inferred
54317             return undefined;
54318         }
54319         function isConstructorDeclaredProperty(symbol) {
54320             // A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
54321             // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
54322             // a class constructor.
54323             if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) {
54324                 var links = getSymbolLinks(symbol);
54325                 if (links.isConstructorDeclaredProperty === undefined) {
54326                     links.isConstructorDeclaredProperty = false;
54327                     links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) {
54328                         return ts.isBinaryExpression(declaration) &&
54329                             isPossiblyAliasedThisProperty(declaration) &&
54330                             (declaration.left.kind !== 206 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) &&
54331                             !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration);
54332                     });
54333                 }
54334                 return links.isConstructorDeclaredProperty;
54335             }
54336             return false;
54337         }
54338         function isAutoTypedProperty(symbol) {
54339             // A property is auto-typed when its declaration has no type annotation or initializer and we're in
54340             // noImplicitAny mode or a .js file.
54341             var declaration = symbol.valueDeclaration;
54342             return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) &&
54343                 !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration));
54344         }
54345         function getDeclaringConstructor(symbol) {
54346             if (!symbol.declarations) {
54347                 return;
54348             }
54349             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
54350                 var declaration = _a[_i];
54351                 var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false);
54352                 if (container && (container.kind === 170 /* Constructor */ || isJSConstructor(container))) {
54353                     return container;
54354                 }
54355             }
54356             ;
54357         }
54358         /** Create a synthetic property access flow node after the last statement of the file */
54359         function getFlowTypeFromCommonJSExport(symbol) {
54360             var file = ts.getSourceFileOfNode(symbol.declarations[0]);
54361             var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName);
54362             var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); });
54363             var reference = areAllModuleExports
54364                 ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName)
54365                 : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName);
54366             if (areAllModuleExports) {
54367                 ts.setParent(reference.expression.expression, reference.expression);
54368             }
54369             ts.setParent(reference.expression, reference);
54370             ts.setParent(reference, file);
54371             reference.flowNode = file.endFlowNode;
54372             return getFlowTypeOfReference(reference, autoType, undefinedType);
54373         }
54374         function getFlowTypeInStaticBlocks(symbol, staticBlocks) {
54375             var accessName = ts.startsWith(symbol.escapedName, "__#")
54376                 ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1])
54377                 : ts.unescapeLeadingUnderscores(symbol.escapedName);
54378             for (var _i = 0, staticBlocks_1 = staticBlocks; _i < staticBlocks_1.length; _i++) {
54379                 var staticBlock = staticBlocks_1[_i];
54380                 var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), accessName);
54381                 ts.setParent(reference.expression, reference);
54382                 ts.setParent(reference, staticBlock);
54383                 reference.flowNode = staticBlock.returnFlowNode;
54384                 var flowType = getFlowTypeOfProperty(reference, symbol);
54385                 if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
54386                     error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54387                 }
54388                 // We don't infer a type if assignments are only null or undefined.
54389                 if (everyType(flowType, isNullableType)) {
54390                     continue;
54391                 }
54392                 return convertAutoToAny(flowType);
54393             }
54394         }
54395         function getFlowTypeInConstructor(symbol, constructor) {
54396             var accessName = ts.startsWith(symbol.escapedName, "__#")
54397                 ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1])
54398                 : ts.unescapeLeadingUnderscores(symbol.escapedName);
54399             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), accessName);
54400             ts.setParent(reference.expression, reference);
54401             ts.setParent(reference, constructor);
54402             reference.flowNode = constructor.returnFlowNode;
54403             var flowType = getFlowTypeOfProperty(reference, symbol);
54404             if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
54405                 error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54406             }
54407             // We don't infer a type if assignments are only null or undefined.
54408             return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType);
54409         }
54410         function getFlowTypeOfProperty(reference, prop) {
54411             var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration)
54412                 && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */)
54413                 && getTypeOfPropertyInBaseClass(prop)
54414                 || undefinedType;
54415             return getFlowTypeOfReference(reference, autoType, initialType);
54416         }
54417         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
54418             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
54419             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
54420             if (container) {
54421                 var tag = ts.getJSDocTypeTag(container);
54422                 if (tag && tag.typeExpression) {
54423                     return getTypeFromTypeNode(tag.typeExpression);
54424                 }
54425                 var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
54426                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
54427             }
54428             var type;
54429             var definedInConstructor = false;
54430             var definedInMethod = false;
54431             // We use control flow analysis to determine the type of the property if the property qualifies as a constructor
54432             // declared property and the resulting control flow type isn't just undefined or null.
54433             if (isConstructorDeclaredProperty(symbol)) {
54434                 type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
54435             }
54436             if (!type) {
54437                 var types = void 0;
54438                 if (symbol.declarations) {
54439                     var jsdocType = void 0;
54440                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
54441                         var declaration = _a[_i];
54442                         var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
54443                             ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
54444                                 undefined;
54445                         if (!expression) {
54446                             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
54447                         }
54448                         var kind = ts.isAccessExpression(expression)
54449                             ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
54450                             : ts.getAssignmentDeclarationKind(expression);
54451                         if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
54452                             if (isDeclarationInConstructor(expression)) {
54453                                 definedInConstructor = true;
54454                             }
54455                             else {
54456                                 definedInMethod = true;
54457                             }
54458                         }
54459                         if (!ts.isCallExpression(expression)) {
54460                             jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
54461                         }
54462                         if (!jsdocType) {
54463                             (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
54464                         }
54465                     }
54466                     type = jsdocType;
54467                 }
54468                 if (!type) {
54469                     if (!ts.length(types)) {
54470                         return errorType; // No types from any declarations :(
54471                     }
54472                     var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
54473                     // use only the constructor types unless they were only assigned null | undefined (including widening variants)
54474                     if (definedInMethod) {
54475                         var propType = getTypeOfPropertyInBaseClass(symbol);
54476                         if (propType) {
54477                             (constructorTypes || (constructorTypes = [])).push(propType);
54478                             definedInConstructor = true;
54479                         }
54480                     }
54481                     var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
54482                     type = getUnionType(sourceTypes, 2 /* Subtype */);
54483                 }
54484             }
54485             var widened = getWidenedType(addOptionality(type, /*isProperty*/ false, definedInMethod && !definedInConstructor));
54486             if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
54487                 reportImplicitAny(symbol.valueDeclaration, anyType);
54488                 return anyType;
54489             }
54490             return widened;
54491         }
54492         function getJSContainerObjectType(decl, symbol, init) {
54493             var _a, _b;
54494             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
54495                 return undefined;
54496             }
54497             var exports = ts.createSymbolTable();
54498             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
54499                 var s_2 = getSymbolOfNode(decl);
54500                 if ((_a = s_2 === null || s_2 === void 0 ? void 0 : s_2.exports) === null || _a === void 0 ? void 0 : _a.size) {
54501                     mergeSymbolTable(exports, s_2.exports);
54502                 }
54503                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
54504             }
54505             var s = getSymbolOfNode(decl);
54506             if ((_b = s === null || s === void 0 ? void 0 : s.exports) === null || _b === void 0 ? void 0 : _b.size) {
54507                 mergeSymbolTable(exports, s.exports);
54508             }
54509             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, ts.emptyArray);
54510             type.objectFlags |= 8192 /* JSLiteral */;
54511             return type;
54512         }
54513         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
54514             var _a;
54515             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
54516             if (typeNode) {
54517                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
54518                 if (!declaredType) {
54519                     return type;
54520                 }
54521                 else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) {
54522                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
54523                 }
54524             }
54525             if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) {
54526                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
54527                 if (typeNode_2) {
54528                     var annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
54529                     if (annotationSymbol) {
54530                         return getNonMissingTypeOfSymbol(annotationSymbol);
54531                     }
54532                 }
54533             }
54534             return declaredType;
54535         }
54536         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
54537         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
54538             if (ts.isCallExpression(expression)) {
54539                 if (resolvedSymbol) {
54540                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
54541                 }
54542                 var objectLitType = checkExpressionCached(expression.arguments[2]);
54543                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
54544                 if (valueType) {
54545                     return valueType;
54546                 }
54547                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
54548                 if (getFunc) {
54549                     var getSig = getSingleCallSignature(getFunc);
54550                     if (getSig) {
54551                         return getReturnTypeOfSignature(getSig);
54552                     }
54553                 }
54554                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
54555                 if (setFunc) {
54556                     var setSig = getSingleCallSignature(setFunc);
54557                     if (setSig) {
54558                         return getTypeOfFirstParameterOfSignature(setSig);
54559                     }
54560                 }
54561                 return anyType;
54562             }
54563             if (containsSameNamedThisProperty(expression.left, expression.right)) {
54564                 return anyType;
54565             }
54566             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
54567             if (type.flags & 524288 /* Object */ &&
54568                 kind === 2 /* ModuleExports */ &&
54569                 symbol.escapedName === "export=" /* ExportEquals */) {
54570                 var exportedType = resolveStructuredTypeMembers(type);
54571                 var members_4 = ts.createSymbolTable();
54572                 ts.copyEntries(exportedType.members, members_4);
54573                 var initialSize = members_4.size;
54574                 if (resolvedSymbol && !resolvedSymbol.exports) {
54575                     resolvedSymbol.exports = ts.createSymbolTable();
54576                 }
54577                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
54578                     var _a;
54579                     var exportedMember = members_4.get(name);
54580                     if (exportedMember && exportedMember !== s) {
54581                         if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
54582                             // If the member has an additional value-like declaration, union the types from the two declarations,
54583                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
54584                             // a pattern like:
54585                             //
54586                             // module.exports = { a: true };
54587                             // module.exports.a = 3;
54588                             //
54589                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
54590                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
54591                             // it's unclear what that's supposed to mean, so it's probably a mistake.
54592                             if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
54593                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
54594                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
54595                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
54596                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
54597                             }
54598                             var union = createSymbol(s.flags | exportedMember.flags, name);
54599                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
54600                             union.valueDeclaration = exportedMember.valueDeclaration;
54601                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
54602                             members_4.set(name, union);
54603                         }
54604                         else {
54605                             members_4.set(name, mergeSymbol(s, exportedMember));
54606                         }
54607                     }
54608                     else {
54609                         members_4.set(name, s);
54610                     }
54611                 });
54612                 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
54613                 members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos);
54614                 result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag
54615                 if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
54616                     result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type
54617                 }
54618                 return result;
54619             }
54620             if (isEmptyArrayLiteralType(type)) {
54621                 reportImplicitAny(expression, anyArrayType);
54622                 return anyArrayType;
54623             }
54624             return type;
54625         }
54626         function containsSameNamedThisProperty(thisProperty, expression) {
54627             return ts.isPropertyAccessExpression(thisProperty)
54628                 && thisProperty.expression.kind === 108 /* ThisKeyword */
54629                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
54630         }
54631         function isDeclarationInConstructor(expression) {
54632             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
54633             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
54634             // Function expressions that are assigned to the prototype count as methods.
54635             return thisContainer.kind === 170 /* Constructor */ ||
54636                 thisContainer.kind === 255 /* FunctionDeclaration */ ||
54637                 (thisContainer.kind === 212 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
54638         }
54639         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
54640             ts.Debug.assert(types.length === declarations.length);
54641             return types.filter(function (_, i) {
54642                 var declaration = declarations[i];
54643                 var expression = ts.isBinaryExpression(declaration) ? declaration :
54644                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
54645                 return expression && isDeclarationInConstructor(expression);
54646             });
54647         }
54648         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
54649         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
54650         // pattern. Otherwise, it is the type any.
54651         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
54652             if (element.initializer) {
54653                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
54654                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
54655                 // pattern.
54656                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
54657                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
54658             }
54659             if (ts.isBindingPattern(element.name)) {
54660                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
54661             }
54662             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
54663                 reportImplicitAny(element, anyType);
54664             }
54665             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
54666             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
54667             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
54668             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
54669             return includePatternInType ? nonInferrableAnyType : anyType;
54670         }
54671         // Return the type implied by an object binding pattern
54672         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
54673             var members = ts.createSymbolTable();
54674             var stringIndexInfo;
54675             var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */;
54676             ts.forEach(pattern.elements, function (e) {
54677                 var name = e.propertyName || e.name;
54678                 if (e.dotDotDotToken) {
54679                     stringIndexInfo = createIndexInfo(stringType, anyType, /*isReadonly*/ false);
54680                     return;
54681                 }
54682                 var exprType = getLiteralTypeFromPropertyName(name);
54683                 if (!isTypeUsableAsPropertyName(exprType)) {
54684                     // do not include computed properties in the implied type
54685                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
54686                     return;
54687                 }
54688                 var text = getPropertyNameFromType(exprType);
54689                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
54690                 var symbol = createSymbol(flags, text);
54691                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
54692                 symbol.bindingElement = e;
54693                 members.set(symbol.escapedName, symbol);
54694             });
54695             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo ? [stringIndexInfo] : ts.emptyArray);
54696             result.objectFlags |= objectFlags;
54697             if (includePatternInType) {
54698                 result.pattern = pattern;
54699                 result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */;
54700             }
54701             return result;
54702         }
54703         // Return the type implied by an array binding pattern
54704         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
54705             var elements = pattern.elements;
54706             var lastElement = ts.lastOrUndefined(elements);
54707             var restElement = lastElement && lastElement.kind === 202 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined;
54708             if (elements.length === 0 || elements.length === 1 && restElement) {
54709                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
54710             }
54711             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
54712             var minLength = ts.findLastIndex(elements, function (e) { return !(e === restElement || ts.isOmittedExpression(e) || hasDefaultValue(e)); }, elements.length - 1) + 1;
54713             var elementFlags = ts.map(elements, function (e, i) { return e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */; });
54714             var result = createTupleType(elementTypes, elementFlags);
54715             if (includePatternInType) {
54716                 result = cloneTypeReference(result);
54717                 result.pattern = pattern;
54718                 result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */;
54719             }
54720             return result;
54721         }
54722         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
54723         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
54724         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
54725         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
54726         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
54727         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
54728         // the parameter.
54729         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
54730             if (includePatternInType === void 0) { includePatternInType = false; }
54731             if (reportErrors === void 0) { reportErrors = false; }
54732             return pattern.kind === 200 /* ObjectBindingPattern */
54733                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
54734                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
54735         }
54736         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
54737         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
54738         // is a bit more involved. For example:
54739         //
54740         //   var [x, s = ""] = [1, "one"];
54741         //
54742         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
54743         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
54744         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
54745         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
54746             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
54747         }
54748         function isGlobalSymbolConstructor(node) {
54749             var symbol = getSymbolOfNode(node);
54750             var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false);
54751             return globalSymbol && symbol && symbol === globalSymbol;
54752         }
54753         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
54754             if (type) {
54755                 // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol`
54756                 if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) {
54757                     type = getESSymbolLikeTypeForNode(declaration);
54758                 }
54759                 if (reportErrors) {
54760                     reportErrorsFromWidening(declaration, type);
54761                 }
54762                 // always widen a 'unique symbol' type if the type was created for a different declaration.
54763                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
54764                     type = esSymbolType;
54765                 }
54766                 return getWidenedType(type);
54767             }
54768             // Rest parameters default to type any[], other parameters default to type any
54769             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
54770             // Report implicit any errors unless this is a private property within an ambient declaration
54771             if (reportErrors) {
54772                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
54773                     reportImplicitAny(declaration, type);
54774                 }
54775             }
54776             return type;
54777         }
54778         function declarationBelongsToPrivateAmbientMember(declaration) {
54779             var root = ts.getRootDeclaration(declaration);
54780             var memberDeclaration = root.kind === 163 /* Parameter */ ? root.parent : root;
54781             return isPrivateWithinAmbient(memberDeclaration);
54782         }
54783         function tryGetTypeFromEffectiveTypeNode(declaration) {
54784             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
54785             if (typeNode) {
54786                 return getTypeFromTypeNode(typeNode);
54787             }
54788         }
54789         function getTypeOfVariableOrParameterOrProperty(symbol) {
54790             var links = getSymbolLinks(symbol);
54791             if (!links.type) {
54792                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
54793                 // For a contextually typed parameter it is possible that a type has already
54794                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
54795                 // to preserve this type.
54796                 if (!links.type) {
54797                     links.type = type;
54798                 }
54799             }
54800             return links.type;
54801         }
54802         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
54803             // Handle prototype property
54804             if (symbol.flags & 4194304 /* Prototype */) {
54805                 return getTypeOfPrototypeProperty(symbol);
54806             }
54807             // CommonsJS require and module both have type any.
54808             if (symbol === requireSymbol) {
54809                 return anyType;
54810             }
54811             if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) {
54812                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
54813                 var result = createSymbol(fileSymbol.flags, "exports");
54814                 result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
54815                 result.parent = symbol;
54816                 result.target = fileSymbol;
54817                 if (fileSymbol.valueDeclaration)
54818                     result.valueDeclaration = fileSymbol.valueDeclaration;
54819                 if (fileSymbol.members)
54820                     result.members = new ts.Map(fileSymbol.members);
54821                 if (fileSymbol.exports)
54822                     result.exports = new ts.Map(fileSymbol.exports);
54823                 var members = ts.createSymbolTable();
54824                 members.set("exports", result);
54825                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, ts.emptyArray);
54826             }
54827             // Handle catch clause variables
54828             ts.Debug.assertIsDefined(symbol.valueDeclaration);
54829             var declaration = symbol.valueDeclaration;
54830             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
54831                 var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
54832                 if (typeNode === undefined) {
54833                     return useUnknownInCatchVariables ? unknownType : anyType;
54834                 }
54835                 var type_1 = getTypeOfNode(typeNode);
54836                 // an errorType will make `checkTryStatement` issue an error
54837                 return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
54838             }
54839             // Handle export default expressions
54840             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
54841                 if (!declaration.statements.length) {
54842                     return emptyObjectType;
54843                 }
54844                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
54845             }
54846             // Handle variable, parameter or property
54847             if (!pushTypeResolution(symbol, 0 /* Type */)) {
54848                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
54849                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
54850                     return getTypeOfFuncClassEnumModule(symbol);
54851                 }
54852                 return reportCircularityError(symbol);
54853             }
54854             var type;
54855             if (declaration.kind === 270 /* ExportAssignment */) {
54856                 type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration);
54857             }
54858             else if (ts.isBinaryExpression(declaration) ||
54859                 (ts.isInJSFile(declaration) &&
54860                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
54861                 type = getWidenedTypeForAssignmentDeclaration(symbol);
54862             }
54863             else if (ts.isPropertyAccessExpression(declaration)
54864                 || ts.isElementAccessExpression(declaration)
54865                 || ts.isIdentifier(declaration)
54866                 || ts.isStringLiteralLike(declaration)
54867                 || ts.isNumericLiteral(declaration)
54868                 || ts.isClassDeclaration(declaration)
54869                 || ts.isFunctionDeclaration(declaration)
54870                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
54871                 || ts.isMethodSignature(declaration)
54872                 || ts.isSourceFile(declaration)) {
54873                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
54874                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
54875                     return getTypeOfFuncClassEnumModule(symbol);
54876                 }
54877                 type = ts.isBinaryExpression(declaration.parent) ?
54878                     getWidenedTypeForAssignmentDeclaration(symbol) :
54879                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
54880             }
54881             else if (ts.isPropertyAssignment(declaration)) {
54882                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
54883             }
54884             else if (ts.isJsxAttribute(declaration)) {
54885                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
54886             }
54887             else if (ts.isShorthandPropertyAssignment(declaration)) {
54888                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
54889             }
54890             else if (ts.isObjectLiteralMethod(declaration)) {
54891                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
54892             }
54893             else if (ts.isParameter(declaration)
54894                 || ts.isPropertyDeclaration(declaration)
54895                 || ts.isPropertySignature(declaration)
54896                 || ts.isVariableDeclaration(declaration)
54897                 || ts.isBindingElement(declaration)
54898                 || ts.isJSDocPropertyLikeTag(declaration)) {
54899                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
54900             }
54901             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
54902             // Re-dispatch based on valueDeclaration.kind instead.
54903             else if (ts.isEnumDeclaration(declaration)) {
54904                 type = getTypeOfFuncClassEnumModule(symbol);
54905             }
54906             else if (ts.isEnumMember(declaration)) {
54907                 type = getTypeOfEnumMember(symbol);
54908             }
54909             else if (ts.isAccessor(declaration)) {
54910                 type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type");
54911             }
54912             else {
54913                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
54914             }
54915             if (!popTypeResolution()) {
54916                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
54917                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
54918                     return getTypeOfFuncClassEnumModule(symbol);
54919                 }
54920                 return reportCircularityError(symbol);
54921             }
54922             return type;
54923         }
54924         function getAnnotatedAccessorTypeNode(accessor) {
54925             if (accessor) {
54926                 if (accessor.kind === 171 /* GetAccessor */) {
54927                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
54928                     return getterTypeAnnotation;
54929                 }
54930                 else {
54931                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
54932                     return setterTypeAnnotation;
54933                 }
54934             }
54935             return undefined;
54936         }
54937         function getAnnotatedAccessorType(accessor) {
54938             var node = getAnnotatedAccessorTypeNode(accessor);
54939             return node && getTypeFromTypeNode(node);
54940         }
54941         function getAnnotatedAccessorThisParameter(accessor) {
54942             var parameter = getAccessorThisParameter(accessor);
54943             return parameter && parameter.symbol;
54944         }
54945         function getThisTypeOfDeclaration(declaration) {
54946             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
54947         }
54948         function getTypeOfAccessors(symbol) {
54949             var links = getSymbolLinks(symbol);
54950             return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type"));
54951         }
54952         function getTypeOfSetAccessor(symbol) {
54953             var links = getSymbolLinks(symbol);
54954             return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true));
54955         }
54956         function getTypeOfAccessorsWorker(symbol, writing) {
54957             if (writing === void 0) { writing = false; }
54958             if (!pushTypeResolution(symbol, 0 /* Type */)) {
54959                 return errorType;
54960             }
54961             var type = resolveTypeOfAccessors(symbol, writing);
54962             if (!popTypeResolution()) {
54963                 type = anyType;
54964                 if (noImplicitAny) {
54965                     var getter = ts.getDeclarationOfKind(symbol, 171 /* GetAccessor */);
54966                     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));
54967                 }
54968             }
54969             return type;
54970         }
54971         function resolveTypeOfAccessors(symbol, writing) {
54972             if (writing === void 0) { writing = false; }
54973             var getter = ts.getDeclarationOfKind(symbol, 171 /* GetAccessor */);
54974             var setter = ts.getDeclarationOfKind(symbol, 172 /* SetAccessor */);
54975             var setterType = getAnnotatedAccessorType(setter);
54976             // For write operations, prioritize type annotations on the setter
54977             if (writing && setterType) {
54978                 return instantiateTypeIfNeeded(setterType, symbol);
54979             }
54980             // Else defer to the getter type
54981             if (getter && ts.isInJSFile(getter)) {
54982                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
54983                 if (jsDocType) {
54984                     return instantiateTypeIfNeeded(jsDocType, symbol);
54985                 }
54986             }
54987             // Try to see if the user specified a return type on the get-accessor.
54988             var getterType = getAnnotatedAccessorType(getter);
54989             if (getterType) {
54990                 return instantiateTypeIfNeeded(getterType, symbol);
54991             }
54992             // If the user didn't specify a return type, try to use the set-accessor's parameter type.
54993             if (setterType) {
54994                 return setterType;
54995             }
54996             // If there are no specified types, try to infer it from the body of the get accessor if it exists.
54997             if (getter && getter.body) {
54998                 var returnTypeFromBody = getReturnTypeFromBody(getter);
54999                 return instantiateTypeIfNeeded(returnTypeFromBody, symbol);
55000             }
55001             // Otherwise, fall back to 'any'.
55002             if (setter) {
55003                 if (!isPrivateWithinAmbient(setter)) {
55004                     errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
55005                 }
55006                 return anyType;
55007             }
55008             else if (getter) {
55009                 ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
55010                 if (!isPrivateWithinAmbient(getter)) {
55011                     errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
55012                 }
55013                 return anyType;
55014             }
55015             return undefined;
55016             function instantiateTypeIfNeeded(type, symbol) {
55017                 if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
55018                     var links = getSymbolLinks(symbol);
55019                     return instantiateType(type, links.mapper);
55020                 }
55021                 return type;
55022             }
55023         }
55024         function getBaseTypeVariableOfClass(symbol) {
55025             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
55026             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
55027                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
55028                     undefined;
55029         }
55030         function getTypeOfFuncClassEnumModule(symbol) {
55031             var links = getSymbolLinks(symbol);
55032             var originalLinks = links;
55033             if (!links.type) {
55034                 var expando = symbol.valueDeclaration && getSymbolOfExpando(symbol.valueDeclaration, /*allowDeclaration*/ false);
55035                 if (expando) {
55036                     var merged = mergeJSSymbols(symbol, expando);
55037                     if (merged) {
55038                         // note:we overwrite links because we just cloned the symbol
55039                         symbol = links = merged;
55040                     }
55041                 }
55042                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
55043             }
55044             return links.type;
55045         }
55046         function getTypeOfFuncClassEnumModuleWorker(symbol) {
55047             var declaration = symbol.valueDeclaration;
55048             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
55049                 return anyType;
55050             }
55051             else if (declaration && (declaration.kind === 220 /* BinaryExpression */ ||
55052                 ts.isAccessExpression(declaration) &&
55053                     declaration.parent.kind === 220 /* BinaryExpression */)) {
55054                 return getWidenedTypeForAssignmentDeclaration(symbol);
55055             }
55056             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
55057                 var resolvedModule = resolveExternalModuleSymbol(symbol);
55058                 if (resolvedModule !== symbol) {
55059                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
55060                         return errorType;
55061                     }
55062                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
55063                     var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
55064                     if (!popTypeResolution()) {
55065                         return reportCircularityError(symbol);
55066                     }
55067                     return type_2;
55068                 }
55069             }
55070             var type = createObjectType(16 /* Anonymous */, symbol);
55071             if (symbol.flags & 32 /* Class */) {
55072                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
55073                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
55074             }
55075             else {
55076                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
55077             }
55078         }
55079         function getTypeOfEnumMember(symbol) {
55080             var links = getSymbolLinks(symbol);
55081             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
55082         }
55083         function getTypeOfAlias(symbol) {
55084             var links = getSymbolLinks(symbol);
55085             if (!links.type) {
55086                 var targetSymbol = resolveAlias(symbol);
55087                 var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true);
55088                 var declaredType = ts.firstDefined(exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations, function (d) { return ts.isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : undefined; });
55089                 // It only makes sense to get the type of a value symbol. If the result of resolving
55090                 // the alias is not a value, then it has no type. To get the type associated with a
55091                 // type symbol, call getDeclaredTypeOfSymbol.
55092                 // This check is important because without it, a call to getTypeOfSymbol could end
55093                 // up recursively calling getTypeOfAlias, causing a stack overflow.
55094                 links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol)
55095                     : isDuplicatedCommonJSExport(symbol.declarations) ? autoType
55096                         : declaredType ? declaredType
55097                             : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol)
55098                                 : errorType;
55099             }
55100             return links.type;
55101         }
55102         function getTypeOfInstantiatedSymbol(symbol) {
55103             var links = getSymbolLinks(symbol);
55104             if (!links.type) {
55105                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
55106                     return links.type = errorType;
55107                 }
55108                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
55109                 if (!popTypeResolution()) {
55110                     type = reportCircularityError(symbol);
55111                 }
55112                 links.type = type;
55113             }
55114             return links.type;
55115         }
55116         function reportCircularityError(symbol) {
55117             var declaration = symbol.valueDeclaration;
55118             // Check if variable has type annotation that circularly references the variable itself
55119             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
55120                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
55121                 return errorType;
55122             }
55123             // Check if variable has initializer that circularly references the variable itself
55124             if (noImplicitAny && (declaration.kind !== 163 /* Parameter */ || declaration.initializer)) {
55125                 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));
55126             }
55127             // Circularities could also result from parameters in function expressions that end up
55128             // having themselves as contextual types following type argument inference. In those cases
55129             // we have already reported an implicit any error so we don't report anything here.
55130             return anyType;
55131         }
55132         function getTypeOfSymbolWithDeferredType(symbol) {
55133             var links = getSymbolLinks(symbol);
55134             if (!links.type) {
55135                 ts.Debug.assertIsDefined(links.deferralParent);
55136                 ts.Debug.assertIsDefined(links.deferralConstituents);
55137                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
55138             }
55139             return links.type;
55140         }
55141         function getSetAccessorTypeOfSymbol(symbol) {
55142             if (symbol.flags & 98304 /* Accessor */) {
55143                 var type = getTypeOfSetAccessor(symbol);
55144                 if (type) {
55145                     return type;
55146                 }
55147             }
55148             return getTypeOfSymbol(symbol);
55149         }
55150         function getTypeOfSymbol(symbol) {
55151             var checkFlags = ts.getCheckFlags(symbol);
55152             if (checkFlags & 65536 /* DeferredType */) {
55153                 return getTypeOfSymbolWithDeferredType(symbol);
55154             }
55155             if (checkFlags & 1 /* Instantiated */) {
55156                 return getTypeOfInstantiatedSymbol(symbol);
55157             }
55158             if (checkFlags & 262144 /* Mapped */) {
55159                 return getTypeOfMappedSymbol(symbol);
55160             }
55161             if (checkFlags & 8192 /* ReverseMapped */) {
55162                 return getTypeOfReverseMappedSymbol(symbol);
55163             }
55164             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
55165                 return getTypeOfVariableOrParameterOrProperty(symbol);
55166             }
55167             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
55168                 return getTypeOfFuncClassEnumModule(symbol);
55169             }
55170             if (symbol.flags & 8 /* EnumMember */) {
55171                 return getTypeOfEnumMember(symbol);
55172             }
55173             if (symbol.flags & 98304 /* Accessor */) {
55174                 return getTypeOfAccessors(symbol);
55175             }
55176             if (symbol.flags & 2097152 /* Alias */) {
55177                 return getTypeOfAlias(symbol);
55178             }
55179             return errorType;
55180         }
55181         function getNonMissingTypeOfSymbol(symbol) {
55182             return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */));
55183         }
55184         function isReferenceToType(type, target) {
55185             return type !== undefined
55186                 && target !== undefined
55187                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
55188                 && type.target === target;
55189         }
55190         function getTargetType(type) {
55191             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
55192         }
55193         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
55194         function hasBaseType(type, checkBase) {
55195             return check(type);
55196             function check(type) {
55197                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
55198                     var target = getTargetType(type);
55199                     return target === checkBase || ts.some(getBaseTypes(target), check);
55200                 }
55201                 else if (type.flags & 2097152 /* Intersection */) {
55202                     return ts.some(type.types, check);
55203                 }
55204                 return false;
55205             }
55206         }
55207         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
55208         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
55209         // in-place and returns the same array.
55210         function appendTypeParameters(typeParameters, declarations) {
55211             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
55212                 var declaration = declarations_2[_i];
55213                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
55214             }
55215             return typeParameters;
55216         }
55217         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
55218         function getOuterTypeParameters(node, includeThisTypes) {
55219             while (true) {
55220                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
55221                 if (node && ts.isBinaryExpression(node)) {
55222                     // prototype assignments get the outer type parameters of their constructor function
55223                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
55224                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
55225                         var symbol = getSymbolOfNode(node.left);
55226                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
55227                             node = symbol.parent.valueDeclaration;
55228                         }
55229                     }
55230                 }
55231                 if (!node) {
55232                     return undefined;
55233                 }
55234                 switch (node.kind) {
55235                     case 256 /* ClassDeclaration */:
55236                     case 225 /* ClassExpression */:
55237                     case 257 /* InterfaceDeclaration */:
55238                     case 173 /* CallSignature */:
55239                     case 174 /* ConstructSignature */:
55240                     case 167 /* MethodSignature */:
55241                     case 178 /* FunctionType */:
55242                     case 179 /* ConstructorType */:
55243                     case 315 /* JSDocFunctionType */:
55244                     case 255 /* FunctionDeclaration */:
55245                     case 168 /* MethodDeclaration */:
55246                     case 212 /* FunctionExpression */:
55247                     case 213 /* ArrowFunction */:
55248                     case 258 /* TypeAliasDeclaration */:
55249                     case 342 /* JSDocTemplateTag */:
55250                     case 343 /* JSDocTypedefTag */:
55251                     case 337 /* JSDocEnumTag */:
55252                     case 336 /* JSDocCallbackTag */:
55253                     case 194 /* MappedType */:
55254                     case 188 /* ConditionalType */: {
55255                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
55256                         if (node.kind === 194 /* MappedType */) {
55257                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
55258                         }
55259                         else if (node.kind === 188 /* ConditionalType */) {
55260                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
55261                         }
55262                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
55263                         var thisType = includeThisTypes &&
55264                             (node.kind === 256 /* ClassDeclaration */ || node.kind === 225 /* ClassExpression */ || node.kind === 257 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
55265                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
55266                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
55267                     }
55268                     case 338 /* JSDocParameterTag */:
55269                         var paramSymbol = ts.getParameterSymbolFromJSDoc(node);
55270                         if (paramSymbol) {
55271                             node = paramSymbol.valueDeclaration;
55272                         }
55273                         break;
55274                     case 318 /* JSDocComment */: {
55275                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
55276                         return node.tags
55277                             ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; }))
55278                             : outerTypeParameters;
55279                     }
55280                 }
55281             }
55282         }
55283         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
55284         function getOuterTypeParametersOfClassOrInterface(symbol) {
55285             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 257 /* InterfaceDeclaration */);
55286             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
55287             return getOuterTypeParameters(declaration);
55288         }
55289         // The local type parameters are the combined set of type parameters from all declarations of the class,
55290         // interface, or type alias.
55291         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
55292             if (!symbol.declarations) {
55293                 return;
55294             }
55295             var result;
55296             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
55297                 var node = _a[_i];
55298                 if (node.kind === 257 /* InterfaceDeclaration */ ||
55299                     node.kind === 256 /* ClassDeclaration */ ||
55300                     node.kind === 225 /* ClassExpression */ ||
55301                     isJSConstructor(node) ||
55302                     ts.isTypeAlias(node)) {
55303                     var declaration = node;
55304                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
55305                 }
55306             }
55307             return result;
55308         }
55309         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
55310         // its locally declared type parameters.
55311         function getTypeParametersOfClassOrInterface(symbol) {
55312             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
55313         }
55314         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
55315         // rest parameter of type any[].
55316         function isMixinConstructorType(type) {
55317             var signatures = getSignaturesOfType(type, 1 /* Construct */);
55318             if (signatures.length === 1) {
55319                 var s = signatures[0];
55320                 if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
55321                     var paramType = getTypeOfParameter(s.parameters[0]);
55322                     return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
55323                 }
55324             }
55325             return false;
55326         }
55327         function isConstructorType(type) {
55328             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
55329                 return true;
55330             }
55331             if (type.flags & 8650752 /* TypeVariable */) {
55332                 var constraint = getBaseConstraintOfType(type);
55333                 return !!constraint && isMixinConstructorType(constraint);
55334             }
55335             return false;
55336         }
55337         function getBaseTypeNodeOfClass(type) {
55338             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
55339         }
55340         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
55341             var typeArgCount = ts.length(typeArgumentNodes);
55342             var isJavascript = ts.isInJSFile(location);
55343             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
55344         }
55345         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
55346             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
55347             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
55348             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
55349         }
55350         /**
55351          * The base constructor of a class can resolve to
55352          * * undefinedType if the class has no extends clause,
55353          * * unknownType if an error occurred during resolution of the extends expression,
55354          * * nullType if the extends expression is the null value,
55355          * * anyType if the extends expression has type any, or
55356          * * an object type with at least one construct signature.
55357          */
55358         function getBaseConstructorTypeOfClass(type) {
55359             if (!type.resolvedBaseConstructorType) {
55360                 var decl = type.symbol.valueDeclaration;
55361                 var extended = ts.getEffectiveBaseTypeNode(decl);
55362                 var baseTypeNode = getBaseTypeNodeOfClass(type);
55363                 if (!baseTypeNode) {
55364                     return type.resolvedBaseConstructorType = undefinedType;
55365                 }
55366                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
55367                     return errorType;
55368                 }
55369                 var baseConstructorType = checkExpression(baseTypeNode.expression);
55370                 if (extended && baseTypeNode !== extended) {
55371                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
55372                     checkExpression(extended.expression);
55373                 }
55374                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
55375                     // Resolving the members of a class requires us to resolve the base class of that class.
55376                     // We force resolution here such that we catch circularities now.
55377                     resolveStructuredTypeMembers(baseConstructorType);
55378                 }
55379                 if (!popTypeResolution()) {
55380                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
55381                     return type.resolvedBaseConstructorType = errorType;
55382                 }
55383                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
55384                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
55385                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
55386                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
55387                         var ctorReturn = unknownType;
55388                         if (constraint) {
55389                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
55390                             if (ctorSig[0]) {
55391                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
55392                             }
55393                         }
55394                         if (baseConstructorType.symbol.declarations) {
55395                             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)));
55396                         }
55397                     }
55398                     return type.resolvedBaseConstructorType = errorType;
55399                 }
55400                 type.resolvedBaseConstructorType = baseConstructorType;
55401             }
55402             return type.resolvedBaseConstructorType;
55403         }
55404         function getImplementsTypes(type) {
55405             var resolvedImplementsTypes = ts.emptyArray;
55406             if (type.symbol.declarations) {
55407                 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
55408                     var declaration = _a[_i];
55409                     var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
55410                     if (!implementsTypeNodes)
55411                         continue;
55412                     for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
55413                         var node = implementsTypeNodes_1[_b];
55414                         var implementsType = getTypeFromTypeNode(node);
55415                         if (!isErrorType(implementsType)) {
55416                             if (resolvedImplementsTypes === ts.emptyArray) {
55417                                 resolvedImplementsTypes = [implementsType];
55418                             }
55419                             else {
55420                                 resolvedImplementsTypes.push(implementsType);
55421                             }
55422                         }
55423                     }
55424                 }
55425             }
55426             return resolvedImplementsTypes;
55427         }
55428         function reportCircularBaseType(node, type) {
55429             error(node, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
55430         }
55431         function getBaseTypes(type) {
55432             if (!type.baseTypesResolved) {
55433                 if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) {
55434                     if (type.objectFlags & 8 /* Tuple */) {
55435                         type.resolvedBaseTypes = [getTupleBaseType(type)];
55436                     }
55437                     else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
55438                         if (type.symbol.flags & 32 /* Class */) {
55439                             resolveBaseTypesOfClass(type);
55440                         }
55441                         if (type.symbol.flags & 64 /* Interface */) {
55442                             resolveBaseTypesOfInterface(type);
55443                         }
55444                     }
55445                     else {
55446                         ts.Debug.fail("type must be class or interface");
55447                     }
55448                     if (!popTypeResolution() && type.symbol.declarations) {
55449                         for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
55450                             var declaration = _a[_i];
55451                             if (declaration.kind === 256 /* ClassDeclaration */ || declaration.kind === 257 /* InterfaceDeclaration */) {
55452                                 reportCircularBaseType(declaration, type);
55453                             }
55454                         }
55455                     }
55456                 }
55457                 type.baseTypesResolved = true;
55458             }
55459             return type.resolvedBaseTypes;
55460         }
55461         function getTupleBaseType(type) {
55462             var elementTypes = ts.sameMap(type.typeParameters, function (t, i) { return type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; });
55463             return createArrayType(getUnionType(elementTypes || ts.emptyArray), type.readonly);
55464         }
55465         function resolveBaseTypesOfClass(type) {
55466             type.resolvedBaseTypes = ts.resolvingEmptyArray;
55467             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
55468             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
55469                 return type.resolvedBaseTypes = ts.emptyArray;
55470             }
55471             var baseTypeNode = getBaseTypeNodeOfClass(type);
55472             var baseType;
55473             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
55474             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
55475                 areAllOuterTypeParametersApplied(originalBaseType)) {
55476                 // 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
55477                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
55478                 // type arguments in the same manner as a type reference to get the same error reporting experience.
55479                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
55480             }
55481             else if (baseConstructorType.flags & 1 /* Any */) {
55482                 baseType = baseConstructorType;
55483             }
55484             else {
55485                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
55486                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
55487                 // we check that all instantiated signatures return the same type.
55488                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
55489                 if (!constructors.length) {
55490                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
55491                     return type.resolvedBaseTypes = ts.emptyArray;
55492                 }
55493                 baseType = getReturnTypeOfSignature(constructors[0]);
55494             }
55495             if (isErrorType(baseType)) {
55496                 return type.resolvedBaseTypes = ts.emptyArray;
55497             }
55498             var reducedBaseType = getReducedType(baseType);
55499             if (!isValidBaseType(reducedBaseType)) {
55500                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
55501                 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));
55502                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
55503                 return type.resolvedBaseTypes = ts.emptyArray;
55504             }
55505             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
55506                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
55507                 return type.resolvedBaseTypes = ts.emptyArray;
55508             }
55509             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
55510                 // Circular reference, likely through instantiation of default parameters
55511                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
55512                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
55513                 // partial instantiation of the members without the base types fully resolved
55514                 type.members = undefined;
55515             }
55516             return type.resolvedBaseTypes = [reducedBaseType];
55517         }
55518         function areAllOuterTypeParametersApplied(type) {
55519             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
55520             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
55521             var outerTypeParameters = type.outerTypeParameters;
55522             if (outerTypeParameters) {
55523                 var last_1 = outerTypeParameters.length - 1;
55524                 var typeArguments = getTypeArguments(type);
55525                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
55526             }
55527             return true;
55528         }
55529         // A valid base type is `any`, an object type or intersection of object types.
55530         function isValidBaseType(type) {
55531             if (type.flags & 262144 /* TypeParameter */) {
55532                 var constraint = getBaseConstraintOfType(type);
55533                 if (constraint) {
55534                     return isValidBaseType(constraint);
55535                 }
55536             }
55537             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
55538             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
55539             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
55540                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
55541         }
55542         function resolveBaseTypesOfInterface(type) {
55543             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
55544             if (type.symbol.declarations) {
55545                 for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
55546                     var declaration = _a[_i];
55547                     if (declaration.kind === 257 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
55548                         for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
55549                             var node = _c[_b];
55550                             var baseType = getReducedType(getTypeFromTypeNode(node));
55551                             if (!isErrorType(baseType)) {
55552                                 if (isValidBaseType(baseType)) {
55553                                     if (type !== baseType && !hasBaseType(baseType, type)) {
55554                                         if (type.resolvedBaseTypes === ts.emptyArray) {
55555                                             type.resolvedBaseTypes = [baseType];
55556                                         }
55557                                         else {
55558                                             type.resolvedBaseTypes.push(baseType);
55559                                         }
55560                                     }
55561                                     else {
55562                                         reportCircularBaseType(declaration, type);
55563                                     }
55564                                 }
55565                                 else {
55566                                     error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
55567                                 }
55568                             }
55569                         }
55570                     }
55571                 }
55572             }
55573         }
55574         /**
55575          * Returns true if the interface given by the symbol is free of "this" references.
55576          *
55577          * Specifically, the result is true if the interface itself contains no references
55578          * to "this" in its body, if all base types are interfaces,
55579          * and if none of the base interfaces have a "this" type.
55580          */
55581         function isThislessInterface(symbol) {
55582             if (!symbol.declarations) {
55583                 return true;
55584             }
55585             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
55586                 var declaration = _a[_i];
55587                 if (declaration.kind === 257 /* InterfaceDeclaration */) {
55588                     if (declaration.flags & 128 /* ContainsThis */) {
55589                         return false;
55590                     }
55591                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
55592                     if (baseTypeNodes) {
55593                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
55594                             var node = baseTypeNodes_1[_b];
55595                             if (ts.isEntityNameExpression(node.expression)) {
55596                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
55597                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
55598                                     return false;
55599                                 }
55600                             }
55601                         }
55602                     }
55603                 }
55604             }
55605             return true;
55606         }
55607         function getDeclaredTypeOfClassOrInterface(symbol) {
55608             var links = getSymbolLinks(symbol);
55609             var originalLinks = links;
55610             if (!links.declaredType) {
55611                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
55612                 var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration));
55613                 if (merged) {
55614                     // note:we overwrite links because we just cloned the symbol
55615                     symbol = links = merged;
55616                 }
55617                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
55618                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
55619                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
55620                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
55621                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
55622                 // property types inferred from initializers and method return types inferred from return statements are very hard
55623                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
55624                 // "this" references.
55625                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
55626                     type.objectFlags |= 4 /* Reference */;
55627                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
55628                     type.outerTypeParameters = outerTypeParameters;
55629                     type.localTypeParameters = localTypeParameters;
55630                     type.instantiations = new ts.Map();
55631                     type.instantiations.set(getTypeListId(type.typeParameters), type);
55632                     type.target = type;
55633                     type.resolvedTypeArguments = type.typeParameters;
55634                     type.thisType = createTypeParameter(symbol);
55635                     type.thisType.isThisType = true;
55636                     type.thisType.constraint = type;
55637                 }
55638             }
55639             return links.declaredType;
55640         }
55641         function getDeclaredTypeOfTypeAlias(symbol) {
55642             var _a;
55643             var links = getSymbolLinks(symbol);
55644             if (!links.declaredType) {
55645                 // Note that we use the links object as the target here because the symbol object is used as the unique
55646                 // identity for resolution of the 'type' property in SymbolLinks.
55647                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
55648                     return errorType;
55649                 }
55650                 var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found");
55651                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
55652                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
55653                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
55654                 if (popTypeResolution()) {
55655                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
55656                     if (typeParameters) {
55657                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
55658                         // an instantiation of the type alias with the type parameters supplied as type arguments.
55659                         links.typeParameters = typeParameters;
55660                         links.instantiations = new ts.Map();
55661                         links.instantiations.set(getTypeListId(typeParameters), type);
55662                     }
55663                 }
55664                 else {
55665                     type = errorType;
55666                     if (declaration.kind === 337 /* JSDocEnumTag */) {
55667                         error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
55668                     }
55669                     else {
55670                         error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
55671                     }
55672                 }
55673                 links.declaredType = type;
55674             }
55675             return links.declaredType;
55676         }
55677         function isStringConcatExpression(expr) {
55678             if (ts.isStringLiteralLike(expr)) {
55679                 return true;
55680             }
55681             else if (expr.kind === 220 /* BinaryExpression */) {
55682                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
55683             }
55684             return false;
55685         }
55686         function isLiteralEnumMember(member) {
55687             var expr = member.initializer;
55688             if (!expr) {
55689                 return !(member.flags & 8388608 /* Ambient */);
55690             }
55691             switch (expr.kind) {
55692                 case 10 /* StringLiteral */:
55693                 case 8 /* NumericLiteral */:
55694                 case 14 /* NoSubstitutionTemplateLiteral */:
55695                     return true;
55696                 case 218 /* PrefixUnaryExpression */:
55697                     return expr.operator === 40 /* MinusToken */ &&
55698                         expr.operand.kind === 8 /* NumericLiteral */;
55699                 case 79 /* Identifier */:
55700                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
55701                 case 220 /* BinaryExpression */:
55702                     return isStringConcatExpression(expr);
55703                 default:
55704                     return false;
55705             }
55706         }
55707         function getEnumKind(symbol) {
55708             var links = getSymbolLinks(symbol);
55709             if (links.enumKind !== undefined) {
55710                 return links.enumKind;
55711             }
55712             var hasNonLiteralMember = false;
55713             if (symbol.declarations) {
55714                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
55715                     var declaration = _a[_i];
55716                     if (declaration.kind === 259 /* EnumDeclaration */) {
55717                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
55718                             var member = _c[_b];
55719                             if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
55720                                 return links.enumKind = 1 /* Literal */;
55721                             }
55722                             if (!isLiteralEnumMember(member)) {
55723                                 hasNonLiteralMember = true;
55724                             }
55725                         }
55726                     }
55727                 }
55728             }
55729             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
55730         }
55731         function getBaseTypeOfEnumLiteralType(type) {
55732             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
55733         }
55734         function getDeclaredTypeOfEnum(symbol) {
55735             var links = getSymbolLinks(symbol);
55736             if (links.declaredType) {
55737                 return links.declaredType;
55738             }
55739             if (getEnumKind(symbol) === 1 /* Literal */) {
55740                 enumCount++;
55741                 var memberTypeList = [];
55742                 if (symbol.declarations) {
55743                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
55744                         var declaration = _a[_i];
55745                         if (declaration.kind === 259 /* EnumDeclaration */) {
55746                             for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
55747                                 var member = _c[_b];
55748                                 var value = getEnumMemberValue(member);
55749                                 var memberType = getFreshTypeOfLiteralType(getEnumLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
55750                                 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
55751                                 memberTypeList.push(getRegularTypeOfLiteralType(memberType));
55752                             }
55753                         }
55754                     }
55755                 }
55756                 if (memberTypeList.length) {
55757                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
55758                     if (enumType_1.flags & 1048576 /* Union */) {
55759                         enumType_1.flags |= 1024 /* EnumLiteral */;
55760                         enumType_1.symbol = symbol;
55761                     }
55762                     return links.declaredType = enumType_1;
55763                 }
55764             }
55765             var enumType = createType(32 /* Enum */);
55766             enumType.symbol = symbol;
55767             return links.declaredType = enumType;
55768         }
55769         function getDeclaredTypeOfEnumMember(symbol) {
55770             var links = getSymbolLinks(symbol);
55771             if (!links.declaredType) {
55772                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
55773                 if (!links.declaredType) {
55774                     links.declaredType = enumType;
55775                 }
55776             }
55777             return links.declaredType;
55778         }
55779         function getDeclaredTypeOfTypeParameter(symbol) {
55780             var links = getSymbolLinks(symbol);
55781             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
55782         }
55783         function getDeclaredTypeOfAlias(symbol) {
55784             var links = getSymbolLinks(symbol);
55785             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
55786         }
55787         function getDeclaredTypeOfSymbol(symbol) {
55788             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
55789         }
55790         function tryGetDeclaredTypeOfSymbol(symbol) {
55791             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
55792                 return getDeclaredTypeOfClassOrInterface(symbol);
55793             }
55794             if (symbol.flags & 524288 /* TypeAlias */) {
55795                 return getDeclaredTypeOfTypeAlias(symbol);
55796             }
55797             if (symbol.flags & 262144 /* TypeParameter */) {
55798                 return getDeclaredTypeOfTypeParameter(symbol);
55799             }
55800             if (symbol.flags & 384 /* Enum */) {
55801                 return getDeclaredTypeOfEnum(symbol);
55802             }
55803             if (symbol.flags & 8 /* EnumMember */) {
55804                 return getDeclaredTypeOfEnumMember(symbol);
55805             }
55806             if (symbol.flags & 2097152 /* Alias */) {
55807                 return getDeclaredTypeOfAlias(symbol);
55808             }
55809             return undefined;
55810         }
55811         /**
55812          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
55813          * literal type, an array with an element type that is free of this references, or a type reference that is
55814          * free of this references.
55815          */
55816         function isThislessType(node) {
55817             switch (node.kind) {
55818                 case 130 /* AnyKeyword */:
55819                 case 154 /* UnknownKeyword */:
55820                 case 149 /* StringKeyword */:
55821                 case 146 /* NumberKeyword */:
55822                 case 157 /* BigIntKeyword */:
55823                 case 133 /* BooleanKeyword */:
55824                 case 150 /* SymbolKeyword */:
55825                 case 147 /* ObjectKeyword */:
55826                 case 114 /* VoidKeyword */:
55827                 case 152 /* UndefinedKeyword */:
55828                 case 143 /* NeverKeyword */:
55829                 case 195 /* LiteralType */:
55830                     return true;
55831                 case 182 /* ArrayType */:
55832                     return isThislessType(node.elementType);
55833                 case 177 /* TypeReference */:
55834                     return !node.typeArguments || node.typeArguments.every(isThislessType);
55835             }
55836             return false;
55837         }
55838         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
55839         function isThislessTypeParameter(node) {
55840             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
55841             return !constraint || isThislessType(constraint);
55842         }
55843         /**
55844          * A variable-like declaration is free of this references if it has a type annotation
55845          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
55846          */
55847         function isThislessVariableLikeDeclaration(node) {
55848             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
55849             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
55850         }
55851         /**
55852          * A function-like declaration is considered free of `this` references if it has a return type
55853          * annotation that is free of this references and if each parameter is thisless and if
55854          * each type parameter (if present) is thisless.
55855          */
55856         function isThislessFunctionLikeDeclaration(node) {
55857             var returnType = ts.getEffectiveReturnTypeNode(node);
55858             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
55859             return (node.kind === 170 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
55860                 node.parameters.every(isThislessVariableLikeDeclaration) &&
55861                 typeParameters.every(isThislessTypeParameter);
55862         }
55863         /**
55864          * Returns true if the class or interface member given by the symbol is free of "this" references. The
55865          * function may return false for symbols that are actually free of "this" references because it is not
55866          * feasible to perform a complete analysis in all cases. In particular, property members with types
55867          * inferred from their initializers and function members with inferred return types are conservatively
55868          * assumed not to be free of "this" references.
55869          */
55870         function isThisless(symbol) {
55871             if (symbol.declarations && symbol.declarations.length === 1) {
55872                 var declaration = symbol.declarations[0];
55873                 if (declaration) {
55874                     switch (declaration.kind) {
55875                         case 166 /* PropertyDeclaration */:
55876                         case 165 /* PropertySignature */:
55877                             return isThislessVariableLikeDeclaration(declaration);
55878                         case 168 /* MethodDeclaration */:
55879                         case 167 /* MethodSignature */:
55880                         case 170 /* Constructor */:
55881                         case 171 /* GetAccessor */:
55882                         case 172 /* SetAccessor */:
55883                             return isThislessFunctionLikeDeclaration(declaration);
55884                     }
55885                 }
55886             }
55887             return false;
55888         }
55889         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
55890         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
55891         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
55892             var result = ts.createSymbolTable();
55893             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
55894                 var symbol = symbols_2[_i];
55895                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
55896             }
55897             return result;
55898         }
55899         function addInheritedMembers(symbols, baseSymbols) {
55900             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
55901                 var s = baseSymbols_1[_i];
55902                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
55903                     symbols.set(s.escapedName, s);
55904                 }
55905             }
55906         }
55907         function isStaticPrivateIdentifierProperty(s) {
55908             return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.isStatic(s.valueDeclaration);
55909         }
55910         function resolveDeclaredMembers(type) {
55911             if (!type.declaredProperties) {
55912                 var symbol = type.symbol;
55913                 var members = getMembersOfSymbol(symbol);
55914                 type.declaredProperties = getNamedMembers(members);
55915                 // Start with signatures at empty array in case of recursive types
55916                 type.declaredCallSignatures = ts.emptyArray;
55917                 type.declaredConstructSignatures = ts.emptyArray;
55918                 type.declaredIndexInfos = ts.emptyArray;
55919                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
55920                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
55921                 type.declaredIndexInfos = getIndexInfosOfSymbol(symbol);
55922             }
55923             return type;
55924         }
55925         /**
55926          * Indicates whether a type can be used as a property name.
55927          */
55928         function isTypeUsableAsPropertyName(type) {
55929             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
55930         }
55931         /**
55932          * Indicates whether a declaration name is definitely late-bindable.
55933          * A declaration name is only late-bindable if:
55934          * - It is a `ComputedPropertyName`.
55935          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
55936          * `ElementAccessExpression` consisting only of these same three types of nodes.
55937          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
55938          */
55939         function isLateBindableName(node) {
55940             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
55941                 return false;
55942             }
55943             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
55944             return ts.isEntityNameExpression(expr)
55945                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
55946         }
55947         function isLateBoundName(name) {
55948             return name.charCodeAt(0) === 95 /* _ */ &&
55949                 name.charCodeAt(1) === 95 /* _ */ &&
55950                 name.charCodeAt(2) === 64 /* at */;
55951         }
55952         /**
55953          * Indicates whether a declaration has a late-bindable dynamic name.
55954          */
55955         function hasLateBindableName(node) {
55956             var name = ts.getNameOfDeclaration(node);
55957             return !!name && isLateBindableName(name);
55958         }
55959         /**
55960          * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound.
55961          */
55962         function hasBindableName(node) {
55963             return !ts.hasDynamicName(node) || hasLateBindableName(node);
55964         }
55965         /**
55966          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
55967          */
55968         function isNonBindableDynamicName(node) {
55969             return ts.isDynamicName(node) && !isLateBindableName(node);
55970         }
55971         /**
55972          * Gets the symbolic name for a member from its type.
55973          */
55974         function getPropertyNameFromType(type) {
55975             if (type.flags & 8192 /* UniqueESSymbol */) {
55976                 return type.escapedName;
55977             }
55978             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
55979                 return ts.escapeLeadingUnderscores("" + type.value);
55980             }
55981             return ts.Debug.fail();
55982         }
55983         /**
55984          * Adds a declaration to a late-bound dynamic member. This performs the same function for
55985          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
55986          * members.
55987          */
55988         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
55989             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
55990             symbol.flags |= symbolFlags;
55991             getSymbolLinks(member.symbol).lateSymbol = symbol;
55992             if (!symbol.declarations) {
55993                 symbol.declarations = [member];
55994             }
55995             else if (!member.symbol.isReplaceableByMethod) {
55996                 symbol.declarations.push(member);
55997             }
55998             if (symbolFlags & 111551 /* Value */) {
55999                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
56000                     symbol.valueDeclaration = member;
56001                 }
56002             }
56003         }
56004         /**
56005          * Performs late-binding of a dynamic member. This performs the same function for
56006          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
56007          * members.
56008          *
56009          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
56010          * binding phase to attempt to resolve the name for the symbol from the type of the computed
56011          * property's expression. If the type of the expression is a string-literal, numeric-literal,
56012          * or unique symbol type, we can use that type as the name of the symbol.
56013          *
56014          * For example, given:
56015          *
56016          *   const x = Symbol();
56017          *
56018          *   interface I {
56019          *     [x]: number;
56020          *   }
56021          *
56022          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
56023          * In the late-binding phase we can type-check the expression `x` and see that it has a
56024          * unique symbol type which we can then use as the name of the member. This allows users
56025          * to define custom symbols that can be used in the members of an object type.
56026          *
56027          * @param parent The containing symbol for the member.
56028          * @param earlySymbols The early-bound symbols of the parent.
56029          * @param lateSymbols The late-bound symbols of the parent.
56030          * @param decl The member to bind.
56031          */
56032         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
56033             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
56034             var links = getNodeLinks(decl);
56035             if (!links.resolvedSymbol) {
56036                 // In the event we attempt to resolve the late-bound name of this member recursively,
56037                 // fall back to the early-bound name of this member.
56038                 links.resolvedSymbol = decl.symbol;
56039                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
56040                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
56041                 if (isTypeUsableAsPropertyName(type)) {
56042                     var memberName = getPropertyNameFromType(type);
56043                     var symbolFlags = decl.symbol.flags;
56044                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
56045                     var lateSymbol = lateSymbols.get(memberName);
56046                     if (!lateSymbol)
56047                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
56048                     // Report an error if a late-bound member has the same name as an early-bound member,
56049                     // or if we have another early-bound symbol declaration with the same name and
56050                     // conflicting flags.
56051                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
56052                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
56053                         // If we have an existing early-bound member, combine its declarations so that we can
56054                         // report an error at each declaration.
56055                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
56056                         var name_4 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
56057                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_4); });
56058                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_4);
56059                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
56060                     }
56061                     lateSymbol.nameType = type;
56062                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
56063                     if (lateSymbol.parent) {
56064                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
56065                     }
56066                     else {
56067                         lateSymbol.parent = parent;
56068                     }
56069                     return links.resolvedSymbol = lateSymbol;
56070                 }
56071             }
56072             return links.resolvedSymbol;
56073         }
56074         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
56075             var links = getSymbolLinks(symbol);
56076             if (!links[resolutionKind]) {
56077                 var isStatic_1 = resolutionKind === "resolvedExports" /* resolvedExports */;
56078                 var earlySymbols = !isStatic_1 ? symbol.members :
56079                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
56080                         symbol.exports;
56081                 // In the event we recursively resolve the members/exports of the symbol, we
56082                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
56083                 // members/exports of the symbol.
56084                 links[resolutionKind] = earlySymbols || emptySymbols;
56085                 // fill in any as-yet-unresolved late-bound members.
56086                 var lateSymbols = ts.createSymbolTable();
56087                 for (var _i = 0, _a = symbol.declarations || ts.emptyArray; _i < _a.length; _i++) {
56088                     var decl = _a[_i];
56089                     var members = ts.getMembersOfDeclaration(decl);
56090                     if (members) {
56091                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
56092                             var member = members_5[_b];
56093                             if (isStatic_1 === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
56094                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
56095                             }
56096                         }
56097                     }
56098                 }
56099                 var assignments = symbol.assignmentDeclarationMembers;
56100                 if (assignments) {
56101                     var decls = ts.arrayFrom(assignments.values());
56102                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
56103                         var member = decls_1[_c];
56104                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
56105                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
56106                             || ts.isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind)
56107                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
56108                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
56109                         if (isStatic_1 === !isInstanceMember && hasLateBindableName(member)) {
56110                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
56111                         }
56112                     }
56113                 }
56114                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
56115             }
56116             return links[resolutionKind];
56117         }
56118         /**
56119          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
56120          *
56121          * For a description of late-binding, see `lateBindMember`.
56122          */
56123         function getMembersOfSymbol(symbol) {
56124             return symbol.flags & 6256 /* LateBindingContainer */
56125                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
56126                 : symbol.members || emptySymbols;
56127         }
56128         /**
56129          * If a symbol is the dynamic name of the member of an object type, get the late-bound
56130          * symbol of the member.
56131          *
56132          * For a description of late-binding, see `lateBindMember`.
56133          */
56134         function getLateBoundSymbol(symbol) {
56135             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
56136                 var links = getSymbolLinks(symbol);
56137                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
56138                     // force late binding of members/exports. This will set the late-bound symbol
56139                     var parent = getMergedSymbol(symbol.parent);
56140                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
56141                         getExportsOfSymbol(parent);
56142                     }
56143                     else {
56144                         getMembersOfSymbol(parent);
56145                     }
56146                 }
56147                 return links.lateSymbol || (links.lateSymbol = symbol);
56148             }
56149             return symbol;
56150         }
56151         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
56152             if (ts.getObjectFlags(type) & 4 /* Reference */) {
56153                 var target = type.target;
56154                 var typeArguments = getTypeArguments(type);
56155                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
56156                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
56157                     return needApparentType ? getApparentType(ref) : ref;
56158                 }
56159             }
56160             else if (type.flags & 2097152 /* Intersection */) {
56161                 var types = ts.sameMap(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); });
56162                 return types !== type.types ? getIntersectionType(types) : type;
56163             }
56164             return needApparentType ? getApparentType(type) : type;
56165         }
56166         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
56167             var mapper;
56168             var members;
56169             var callSignatures;
56170             var constructSignatures;
56171             var indexInfos;
56172             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
56173                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
56174                 callSignatures = source.declaredCallSignatures;
56175                 constructSignatures = source.declaredConstructSignatures;
56176                 indexInfos = source.declaredIndexInfos;
56177             }
56178             else {
56179                 mapper = createTypeMapper(typeParameters, typeArguments);
56180                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
56181                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
56182                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
56183                 indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper);
56184             }
56185             var baseTypes = getBaseTypes(source);
56186             if (baseTypes.length) {
56187                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
56188                     members = ts.createSymbolTable(source.declaredProperties);
56189                 }
56190                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
56191                 var thisArgument = ts.lastOrUndefined(typeArguments);
56192                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
56193                     var baseType = baseTypes_1[_i];
56194                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
56195                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
56196                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
56197                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
56198                     var inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [createIndexInfo(stringType, anyType, /*isReadonly*/ false)];
56199                     indexInfos = ts.concatenate(indexInfos, ts.filter(inheritedIndexInfos, function (info) { return !findIndexInfo(indexInfos, info.keyType); }));
56200                 }
56201             }
56202             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
56203         }
56204         function resolveClassOrInterfaceMembers(type) {
56205             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
56206         }
56207         function resolveTypeReferenceMembers(type) {
56208             var source = resolveDeclaredMembers(type.target);
56209             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
56210             var typeArguments = getTypeArguments(type);
56211             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
56212             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
56213         }
56214         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
56215             var sig = new Signature(checker, flags);
56216             sig.declaration = declaration;
56217             sig.typeParameters = typeParameters;
56218             sig.parameters = parameters;
56219             sig.thisParameter = thisParameter;
56220             sig.resolvedReturnType = resolvedReturnType;
56221             sig.resolvedTypePredicate = resolvedTypePredicate;
56222             sig.minArgumentCount = minArgumentCount;
56223             sig.resolvedMinArgumentCount = undefined;
56224             sig.target = undefined;
56225             sig.mapper = undefined;
56226             sig.compositeSignatures = undefined;
56227             sig.compositeKind = undefined;
56228             return sig;
56229         }
56230         function cloneSignature(sig) {
56231             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
56232             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */);
56233             result.target = sig.target;
56234             result.mapper = sig.mapper;
56235             result.compositeSignatures = sig.compositeSignatures;
56236             result.compositeKind = sig.compositeKind;
56237             return result;
56238         }
56239         function createUnionSignature(signature, unionSignatures) {
56240             var result = cloneSignature(signature);
56241             result.compositeSignatures = unionSignatures;
56242             result.compositeKind = 1048576 /* Union */;
56243             result.target = undefined;
56244             result.mapper = undefined;
56245             return result;
56246         }
56247         function getOptionalCallSignature(signature, callChainFlags) {
56248             if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) {
56249                 return signature;
56250             }
56251             if (!signature.optionalCallSignatureCache) {
56252                 signature.optionalCallSignatureCache = {};
56253             }
56254             var key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer";
56255             return signature.optionalCallSignatureCache[key]
56256                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
56257         }
56258         function createOptionalCallSignature(signature, callChainFlags) {
56259             ts.Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
56260             var result = cloneSignature(signature);
56261             result.flags |= callChainFlags;
56262             return result;
56263         }
56264         function getExpandedParameters(sig, skipUnionExpanding) {
56265             if (signatureHasRestParameter(sig)) {
56266                 var restIndex_1 = sig.parameters.length - 1;
56267                 var restType = getTypeOfSymbol(sig.parameters[restIndex_1]);
56268                 if (isTupleType(restType)) {
56269                     return [expandSignatureParametersWithTupleMembers(restType, restIndex_1)];
56270                 }
56271                 else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && ts.every(restType.types, isTupleType)) {
56272                     return ts.map(restType.types, function (t) { return expandSignatureParametersWithTupleMembers(t, restIndex_1); });
56273                 }
56274             }
56275             return [sig.parameters];
56276             function expandSignatureParametersWithTupleMembers(restType, restIndex) {
56277                 var elementTypes = getTypeArguments(restType);
56278                 var associatedNames = restType.target.labeledElementDeclarations;
56279                 var restParams = ts.map(elementTypes, function (t, i) {
56280                     // Lookup the label from the individual tuple passed in before falling back to the signature `rest` parameter name
56281                     var tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]);
56282                     var name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType);
56283                     var flags = restType.target.elementFlags[i];
56284                     var checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ :
56285                         flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
56286                     var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
56287                     symbol.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
56288                     return symbol;
56289                 });
56290                 return ts.concatenate(sig.parameters.slice(0, restIndex), restParams);
56291             }
56292         }
56293         function getDefaultConstructSignatures(classType) {
56294             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
56295             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
56296             var declaration = ts.getClassLikeDeclarationOfSymbol(classType.symbol);
56297             var isAbstract = !!declaration && ts.hasSyntacticModifier(declaration, 128 /* Abstract */);
56298             if (baseSignatures.length === 0) {
56299                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */)];
56300             }
56301             var baseTypeNode = getBaseTypeNodeOfClass(classType);
56302             var isJavaScript = ts.isInJSFile(baseTypeNode);
56303             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
56304             var typeArgCount = ts.length(typeArguments);
56305             var result = [];
56306             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
56307                 var baseSig = baseSignatures_1[_i];
56308                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
56309                 var typeParamCount = ts.length(baseSig.typeParameters);
56310                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
56311                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
56312                     sig.typeParameters = classType.localTypeParameters;
56313                     sig.resolvedReturnType = classType;
56314                     sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */;
56315                     result.push(sig);
56316                 }
56317             }
56318             return result;
56319         }
56320         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
56321             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
56322                 var s = signatureList_1[_i];
56323                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
56324                     return s;
56325                 }
56326             }
56327         }
56328         function findMatchingSignatures(signatureLists, signature, listIndex) {
56329             if (signature.typeParameters) {
56330                 // We require an exact match for generic signatures, so we only return signatures from the first
56331                 // signature list and only if they have exact matches in the other signature lists.
56332                 if (listIndex > 0) {
56333                     return undefined;
56334                 }
56335                 for (var i = 1; i < signatureLists.length; i++) {
56336                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
56337                         return undefined;
56338                     }
56339                 }
56340                 return [signature];
56341             }
56342             var result;
56343             for (var i = 0; i < signatureLists.length; i++) {
56344                 // Allow matching non-generic signatures to have excess parameters and different return types.
56345                 // Prefer matching this types if possible.
56346                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
56347                 if (!match) {
56348                     return undefined;
56349                 }
56350                 result = ts.appendIfUnique(result, match);
56351             }
56352             return result;
56353         }
56354         // The signatures of a union type are those signatures that are present in each of the constituent types.
56355         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
56356         // parameters and may differ in return types. When signatures differ in return types, the resulting return
56357         // type is the union of the constituent return types.
56358         function getUnionSignatures(signatureLists) {
56359             var result;
56360             var indexWithLengthOverOne;
56361             for (var i = 0; i < signatureLists.length; i++) {
56362                 if (signatureLists[i].length === 0)
56363                     return ts.emptyArray;
56364                 if (signatureLists[i].length > 1) {
56365                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
56366                 }
56367                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
56368                     var signature = _a[_i];
56369                     // Only process signatures with parameter lists that aren't already in the result list
56370                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
56371                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
56372                         if (unionSignatures) {
56373                             var s = signature;
56374                             // Union the result types when more than one signature matches
56375                             if (unionSignatures.length > 1) {
56376                                 var thisParameter = signature.thisParameter;
56377                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
56378                                 if (firstThisParameterOfUnionSignatures) {
56379                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
56380                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
56381                                 }
56382                                 s = createUnionSignature(signature, unionSignatures);
56383                                 s.thisParameter = thisParameter;
56384                             }
56385                             (result || (result = [])).push(s);
56386                         }
56387                     }
56388                 }
56389             }
56390             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
56391                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
56392                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
56393                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
56394                 // signatures from the type, whose ordering would be non-obvious)
56395                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
56396                 var results = masterList.slice();
56397                 var _loop_10 = function (signatures) {
56398                     if (signatures !== masterList) {
56399                         var signature_1 = signatures[0];
56400                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
56401                         results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
56402                         if (!results) {
56403                             return "break";
56404                         }
56405                     }
56406                 };
56407                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
56408                     var signatures = signatureLists_1[_b];
56409                     var state_3 = _loop_10(signatures);
56410                     if (state_3 === "break")
56411                         break;
56412                 }
56413                 result = results;
56414             }
56415             return result || ts.emptyArray;
56416         }
56417         function compareTypeParametersIdentical(sourceParams, targetParams) {
56418             if (ts.length(sourceParams) !== ts.length(targetParams)) {
56419                 return false;
56420             }
56421             if (!sourceParams || !targetParams) {
56422                 return true;
56423             }
56424             var mapper = createTypeMapper(targetParams, sourceParams);
56425             for (var i = 0; i < sourceParams.length; i++) {
56426                 var source = sourceParams[i];
56427                 var target = targetParams[i];
56428                 if (source === target)
56429                     continue;
56430                 // We instantiate the target type parameter constraints into the source types so we can recognize `<T, U extends T>` as the same as `<A, B extends A>`
56431                 if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper)))
56432                     return false;
56433                 // We don't compare defaults - we just use the type parameter defaults from the first signature that seems to match.
56434                 // It might make sense to combine these defaults in the future, but doing so intelligently requires knowing
56435                 // if the parameter is used covariantly or contravariantly (so we intersect if it's used like a parameter or union if used like a return type)
56436                 // and, since it's just an inference _default_, just picking one arbitrarily works OK.
56437             }
56438             return true;
56439         }
56440         function combineUnionThisParam(left, right, mapper) {
56441             if (!left || !right) {
56442                 return left || right;
56443             }
56444             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
56445             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
56446             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
56447             var thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
56448             return createSymbolWithType(left, thisType);
56449         }
56450         function combineUnionParameters(left, right, mapper) {
56451             var leftCount = getParameterCount(left);
56452             var rightCount = getParameterCount(right);
56453             var longest = leftCount >= rightCount ? left : right;
56454             var shorter = longest === left ? right : left;
56455             var longestCount = longest === left ? leftCount : rightCount;
56456             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
56457             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
56458             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
56459             for (var i = 0; i < longestCount; i++) {
56460                 var longestParamType = tryGetTypeAtPosition(longest, i);
56461                 if (longest === right) {
56462                     longestParamType = instantiateType(longestParamType, mapper);
56463                 }
56464                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
56465                 if (shorter === right) {
56466                     shorterParamType = instantiateType(shorterParamType, mapper);
56467                 }
56468                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
56469                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
56470                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
56471                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
56472                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
56473                 var paramName = leftName === rightName ? leftName :
56474                     !leftName ? rightName :
56475                         !rightName ? leftName :
56476                             undefined;
56477                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg".concat(i));
56478                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
56479                 params[i] = paramSymbol;
56480             }
56481             if (needsExtraRestElement) {
56482                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
56483                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
56484                 if (shorter === right) {
56485                     restParamSymbol.type = instantiateType(restParamSymbol.type, mapper);
56486                 }
56487                 params[longestCount] = restParamSymbol;
56488             }
56489             return params;
56490         }
56491         function combineSignaturesOfUnionMembers(left, right) {
56492             var typeParams = left.typeParameters || right.typeParameters;
56493             var paramMapper;
56494             if (left.typeParameters && right.typeParameters) {
56495                 paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
56496                 // We just use the type parameter defaults from the first signature
56497             }
56498             var declaration = left.declaration;
56499             var params = combineUnionParameters(left, right, paramMapper);
56500             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
56501             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
56502             var result = createSignature(declaration, typeParams, thisParam, params, 
56503             /*resolvedReturnType*/ undefined, 
56504             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */);
56505             result.compositeKind = 1048576 /* Union */;
56506             result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]);
56507             if (paramMapper) {
56508                 result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
56509             }
56510             return result;
56511         }
56512         function getUnionIndexInfos(types) {
56513             var sourceInfos = getIndexInfosOfType(types[0]);
56514             if (sourceInfos) {
56515                 var result = [];
56516                 var _loop_11 = function (info) {
56517                     var indexType = info.keyType;
56518                     if (ts.every(types, function (t) { return !!getIndexInfoOfType(t, indexType); })) {
56519                         result.push(createIndexInfo(indexType, getUnionType(ts.map(types, function (t) { return getIndexTypeOfType(t, indexType); })), ts.some(types, function (t) { return getIndexInfoOfType(t, indexType).isReadonly; })));
56520                     }
56521                 };
56522                 for (var _i = 0, sourceInfos_1 = sourceInfos; _i < sourceInfos_1.length; _i++) {
56523                     var info = sourceInfos_1[_i];
56524                     _loop_11(info);
56525                 }
56526                 return result;
56527             }
56528             return ts.emptyArray;
56529         }
56530         function resolveUnionTypeMembers(type) {
56531             // The members and properties collections are empty for union types. To get all properties of a union
56532             // type use getPropertiesOfType (only the language service uses this).
56533             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
56534             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
56535             var indexInfos = getUnionIndexInfos(type.types);
56536             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos);
56537         }
56538         function intersectTypes(type1, type2) {
56539             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
56540         }
56541         function findMixins(types) {
56542             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
56543             var mixinFlags = ts.map(types, isMixinConstructorType);
56544             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
56545                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
56546                 mixinFlags[firstMixinIndex] = false;
56547             }
56548             return mixinFlags;
56549         }
56550         function includeMixinType(type, types, mixinFlags, index) {
56551             var mixedTypes = [];
56552             for (var i = 0; i < types.length; i++) {
56553                 if (i === index) {
56554                     mixedTypes.push(type);
56555                 }
56556                 else if (mixinFlags[i]) {
56557                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
56558                 }
56559             }
56560             return getIntersectionType(mixedTypes);
56561         }
56562         function resolveIntersectionTypeMembers(type) {
56563             // The members and properties collections are empty for intersection types. To get all properties of an
56564             // intersection type use getPropertiesOfType (only the language service uses this).
56565             var callSignatures;
56566             var constructSignatures;
56567             var indexInfos;
56568             var types = type.types;
56569             var mixinFlags = findMixins(types);
56570             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
56571             var _loop_12 = function (i) {
56572                 var t = type.types[i];
56573                 // When an intersection type contains mixin constructor types, the construct signatures from
56574                 // those types are discarded and their return types are mixed into the return types of all
56575                 // other construct signatures in the intersection type. For example, the intersection type
56576                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
56577                 // 'new(s: string) => A & B'.
56578                 if (!mixinFlags[i]) {
56579                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
56580                     if (signatures.length && mixinCount > 0) {
56581                         signatures = ts.map(signatures, function (s) {
56582                             var clone = cloneSignature(s);
56583                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
56584                             return clone;
56585                         });
56586                     }
56587                     constructSignatures = appendSignatures(constructSignatures, signatures);
56588                 }
56589                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
56590                 indexInfos = ts.reduceLeft(getIndexInfosOfType(t), function (infos, newInfo) { return appendIndexInfo(infos, newInfo, /*union*/ false); }, indexInfos);
56591             };
56592             for (var i = 0; i < types.length; i++) {
56593                 _loop_12(i);
56594             }
56595             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, indexInfos || ts.emptyArray);
56596         }
56597         function appendSignatures(signatures, newSignatures) {
56598             var _loop_13 = function (sig) {
56599                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
56600                     signatures = ts.append(signatures, sig);
56601                 }
56602             };
56603             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
56604                 var sig = newSignatures_1[_i];
56605                 _loop_13(sig);
56606             }
56607             return signatures;
56608         }
56609         function appendIndexInfo(indexInfos, newInfo, union) {
56610             if (indexInfos) {
56611                 for (var i = 0; i < indexInfos.length; i++) {
56612                     var info = indexInfos[i];
56613                     if (info.keyType === newInfo.keyType) {
56614                         indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly);
56615                         return indexInfos;
56616                     }
56617                 }
56618             }
56619             return ts.append(indexInfos, newInfo);
56620         }
56621         /**
56622          * Converts an AnonymousType to a ResolvedType.
56623          */
56624         function resolveAnonymousTypeMembers(type) {
56625             var symbol = getMergedSymbol(type.symbol);
56626             if (type.target) {
56627                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
56628                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
56629                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
56630                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
56631                 var indexInfos = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper);
56632                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
56633             }
56634             else if (symbol.flags & 2048 /* TypeLiteral */) {
56635                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
56636                 var members = getMembersOfSymbol(symbol);
56637                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
56638                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
56639                 var indexInfos = getIndexInfosOfSymbol(symbol);
56640                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
56641             }
56642             else {
56643                 // Combinations of function, class, enum and module
56644                 var members = emptySymbols;
56645                 var indexInfos = void 0;
56646                 if (symbol.exports) {
56647                     members = getExportsOfSymbol(symbol);
56648                     if (symbol === globalThisSymbol) {
56649                         var varsOnly_1 = new ts.Map();
56650                         members.forEach(function (p) {
56651                             if (!(p.flags & 418 /* BlockScoped */)) {
56652                                 varsOnly_1.set(p.escapedName, p);
56653                             }
56654                         });
56655                         members = varsOnly_1;
56656                     }
56657                 }
56658                 var baseConstructorIndexInfo = void 0;
56659                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, ts.emptyArray);
56660                 if (symbol.flags & 32 /* Class */) {
56661                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
56662                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
56663                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
56664                         members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members));
56665                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
56666                     }
56667                     else if (baseConstructorType === anyType) {
56668                         baseConstructorIndexInfo = createIndexInfo(stringType, anyType, /*isReadonly*/ false);
56669                     }
56670                 }
56671                 var indexSymbol = getIndexSymbolFromSymbolTable(members);
56672                 if (indexSymbol) {
56673                     indexInfos = getIndexInfosOfIndexSymbol(indexSymbol);
56674                 }
56675                 else {
56676                     if (baseConstructorIndexInfo) {
56677                         indexInfos = ts.append(indexInfos, baseConstructorIndexInfo);
56678                     }
56679                     if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
56680                         ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) {
56681                         indexInfos = ts.append(indexInfos, enumNumberIndexInfo);
56682                     }
56683                 }
56684                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, indexInfos || ts.emptyArray);
56685                 // We resolve the members before computing the signatures because a signature may use
56686                 // typeof with a qualified name expression that circularly references the type we are
56687                 // in the process of resolving (see issue #6072). The temporarily empty signature list
56688                 // will never be observed because a qualified name can't reference signatures.
56689                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
56690                     type.callSignatures = getSignaturesOfSymbol(symbol);
56691                 }
56692                 // And likewise for construct signatures for classes
56693                 if (symbol.flags & 32 /* Class */) {
56694                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
56695                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
56696                     if (symbol.flags & 16 /* Function */) {
56697                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
56698                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */) :
56699                             undefined; }));
56700                     }
56701                     if (!constructSignatures.length) {
56702                         constructSignatures = getDefaultConstructSignatures(classType_1);
56703                     }
56704                     type.constructSignatures = constructSignatures;
56705                 }
56706             }
56707         }
56708         function replaceIndexedAccess(instantiable, type, replacement) {
56709             // map type.indexType to 0
56710             // map type.objectType to `[TReplacement]`
56711             // thus making the indexed access `[TReplacement][0]` or `TReplacement`
56712             return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getNumberLiteralType(0), createTupleType([replacement])]));
56713         }
56714         function resolveReverseMappedTypeMembers(type) {
56715             var indexInfo = getIndexInfoOfType(type.source, stringType);
56716             var modifiers = getMappedTypeModifiers(type.mappedType);
56717             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
56718             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
56719             var indexInfos = indexInfo ? [createIndexInfo(stringType, inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly)] : ts.emptyArray;
56720             var members = ts.createSymbolTable();
56721             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
56722                 var prop = _a[_i];
56723                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
56724                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
56725                 inferredProp.declarations = prop.declarations;
56726                 inferredProp.nameType = getSymbolLinks(prop).nameType;
56727                 inferredProp.propertyType = getTypeOfSymbol(prop);
56728                 if (type.constraintType.type.flags & 8388608 /* IndexedAccess */
56729                     && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */
56730                     && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) {
56731                     // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is
56732                     // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of
56733                     // type identities produced, we simplify such indexed access occurences
56734                     var newTypeParam = type.constraintType.type.objectType;
56735                     var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam);
56736                     inferredProp.mappedType = newMappedType;
56737                     inferredProp.constraintType = getIndexType(newTypeParam);
56738                 }
56739                 else {
56740                     inferredProp.mappedType = type.mappedType;
56741                     inferredProp.constraintType = type.constraintType;
56742                 }
56743                 members.set(prop.escapedName, inferredProp);
56744             }
56745             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, indexInfos);
56746         }
56747         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
56748         // bound includes those keys that are known to always be present, for example because
56749         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
56750         function getLowerBoundOfKeyType(type) {
56751             if (type.flags & 4194304 /* Index */) {
56752                 var t = getApparentType(type.type);
56753                 return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
56754             }
56755             if (type.flags & 16777216 /* Conditional */) {
56756                 if (type.root.isDistributive) {
56757                     var checkType = type.checkType;
56758                     var constraint = getLowerBoundOfKeyType(checkType);
56759                     if (constraint !== checkType) {
56760                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
56761                     }
56762                 }
56763                 return type;
56764             }
56765             if (type.flags & 1048576 /* Union */) {
56766                 return mapType(type, getLowerBoundOfKeyType);
56767             }
56768             if (type.flags & 2097152 /* Intersection */) {
56769                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
56770             }
56771             return type;
56772         }
56773         function getIsLateCheckFlag(s) {
56774             return ts.getCheckFlags(s) & 4096 /* Late */;
56775         }
56776         function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) {
56777             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56778                 var prop = _a[_i];
56779                 cb(getLiteralTypeFromProperty(prop, include));
56780             }
56781             if (type.flags & 1 /* Any */) {
56782                 cb(stringType);
56783             }
56784             else {
56785                 for (var _b = 0, _c = getIndexInfosOfType(type); _b < _c.length; _b++) {
56786                     var info = _c[_b];
56787                     if (!stringsOnly || info.keyType.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
56788                         cb(info.keyType);
56789                     }
56790                 }
56791             }
56792         }
56793         /** Resolve the members of a mapped type { [P in K]: T } */
56794         function resolveMappedTypeMembers(type) {
56795             var members = ts.createSymbolTable();
56796             var indexInfos;
56797             // Resolve upfront such that recursive references see an empty object type.
56798             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
56799             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
56800             // and T as the template type.
56801             var typeParameter = getTypeParameterFromMappedType(type);
56802             var constraintType = getConstraintTypeFromMappedType(type);
56803             var nameType = getNameTypeFromMappedType(type.target || type);
56804             var templateType = getTemplateTypeFromMappedType(type.target || type);
56805             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
56806             var templateModifiers = getMappedTypeModifiers(type);
56807             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
56808             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
56809                 // We have a { [P in keyof T]: X }
56810                 forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, include, keyofStringsOnly, addMemberForKeyType);
56811             }
56812             else {
56813                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
56814             }
56815             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, indexInfos || ts.emptyArray);
56816             function addMemberForKeyType(keyType) {
56817                 var propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
56818                 forEachType(propNameType, function (t) { return addMemberForKeyTypeWorker(keyType, t); });
56819             }
56820             function addMemberForKeyTypeWorker(keyType, propNameType) {
56821                 // If the current iteration type constituent is a string literal type, create a property.
56822                 // Otherwise, for type string create a string index signature.
56823                 if (isTypeUsableAsPropertyName(propNameType)) {
56824                     var propName = getPropertyNameFromType(propNameType);
56825                     // String enum members from separate enums with identical values
56826                     // are distinct types with the same property name. Make the resulting
56827                     // property symbol's name type be the union of those enum member types.
56828                     var existingProp = members.get(propName);
56829                     if (existingProp) {
56830                         existingProp.nameType = getUnionType([existingProp.nameType, propNameType]);
56831                         existingProp.keyType = getUnionType([existingProp.keyType, keyType]);
56832                     }
56833                     else {
56834                         var modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : undefined;
56835                         var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
56836                             !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
56837                         var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
56838                             !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
56839                         var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
56840                         var lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
56841                         var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
56842                         prop.mappedType = type;
56843                         prop.nameType = propNameType;
56844                         prop.keyType = keyType;
56845                         if (modifiersProp) {
56846                             prop.syntheticOrigin = modifiersProp;
56847                             // If the mapped type has an `as XXX` clause, the property name likely won't match the declaration name and
56848                             // multiple properties may map to the same name. Thus, we attach no declarations to the symbol.
56849                             prop.declarations = nameType ? undefined : modifiersProp.declarations;
56850                         }
56851                         members.set(propName, prop);
56852                     }
56853                 }
56854                 else if (isValidIndexKeyType(propNameType) || propNameType.flags & (1 /* Any */ | 32 /* Enum */)) {
56855                     var indexKeyType = propNameType.flags & (1 /* Any */ | 4 /* String */) ? stringType :
56856                         propNameType.flags & (8 /* Number */ | 32 /* Enum */) ? numberType :
56857                             propNameType;
56858                     var propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
56859                     var indexInfo = createIndexInfo(indexKeyType, propType, !!(templateModifiers & 1 /* IncludeReadonly */));
56860                     indexInfos = appendIndexInfo(indexInfos, indexInfo, /*union*/ true);
56861                 }
56862             }
56863         }
56864         function getTypeOfMappedSymbol(symbol) {
56865             if (!symbol.type) {
56866                 var mappedType = symbol.mappedType;
56867                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
56868                     mappedType.containsError = true;
56869                     return errorType;
56870                 }
56871                 var templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
56872                 var mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.keyType);
56873                 var propType = instantiateType(templateType, mapper);
56874                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
56875                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
56876                 // mode, if the underlying property is optional we remove 'undefined' from the type.
56877                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType, /*isProperty*/ true) :
56878                     symbol.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) :
56879                         propType;
56880                 if (!popTypeResolution()) {
56881                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
56882                     type = errorType;
56883                 }
56884                 symbol.type = type;
56885             }
56886             return symbol.type;
56887         }
56888         function getTypeParameterFromMappedType(type) {
56889             return type.typeParameter ||
56890                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
56891         }
56892         function getConstraintTypeFromMappedType(type) {
56893             return type.constraintType ||
56894                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
56895         }
56896         function getNameTypeFromMappedType(type) {
56897             return type.declaration.nameType ?
56898                 type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) :
56899                 undefined;
56900         }
56901         function getTemplateTypeFromMappedType(type) {
56902             return type.templateType ||
56903                 (type.templateType = type.declaration.type ?
56904                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), /*isProperty*/ true, !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
56905                     errorType);
56906         }
56907         function getConstraintDeclarationForMappedType(type) {
56908             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
56909         }
56910         function isMappedTypeWithKeyofConstraintDeclaration(type) {
56911             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
56912             return constraintDeclaration.kind === 192 /* TypeOperator */ &&
56913                 constraintDeclaration.operator === 140 /* KeyOfKeyword */;
56914         }
56915         function getModifiersTypeFromMappedType(type) {
56916             if (!type.modifiersType) {
56917                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
56918                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
56919                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
56920                     // 'keyof T' to a literal union type and we can't recover T from that type.
56921                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
56922                 }
56923                 else {
56924                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
56925                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
56926                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
56927                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
56928                     var constraint = getConstraintTypeFromMappedType(declaredType);
56929                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
56930                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
56931                 }
56932             }
56933             return type.modifiersType;
56934         }
56935         function getMappedTypeModifiers(type) {
56936             var declaration = type.declaration;
56937             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
56938                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
56939         }
56940         function getMappedTypeOptionality(type) {
56941             var modifiers = getMappedTypeModifiers(type);
56942             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
56943         }
56944         function getCombinedMappedTypeOptionality(type) {
56945             var optionality = getMappedTypeOptionality(type);
56946             var modifiersType = getModifiersTypeFromMappedType(type);
56947             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
56948         }
56949         function isPartialMappedType(type) {
56950             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
56951         }
56952         function isGenericMappedType(type) {
56953             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
56954         }
56955         function resolveStructuredTypeMembers(type) {
56956             if (!type.members) {
56957                 if (type.flags & 524288 /* Object */) {
56958                     if (type.objectFlags & 4 /* Reference */) {
56959                         resolveTypeReferenceMembers(type);
56960                     }
56961                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
56962                         resolveClassOrInterfaceMembers(type);
56963                     }
56964                     else if (type.objectFlags & 1024 /* ReverseMapped */) {
56965                         resolveReverseMappedTypeMembers(type);
56966                     }
56967                     else if (type.objectFlags & 16 /* Anonymous */) {
56968                         resolveAnonymousTypeMembers(type);
56969                     }
56970                     else if (type.objectFlags & 32 /* Mapped */) {
56971                         resolveMappedTypeMembers(type);
56972                     }
56973                 }
56974                 else if (type.flags & 1048576 /* Union */) {
56975                     resolveUnionTypeMembers(type);
56976                 }
56977                 else if (type.flags & 2097152 /* Intersection */) {
56978                     resolveIntersectionTypeMembers(type);
56979                 }
56980             }
56981             return type;
56982         }
56983         /** Return properties of an object type or an empty array for other types */
56984         function getPropertiesOfObjectType(type) {
56985             if (type.flags & 524288 /* Object */) {
56986                 return resolveStructuredTypeMembers(type).properties;
56987             }
56988             return ts.emptyArray;
56989         }
56990         /** If the given type is an object type and that type has a property by the given name,
56991          * return the symbol for that property. Otherwise return undefined.
56992          */
56993         function getPropertyOfObjectType(type, name) {
56994             if (type.flags & 524288 /* Object */) {
56995                 var resolved = resolveStructuredTypeMembers(type);
56996                 var symbol = resolved.members.get(name);
56997                 if (symbol && symbolIsValue(symbol)) {
56998                     return symbol;
56999                 }
57000             }
57001         }
57002         function getPropertiesOfUnionOrIntersectionType(type) {
57003             if (!type.resolvedProperties) {
57004                 var members = ts.createSymbolTable();
57005                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
57006                     var current = _a[_i];
57007                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
57008                         var prop = _c[_b];
57009                         if (!members.has(prop.escapedName)) {
57010                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
57011                             if (combinedProp) {
57012                                 members.set(prop.escapedName, combinedProp);
57013                             }
57014                         }
57015                     }
57016                     // The properties of a union type are those that are present in all constituent types, so
57017                     // we only need to check the properties of the first type without index signature
57018                     if (type.flags & 1048576 /* Union */ && getIndexInfosOfType(current).length === 0) {
57019                         break;
57020                     }
57021                 }
57022                 type.resolvedProperties = getNamedMembers(members);
57023             }
57024             return type.resolvedProperties;
57025         }
57026         function getPropertiesOfType(type) {
57027             type = getReducedApparentType(type);
57028             return type.flags & 3145728 /* UnionOrIntersection */ ?
57029                 getPropertiesOfUnionOrIntersectionType(type) :
57030                 getPropertiesOfObjectType(type);
57031         }
57032         function forEachPropertyOfType(type, action) {
57033             type = getReducedApparentType(type);
57034             if (type.flags & 3670016 /* StructuredType */) {
57035                 resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) {
57036                     if (isNamedMember(symbol, escapedName)) {
57037                         action(symbol, escapedName);
57038                     }
57039                 });
57040             }
57041         }
57042         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
57043             var list = obj.properties;
57044             return list.some(function (property) {
57045                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
57046                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
57047                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
57048                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
57049             });
57050         }
57051         function getAllPossiblePropertiesOfTypes(types) {
57052             var unionType = getUnionType(types);
57053             if (!(unionType.flags & 1048576 /* Union */)) {
57054                 return getAugmentedPropertiesOfType(unionType);
57055             }
57056             var props = ts.createSymbolTable();
57057             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
57058                 var memberType = types_4[_i];
57059                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
57060                     var escapedName = _b[_a].escapedName;
57061                     if (!props.has(escapedName)) {
57062                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
57063                         // May be undefined if the property is private
57064                         if (prop)
57065                             props.set(escapedName, prop);
57066                     }
57067                 }
57068             }
57069             return ts.arrayFrom(props.values());
57070         }
57071         function getConstraintOfType(type) {
57072             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
57073                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
57074                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
57075                         getBaseConstraintOfType(type);
57076         }
57077         function getConstraintOfTypeParameter(typeParameter) {
57078             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
57079         }
57080         function getConstraintOfIndexedAccess(type) {
57081             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
57082         }
57083         function getSimplifiedTypeOrConstraint(type) {
57084             var simplified = getSimplifiedType(type, /*writing*/ false);
57085             return simplified !== type ? simplified : getConstraintOfType(type);
57086         }
57087         function getConstraintFromIndexedAccess(type) {
57088             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
57089             if (indexConstraint && indexConstraint !== type.indexType) {
57090                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags);
57091                 if (indexedAccess) {
57092                     return indexedAccess;
57093                 }
57094             }
57095             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
57096             if (objectConstraint && objectConstraint !== type.objectType) {
57097                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags);
57098             }
57099             return undefined;
57100         }
57101         function getDefaultConstraintOfConditionalType(type) {
57102             if (!type.resolvedDefaultConstraint) {
57103                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
57104                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
57105                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
57106                 // in effect treating `any` like `never` rather than `unknown` in this location.
57107                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
57108                 var falseConstraint = getFalseTypeFromConditionalType(type);
57109                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
57110             }
57111             return type.resolvedDefaultConstraint;
57112         }
57113         function getConstraintOfDistributiveConditionalType(type) {
57114             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
57115             // type parameter. If so, create an instantiation of the conditional type where T is replaced
57116             // with its constraint. We do this because if the constraint is a union type it will be distributed
57117             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
57118             // removes 'undefined' from T.
57119             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
57120             // as the constraint for all type params (check type included) have been replace with `unknown`, which
57121             // is going to produce even more false positive/negative results than the distribute constraint already does.
57122             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
57123             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
57124             // likely doesn't need to exist.
57125             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
57126                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
57127                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
57128                 if (constraint && constraint !== type.checkType) {
57129                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
57130                     if (!(instantiated.flags & 131072 /* Never */)) {
57131                         return instantiated;
57132                     }
57133                 }
57134             }
57135             return undefined;
57136         }
57137         function getConstraintFromConditionalType(type) {
57138             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
57139         }
57140         function getConstraintOfConditionalType(type) {
57141             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
57142         }
57143         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
57144             var constraints;
57145             var hasDisjointDomainType = false;
57146             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
57147                 var t = types_5[_i];
57148                 if (t.flags & 465829888 /* Instantiable */) {
57149                     // We keep following constraints as long as we have an instantiable type that is known
57150                     // not to be circular or infinite (hence we stop on index access types).
57151                     var constraint = getConstraintOfType(t);
57152                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
57153                         constraint = getConstraintOfType(constraint);
57154                     }
57155                     if (constraint) {
57156                         constraints = ts.append(constraints, constraint);
57157                         if (targetIsUnion) {
57158                             constraints = ts.append(constraints, t);
57159                         }
57160                     }
57161                 }
57162                 else if (t.flags & 469892092 /* DisjointDomains */) {
57163                     hasDisjointDomainType = true;
57164                 }
57165             }
57166             // If the target is a union type or if we are intersecting with types belonging to one of the
57167             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
57168             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
57169                 if (hasDisjointDomainType) {
57170                     // We add any types belong to one of the disjoint domains because they might cause the final
57171                     // intersection operation to reduce the union constraints.
57172                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
57173                         var t = types_6[_a];
57174                         if (t.flags & 469892092 /* DisjointDomains */) {
57175                             constraints = ts.append(constraints, t);
57176                         }
57177                     }
57178                 }
57179                 return getIntersectionType(constraints);
57180             }
57181             return undefined;
57182         }
57183         function getBaseConstraintOfType(type) {
57184             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) {
57185                 var constraint = getResolvedBaseConstraint(type);
57186                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
57187             }
57188             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
57189         }
57190         /**
57191          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
57192          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
57193          */
57194         function getBaseConstraintOrType(type) {
57195             return getBaseConstraintOfType(type) || type;
57196         }
57197         function hasNonCircularBaseConstraint(type) {
57198             return getResolvedBaseConstraint(type) !== circularConstraintType;
57199         }
57200         /**
57201          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
57202          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
57203          * circularly references the type variable.
57204          */
57205         function getResolvedBaseConstraint(type) {
57206             if (type.resolvedBaseConstraint) {
57207                 return type.resolvedBaseConstraint;
57208             }
57209             var stack = [];
57210             return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type);
57211             function getImmediateBaseConstraint(t) {
57212                 if (!t.immediateBaseConstraint) {
57213                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
57214                         return circularConstraintType;
57215                     }
57216                     var result = void 0;
57217                     // We always explore at least 10 levels of nested constraints. Thereafter, we continue to explore
57218                     // up to 50 levels of nested constraints provided there are no "deeply nested" types on the stack
57219                     // (i.e. no types for which five instantiations have been recorded on the stack). If we reach 50
57220                     // levels of nesting, we are presumably exploring a repeating pattern with a long cycle that hasn't
57221                     // yet triggered the deeply nested limiter. We have no test cases that actually get to 50 levels of
57222                     // nesting, so it is effectively just a safety stop.
57223                     if (stack.length < 10 || stack.length < 50 && !isDeeplyNestedType(t, stack, stack.length)) {
57224                         stack.push(t);
57225                         result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
57226                         stack.pop();
57227                     }
57228                     if (!popTypeResolution()) {
57229                         if (t.flags & 262144 /* TypeParameter */) {
57230                             var errorNode = getConstraintDeclaration(t);
57231                             if (errorNode) {
57232                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
57233                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
57234                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
57235                                 }
57236                             }
57237                         }
57238                         result = circularConstraintType;
57239                     }
57240                     t.immediateBaseConstraint = result || noConstraintType;
57241                 }
57242                 return t.immediateBaseConstraint;
57243             }
57244             function getBaseConstraint(t) {
57245                 var c = getImmediateBaseConstraint(t);
57246                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
57247             }
57248             function computeBaseConstraint(t) {
57249                 if (t.flags & 262144 /* TypeParameter */) {
57250                     var constraint = getConstraintFromTypeParameter(t);
57251                     return t.isThisType || !constraint ?
57252                         constraint :
57253                         getBaseConstraint(constraint);
57254                 }
57255                 if (t.flags & 3145728 /* UnionOrIntersection */) {
57256                     var types = t.types;
57257                     var baseTypes = [];
57258                     var different = false;
57259                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
57260                         var type_3 = types_7[_i];
57261                         var baseType = getBaseConstraint(type_3);
57262                         if (baseType) {
57263                             if (baseType !== type_3) {
57264                                 different = true;
57265                             }
57266                             baseTypes.push(baseType);
57267                         }
57268                         else {
57269                             different = true;
57270                         }
57271                     }
57272                     if (!different) {
57273                         return t;
57274                     }
57275                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
57276                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
57277                             undefined;
57278                 }
57279                 if (t.flags & 4194304 /* Index */) {
57280                     return keyofConstraintType;
57281                 }
57282                 if (t.flags & 134217728 /* TemplateLiteral */) {
57283                     var types = t.types;
57284                     var constraints = ts.mapDefined(types, getBaseConstraint);
57285                     return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
57286                 }
57287                 if (t.flags & 268435456 /* StringMapping */) {
57288                     var constraint = getBaseConstraint(t.type);
57289                     return constraint ? getStringMappingType(t.symbol, constraint) : stringType;
57290                 }
57291                 if (t.flags & 8388608 /* IndexedAccess */) {
57292                     var baseObjectType = getBaseConstraint(t.objectType);
57293                     var baseIndexType = getBaseConstraint(t.indexType);
57294                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags);
57295                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
57296                 }
57297                 if (t.flags & 16777216 /* Conditional */) {
57298                     var constraint = getConstraintFromConditionalType(t);
57299                     return constraint && getBaseConstraint(constraint);
57300                 }
57301                 if (t.flags & 33554432 /* Substitution */) {
57302                     return getBaseConstraint(t.substitute);
57303                 }
57304                 return t;
57305             }
57306         }
57307         function getApparentTypeOfIntersectionType(type) {
57308             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
57309         }
57310         function getResolvedTypeParameterDefault(typeParameter) {
57311             if (!typeParameter.default) {
57312                 if (typeParameter.target) {
57313                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
57314                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
57315                 }
57316                 else {
57317                     // To block recursion, set the initial value to the resolvingDefaultType.
57318                     typeParameter.default = resolvingDefaultType;
57319                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
57320                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
57321                     if (typeParameter.default === resolvingDefaultType) {
57322                         // If we have not been called recursively, set the correct default type.
57323                         typeParameter.default = defaultType;
57324                     }
57325                 }
57326             }
57327             else if (typeParameter.default === resolvingDefaultType) {
57328                 // If we are called recursively for this type parameter, mark the default as circular.
57329                 typeParameter.default = circularConstraintType;
57330             }
57331             return typeParameter.default;
57332         }
57333         /**
57334          * Gets the default type for a type parameter.
57335          *
57336          * If the type parameter is the result of an instantiation, this gets the instantiated
57337          * default type of its target. If the type parameter has no default type or the default is
57338          * circular, `undefined` is returned.
57339          */
57340         function getDefaultFromTypeParameter(typeParameter) {
57341             var defaultType = getResolvedTypeParameterDefault(typeParameter);
57342             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
57343         }
57344         function hasNonCircularTypeParameterDefault(typeParameter) {
57345             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
57346         }
57347         /**
57348          * Indicates whether the declaration of a typeParameter has a default type.
57349          */
57350         function hasTypeParameterDefault(typeParameter) {
57351             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
57352         }
57353         function getApparentTypeOfMappedType(type) {
57354             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
57355         }
57356         function getResolvedApparentTypeOfMappedType(type) {
57357             var typeVariable = getHomomorphicTypeVariable(type);
57358             if (typeVariable && !type.declaration.nameType) {
57359                 var constraint = getConstraintOfTypeParameter(typeVariable);
57360                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
57361                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
57362                 }
57363             }
57364             return type;
57365         }
57366         /**
57367          * For a type parameter, return the base constraint of the type parameter. For the string, number,
57368          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
57369          * type itself.
57370          */
57371         function getApparentType(type) {
57372             var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
57373             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
57374                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
57375                     t.flags & 402653316 /* StringLike */ ? globalStringType :
57376                         t.flags & 296 /* NumberLike */ ? globalNumberType :
57377                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
57378                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
57379                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
57380                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
57381                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
57382                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
57383                                                     t;
57384         }
57385         function getReducedApparentType(type) {
57386             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
57387             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
57388             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
57389             // that type may need further reduction to remove empty intersections.
57390             return getReducedType(getApparentType(getReducedType(type)));
57391         }
57392         function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
57393             var _a, _b;
57394             var singleProp;
57395             var propSet;
57396             var indexTypes;
57397             var isUnion = containingType.flags & 1048576 /* Union */;
57398             // Flags we want to propagate to the result if they exist in all source symbols
57399             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
57400             var syntheticFlag = 4 /* SyntheticMethod */;
57401             var checkFlags = isUnion ? 0 : 8 /* Readonly */;
57402             var mergedInstantiations = false;
57403             for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) {
57404                 var current = _c[_i];
57405                 var type = getApparentType(current);
57406                 if (!(isErrorType(type) || type.flags & 131072 /* Never */)) {
57407                     var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
57408                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
57409                     if (prop) {
57410                         if (isUnion) {
57411                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
57412                         }
57413                         else {
57414                             optionalFlag &= prop.flags;
57415                         }
57416                         if (!singleProp) {
57417                             singleProp = prop;
57418                         }
57419                         else if (prop !== singleProp) {
57420                             var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp);
57421                             // If the symbols are instances of one another with identical types - consider the symbols
57422                             // equivalent and just use the first one, which thus allows us to avoid eliding private
57423                             // members when intersecting a (this-)instantiations of a class with it's raw base or another instance
57424                             if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) {
57425                                 // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used
57426                                 // to do when we recorded multiple distinct symbols so that we still get, eg, `Array<T>.length` printed
57427                                 // back and not `Array<string>.length` when we're looking at a `.length` access on a `string[] | number[]`
57428                                 mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent));
57429                             }
57430                             else {
57431                                 if (!propSet) {
57432                                     propSet = new ts.Map();
57433                                     propSet.set(getSymbolId(singleProp), singleProp);
57434                                 }
57435                                 var id = getSymbolId(prop);
57436                                 if (!propSet.has(id)) {
57437                                     propSet.set(id, prop);
57438                                 }
57439                             }
57440                         }
57441                         if (isUnion && isReadonlySymbol(prop)) {
57442                             checkFlags |= 8 /* Readonly */;
57443                         }
57444                         else if (!isUnion && !isReadonlySymbol(prop)) {
57445                             checkFlags &= ~8 /* Readonly */;
57446                         }
57447                         checkFlags |= (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
57448                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
57449                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
57450                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
57451                         if (!isPrototypeProperty(prop)) {
57452                             syntheticFlag = 2 /* SyntheticProperty */;
57453                         }
57454                     }
57455                     else if (isUnion) {
57456                         var indexInfo = !isLateBoundName(name) && getApplicableIndexInfoForName(type, name);
57457                         if (indexInfo) {
57458                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
57459                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
57460                         }
57461                         else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) {
57462                             checkFlags |= 32 /* WritePartial */;
57463                             indexTypes = ts.append(indexTypes, undefinedType);
57464                         }
57465                         else {
57466                             checkFlags |= 16 /* ReadPartial */;
57467                         }
57468                     }
57469                 }
57470             }
57471             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
57472                 // No property was found, or, in a union, a property has a private or protected declaration in one
57473                 // constituent, but is missing or has a different declaration in another constituent.
57474                 return undefined;
57475             }
57476             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
57477                 if (mergedInstantiations) {
57478                     // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents)
57479                     // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!)
57480                     // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol`
57481                     var clone_1 = createSymbolWithType(singleProp, singleProp.type);
57482                     clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent;
57483                     clone_1.containingType = containingType;
57484                     clone_1.mapper = singleProp.mapper;
57485                     return clone_1;
57486                 }
57487                 else {
57488                     return singleProp;
57489                 }
57490             }
57491             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
57492             var declarations;
57493             var firstType;
57494             var nameType;
57495             var propTypes = [];
57496             var firstValueDeclaration;
57497             var hasNonUniformValueDeclaration = false;
57498             for (var _d = 0, props_1 = props; _d < props_1.length; _d++) {
57499                 var prop = props_1[_d];
57500                 if (!firstValueDeclaration) {
57501                     firstValueDeclaration = prop.valueDeclaration;
57502                 }
57503                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
57504                     hasNonUniformValueDeclaration = true;
57505                 }
57506                 declarations = ts.addRange(declarations, prop.declarations);
57507                 var type = getTypeOfSymbol(prop);
57508                 if (!firstType) {
57509                     firstType = type;
57510                     nameType = getSymbolLinks(prop).nameType;
57511                 }
57512                 else if (type !== firstType) {
57513                     checkFlags |= 64 /* HasNonUniformType */;
57514                 }
57515                 if (isLiteralType(type) || isPatternLiteralType(type)) {
57516                     checkFlags |= 128 /* HasLiteralType */;
57517                 }
57518                 if (type.flags & 131072 /* Never */) {
57519                     checkFlags |= 131072 /* HasNeverType */;
57520                 }
57521                 propTypes.push(type);
57522             }
57523             ts.addRange(propTypes, indexTypes);
57524             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
57525             result.containingType = containingType;
57526             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
57527                 result.valueDeclaration = firstValueDeclaration;
57528                 // Inherit information about parent type.
57529                 if (firstValueDeclaration.symbol.parent) {
57530                     result.parent = firstValueDeclaration.symbol.parent;
57531                 }
57532             }
57533             result.declarations = declarations;
57534             result.nameType = nameType;
57535             if (propTypes.length > 2) {
57536                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
57537                 result.checkFlags |= 65536 /* DeferredType */;
57538                 result.deferralParent = containingType;
57539                 result.deferralConstituents = propTypes;
57540             }
57541             else {
57542                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
57543             }
57544             return result;
57545         }
57546         // Return the symbol for a given property in a union or intersection type, or undefined if the property
57547         // does not exist in any constituent type. Note that the returned property may only be present in some
57548         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
57549         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
57550         // and do not appear to be present in the union type.
57551         function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
57552             var _a, _b;
57553             var property = ((_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) === null || _a === void 0 ? void 0 : _a.get(name)) ||
57554                 !skipObjectFunctionPropertyAugment ? (_b = type.propertyCache) === null || _b === void 0 ? void 0 : _b.get(name) : undefined;
57555             if (!property) {
57556                 property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
57557                 if (property) {
57558                     var properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = ts.createSymbolTable()) : type.propertyCache || (type.propertyCache = ts.createSymbolTable());
57559                     properties.set(name, property);
57560                 }
57561             }
57562             return property;
57563         }
57564         function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
57565             var property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
57566             // We need to filter out partial properties in union types
57567             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
57568         }
57569         /**
57570          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
57571          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
57572          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
57573          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
57574          */
57575         function getReducedType(type) {
57576             if (type.flags & 1048576 /* Union */ && type.objectFlags & 33554432 /* ContainsIntersections */) {
57577                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
57578             }
57579             else if (type.flags & 2097152 /* Intersection */) {
57580                 if (!(type.objectFlags & 33554432 /* IsNeverIntersectionComputed */)) {
57581                     type.objectFlags |= 33554432 /* IsNeverIntersectionComputed */ |
57582                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 67108864 /* IsNeverIntersection */ : 0);
57583                 }
57584                 return type.objectFlags & 67108864 /* IsNeverIntersection */ ? neverType : type;
57585             }
57586             return type;
57587         }
57588         function getReducedUnionType(unionType) {
57589             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
57590             if (reducedTypes === unionType.types) {
57591                 return unionType;
57592             }
57593             var reduced = getUnionType(reducedTypes);
57594             if (reduced.flags & 1048576 /* Union */) {
57595                 reduced.resolvedReducedType = reduced;
57596             }
57597             return reduced;
57598         }
57599         function isNeverReducedProperty(prop) {
57600             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
57601         }
57602         function isDiscriminantWithNeverType(prop) {
57603             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
57604             // a literal type and none is never, that reduces to never.
57605             return !(prop.flags & 16777216 /* Optional */) &&
57606                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
57607                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
57608         }
57609         function isConflictingPrivateProperty(prop) {
57610             // Return true for a synthetic property with multiple declarations, at least one of which is private.
57611             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
57612         }
57613         function elaborateNeverIntersection(errorInfo, type) {
57614             if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 67108864 /* IsNeverIntersection */) {
57615                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
57616                 if (neverProp) {
57617                     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));
57618                 }
57619                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
57620                 if (privateProp) {
57621                     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));
57622                 }
57623             }
57624             return errorInfo;
57625         }
57626         /**
57627          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
57628          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
57629          * Object and Function as appropriate.
57630          *
57631          * @param type a type to look up property from
57632          * @param name a name of property to look up in a given type
57633          */
57634         function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) {
57635             type = getReducedApparentType(type);
57636             if (type.flags & 524288 /* Object */) {
57637                 var resolved = resolveStructuredTypeMembers(type);
57638                 var symbol = resolved.members.get(name);
57639                 if (symbol && symbolIsValue(symbol)) {
57640                     return symbol;
57641                 }
57642                 if (skipObjectFunctionPropertyAugment)
57643                     return undefined;
57644                 var functionType = resolved === anyFunctionType ? globalFunctionType :
57645                     resolved.callSignatures.length ? globalCallableFunctionType :
57646                         resolved.constructSignatures.length ? globalNewableFunctionType :
57647                             undefined;
57648                 if (functionType) {
57649                     var symbol_1 = getPropertyOfObjectType(functionType, name);
57650                     if (symbol_1) {
57651                         return symbol_1;
57652                     }
57653                 }
57654                 return getPropertyOfObjectType(globalObjectType, name);
57655             }
57656             if (type.flags & 3145728 /* UnionOrIntersection */) {
57657                 return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
57658             }
57659             return undefined;
57660         }
57661         function getSignaturesOfStructuredType(type, kind) {
57662             if (type.flags & 3670016 /* StructuredType */) {
57663                 var resolved = resolveStructuredTypeMembers(type);
57664                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
57665             }
57666             return ts.emptyArray;
57667         }
57668         /**
57669          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
57670          * maps primitive types and type parameters are to their apparent types.
57671          */
57672         function getSignaturesOfType(type, kind) {
57673             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
57674         }
57675         function findIndexInfo(indexInfos, keyType) {
57676             return ts.find(indexInfos, function (info) { return info.keyType === keyType; });
57677         }
57678         function findApplicableIndexInfo(indexInfos, keyType) {
57679             // Index signatures for type 'string' are considered only when no other index signatures apply.
57680             var stringIndexInfo;
57681             var applicableInfo;
57682             var applicableInfos;
57683             for (var _i = 0, indexInfos_1 = indexInfos; _i < indexInfos_1.length; _i++) {
57684                 var info = indexInfos_1[_i];
57685                 if (info.keyType === stringType) {
57686                     stringIndexInfo = info;
57687                 }
57688                 else if (isApplicableIndexType(keyType, info.keyType)) {
57689                     if (!applicableInfo) {
57690                         applicableInfo = info;
57691                     }
57692                     else {
57693                         (applicableInfos || (applicableInfos = [applicableInfo])).push(info);
57694                     }
57695                 }
57696             }
57697             // When more than one index signature is applicable we create a synthetic IndexInfo. Instead of computing
57698             // the intersected key type, we just use unknownType for the key type as nothing actually depends on the
57699             // keyType property of the returned IndexInfo.
57700             return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(ts.map(applicableInfos, function (info) { return info.type; })), ts.reduceLeft(applicableInfos, function (isReadonly, info) { return isReadonly && info.isReadonly; }, /*initial*/ true)) :
57701                 applicableInfo ? applicableInfo :
57702                     stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo :
57703                         undefined;
57704         }
57705         function isApplicableIndexType(source, target) {
57706             // A 'string' index signature applies to types assignable to 'string' or 'number', and a 'number' index
57707             // signature applies to types assignable to 'number' and numeric string literal types.
57708             return isTypeAssignableTo(source, target) ||
57709                 target === stringType && isTypeAssignableTo(source, numberType) ||
57710                 target === numberType && !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value);
57711         }
57712         function getIndexInfosOfStructuredType(type) {
57713             if (type.flags & 3670016 /* StructuredType */) {
57714                 var resolved = resolveStructuredTypeMembers(type);
57715                 return resolved.indexInfos;
57716             }
57717             return ts.emptyArray;
57718         }
57719         function getIndexInfosOfType(type) {
57720             return getIndexInfosOfStructuredType(getReducedApparentType(type));
57721         }
57722         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
57723         // maps primitive types and type parameters are to their apparent types.
57724         function getIndexInfoOfType(type, keyType) {
57725             return findIndexInfo(getIndexInfosOfType(type), keyType);
57726         }
57727         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
57728         // maps primitive types and type parameters are to their apparent types.
57729         function getIndexTypeOfType(type, keyType) {
57730             var _a;
57731             return (_a = getIndexInfoOfType(type, keyType)) === null || _a === void 0 ? void 0 : _a.type;
57732         }
57733         function getApplicableIndexInfos(type, keyType) {
57734             return getIndexInfosOfType(type).filter(function (info) { return isApplicableIndexType(keyType, info.keyType); });
57735         }
57736         function getApplicableIndexInfo(type, keyType) {
57737             return findApplicableIndexInfo(getIndexInfosOfType(type), keyType);
57738         }
57739         function getApplicableIndexInfoForName(type, name) {
57740             return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(ts.unescapeLeadingUnderscores(name)));
57741         }
57742         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
57743         // type checking functions).
57744         function getTypeParametersFromDeclaration(declaration) {
57745             var result;
57746             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
57747                 var node = _a[_i];
57748                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
57749             }
57750             return result;
57751         }
57752         function symbolsToArray(symbols) {
57753             var result = [];
57754             symbols.forEach(function (symbol, id) {
57755                 if (!isReservedMemberName(id)) {
57756                     result.push(symbol);
57757                 }
57758             });
57759             return result;
57760         }
57761         function isJSDocOptionalParameter(node) {
57762             return ts.isInJSFile(node) && (
57763             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
57764             node.type && node.type.kind === 314 /* JSDocOptionalType */
57765                 || ts.getJSDocParameterTags(node).some(function (_a) {
57766                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
57767                     return isBracketed || !!typeExpression && typeExpression.type.kind === 314 /* JSDocOptionalType */;
57768                 }));
57769         }
57770         function tryFindAmbientModule(moduleName, withAugmentations) {
57771             if (ts.isExternalModuleNameRelative(moduleName)) {
57772                 return undefined;
57773             }
57774             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
57775             // merged symbol is module declaration symbol combined with all augmentations
57776             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
57777         }
57778         function isOptionalParameter(node) {
57779             if (ts.hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isJSDocOptionalParameter(node)) {
57780                 return true;
57781             }
57782             if (node.initializer) {
57783                 var signature = getSignatureFromDeclaration(node.parent);
57784                 var parameterIndex = node.parent.parameters.indexOf(node);
57785                 ts.Debug.assert(parameterIndex >= 0);
57786                 // Only consider syntactic or instantiated parameters as optional, not `void` parameters as this function is used
57787                 // in grammar checks and checking for `void` too early results in parameter types widening too early
57788                 // and causes some noImplicitAny errors to be lost.
57789                 return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
57790             }
57791             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
57792             if (iife) {
57793                 return !node.type &&
57794                     !node.dotDotDotToken &&
57795                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
57796             }
57797             return false;
57798         }
57799         function isOptionalPropertyDeclaration(node) {
57800             return ts.isPropertyDeclaration(node) && node.questionToken;
57801         }
57802         function isOptionalJSDocPropertyLikeTag(node) {
57803             if (!ts.isJSDocPropertyLikeTag(node)) {
57804                 return false;
57805             }
57806             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
57807             return isBracketed || !!typeExpression && typeExpression.type.kind === 314 /* JSDocOptionalType */;
57808         }
57809         function createTypePredicate(kind, parameterName, parameterIndex, type) {
57810             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
57811         }
57812         /**
57813          * Gets the minimum number of type arguments needed to satisfy all non-optional type
57814          * parameters.
57815          */
57816         function getMinTypeArgumentCount(typeParameters) {
57817             var minTypeArgumentCount = 0;
57818             if (typeParameters) {
57819                 for (var i = 0; i < typeParameters.length; i++) {
57820                     if (!hasTypeParameterDefault(typeParameters[i])) {
57821                         minTypeArgumentCount = i + 1;
57822                     }
57823                 }
57824             }
57825             return minTypeArgumentCount;
57826         }
57827         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
57828             var numTypeParameters = ts.length(typeParameters);
57829             if (!numTypeParameters) {
57830                 return [];
57831             }
57832             var numTypeArguments = ts.length(typeArguments);
57833             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
57834                 var result = typeArguments ? typeArguments.slice() : [];
57835                 // Map invalid forward references in default types to the error type
57836                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
57837                     result[i] = errorType;
57838                 }
57839                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
57840                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
57841                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
57842                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
57843                         defaultType = anyType;
57844                     }
57845                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
57846                 }
57847                 result.length = typeParameters.length;
57848                 return result;
57849             }
57850             return typeArguments && typeArguments.slice();
57851         }
57852         function getSignatureFromDeclaration(declaration) {
57853             var links = getNodeLinks(declaration);
57854             if (!links.resolvedSignature) {
57855                 var parameters = [];
57856                 var flags = 0 /* None */;
57857                 var minArgumentCount = 0;
57858                 var thisParameter = void 0;
57859                 var hasThisParameter = false;
57860                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
57861                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
57862                 var isUntypedSignatureInJSFile = !iife &&
57863                     ts.isInJSFile(declaration) &&
57864                     ts.isValueSignatureDeclaration(declaration) &&
57865                     !ts.hasJSDocParameterTags(declaration) &&
57866                     !ts.getJSDocType(declaration);
57867                 if (isUntypedSignatureInJSFile) {
57868                     flags |= 32 /* IsUntypedSignatureInJSFile */;
57869                 }
57870                 // If this is a JSDoc construct signature, then skip the first parameter in the
57871                 // parameter list.  The first parameter represents the return type of the construct
57872                 // signature.
57873                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
57874                     var param = declaration.parameters[i];
57875                     var paramSymbol = param.symbol;
57876                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
57877                     // Include parameter symbol instead of property symbol in the signature
57878                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
57879                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
57880                         paramSymbol = resolvedSymbol;
57881                     }
57882                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
57883                         hasThisParameter = true;
57884                         thisParameter = param.symbol;
57885                     }
57886                     else {
57887                         parameters.push(paramSymbol);
57888                     }
57889                     if (type && type.kind === 195 /* LiteralType */) {
57890                         flags |= 2 /* HasLiteralTypes */;
57891                     }
57892                     // Record a new minimum argument count if this is not an optional parameter
57893                     var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) ||
57894                         param.initializer || param.questionToken || ts.isRestParameter(param) ||
57895                         iife && parameters.length > iife.arguments.length && !type ||
57896                         isJSDocOptionalParameter(param);
57897                     if (!isOptionalParameter_1) {
57898                         minArgumentCount = parameters.length;
57899                     }
57900                 }
57901                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
57902                 if ((declaration.kind === 171 /* GetAccessor */ || declaration.kind === 172 /* SetAccessor */) &&
57903                     hasBindableName(declaration) &&
57904                     (!hasThisParameter || !thisParameter)) {
57905                     var otherKind = declaration.kind === 171 /* GetAccessor */ ? 172 /* SetAccessor */ : 171 /* GetAccessor */;
57906                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
57907                     if (other) {
57908                         thisParameter = getAnnotatedAccessorThisParameter(other);
57909                     }
57910                 }
57911                 var classType = declaration.kind === 170 /* Constructor */ ?
57912                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
57913                     : undefined;
57914                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
57915                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
57916                     flags |= 1 /* HasRestParameter */;
57917                 }
57918                 if (ts.isConstructorTypeNode(declaration) && ts.hasSyntacticModifier(declaration, 128 /* Abstract */) ||
57919                     ts.isConstructorDeclaration(declaration) && ts.hasSyntacticModifier(declaration.parent, 128 /* Abstract */)) {
57920                     flags |= 4 /* Abstract */;
57921                 }
57922                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
57923                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
57924             }
57925             return links.resolvedSignature;
57926         }
57927         /**
57928          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
57929          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
57930          * OR
57931          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
57932          */
57933         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
57934             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
57935                 return false;
57936             }
57937             var lastParam = ts.lastOrUndefined(declaration.parameters);
57938             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
57939             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
57940                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
57941             });
57942             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
57943             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
57944             if (lastParamVariadicType) {
57945                 // Replace the last parameter with a rest parameter.
57946                 parameters.pop();
57947             }
57948             parameters.push(syntheticArgsSymbol);
57949             return true;
57950         }
57951         function getSignatureOfTypeTag(node) {
57952             // should be attached to a function declaration or expression
57953             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
57954                 return undefined;
57955             var typeTag = ts.getJSDocTypeTag(node);
57956             return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
57957         }
57958         function getReturnTypeOfTypeTag(node) {
57959             var signature = getSignatureOfTypeTag(node);
57960             return signature && getReturnTypeOfSignature(signature);
57961         }
57962         function containsArgumentsReference(declaration) {
57963             var links = getNodeLinks(declaration);
57964             if (links.containsArgumentsReference === undefined) {
57965                 if (links.flags & 8192 /* CaptureArguments */) {
57966                     links.containsArgumentsReference = true;
57967                 }
57968                 else {
57969                     links.containsArgumentsReference = traverse(declaration.body);
57970                 }
57971             }
57972             return links.containsArgumentsReference;
57973             function traverse(node) {
57974                 if (!node)
57975                     return false;
57976                 switch (node.kind) {
57977                     case 79 /* Identifier */:
57978                         return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol;
57979                     case 166 /* PropertyDeclaration */:
57980                     case 168 /* MethodDeclaration */:
57981                     case 171 /* GetAccessor */:
57982                     case 172 /* SetAccessor */:
57983                         return node.name.kind === 161 /* ComputedPropertyName */
57984                             && traverse(node.name);
57985                     case 205 /* PropertyAccessExpression */:
57986                     case 206 /* ElementAccessExpression */:
57987                         return traverse(node.expression);
57988                     default:
57989                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
57990                 }
57991             }
57992         }
57993         function getSignaturesOfSymbol(symbol) {
57994             if (!symbol || !symbol.declarations)
57995                 return ts.emptyArray;
57996             var result = [];
57997             for (var i = 0; i < symbol.declarations.length; i++) {
57998                 var decl = symbol.declarations[i];
57999                 if (!ts.isFunctionLike(decl))
58000                     continue;
58001                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
58002                 // an implementation node if it has a body and the previous node is of the same kind and immediately
58003                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
58004                 if (i > 0 && decl.body) {
58005                     var previous = symbol.declarations[i - 1];
58006                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
58007                         continue;
58008                     }
58009                 }
58010                 result.push(getSignatureFromDeclaration(decl));
58011             }
58012             return result;
58013         }
58014         function resolveExternalModuleTypeByLiteral(name) {
58015             var moduleSym = resolveExternalModuleName(name, name);
58016             if (moduleSym) {
58017                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
58018                 if (resolvedModuleSymbol) {
58019                     return getTypeOfSymbol(resolvedModuleSymbol);
58020                 }
58021             }
58022             return anyType;
58023         }
58024         function getThisTypeOfSignature(signature) {
58025             if (signature.thisParameter) {
58026                 return getTypeOfSymbol(signature.thisParameter);
58027             }
58028         }
58029         function getTypePredicateOfSignature(signature) {
58030             if (!signature.resolvedTypePredicate) {
58031                 if (signature.target) {
58032                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
58033                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
58034                 }
58035                 else if (signature.compositeSignatures) {
58036                     signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate;
58037                 }
58038                 else {
58039                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
58040                     var jsdocPredicate = void 0;
58041                     if (!type && ts.isInJSFile(signature.declaration)) {
58042                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
58043                         if (jsdocSignature && signature !== jsdocSignature) {
58044                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
58045                         }
58046                     }
58047                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
58048                         createTypePredicateFromTypePredicateNode(type, signature) :
58049                         jsdocPredicate || noTypePredicate;
58050                 }
58051                 ts.Debug.assert(!!signature.resolvedTypePredicate);
58052             }
58053             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
58054         }
58055         function createTypePredicateFromTypePredicateNode(node, signature) {
58056             var parameterName = node.parameterName;
58057             var type = node.type && getTypeFromTypeNode(node.type);
58058             return parameterName.kind === 191 /* ThisType */ ?
58059                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
58060                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
58061         }
58062         function getUnionOrIntersectionType(types, kind, unionReduction) {
58063             return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types);
58064         }
58065         function getReturnTypeOfSignature(signature) {
58066             if (!signature.resolvedReturnType) {
58067                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
58068                     return errorType;
58069                 }
58070                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
58071                     signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) :
58072                         getReturnTypeFromAnnotation(signature.declaration) ||
58073                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
58074                 if (signature.flags & 8 /* IsInnerCallChain */) {
58075                     type = addOptionalTypeMarker(type);
58076                 }
58077                 else if (signature.flags & 16 /* IsOuterCallChain */) {
58078                     type = getOptionalType(type);
58079                 }
58080                 if (!popTypeResolution()) {
58081                     if (signature.declaration) {
58082                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
58083                         if (typeNode) {
58084                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
58085                         }
58086                         else if (noImplicitAny) {
58087                             var declaration = signature.declaration;
58088                             var name = ts.getNameOfDeclaration(declaration);
58089                             if (name) {
58090                                 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));
58091                             }
58092                             else {
58093                                 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);
58094                             }
58095                         }
58096                     }
58097                     type = anyType;
58098                 }
58099                 signature.resolvedReturnType = type;
58100             }
58101             return signature.resolvedReturnType;
58102         }
58103         function getReturnTypeFromAnnotation(declaration) {
58104             if (declaration.kind === 170 /* Constructor */) {
58105                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
58106             }
58107             if (ts.isJSDocConstructSignature(declaration)) {
58108                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
58109             }
58110             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
58111             if (typeNode) {
58112                 return getTypeFromTypeNode(typeNode);
58113             }
58114             if (declaration.kind === 171 /* GetAccessor */ && hasBindableName(declaration)) {
58115                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
58116                 if (jsDocType) {
58117                     return jsDocType;
58118                 }
58119                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 172 /* SetAccessor */);
58120                 var setterType = getAnnotatedAccessorType(setter);
58121                 if (setterType) {
58122                     return setterType;
58123                 }
58124             }
58125             return getReturnTypeOfTypeTag(declaration);
58126         }
58127         function isResolvingReturnTypeOfSignature(signature) {
58128             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
58129         }
58130         function getRestTypeOfSignature(signature) {
58131             return tryGetRestTypeOfSignature(signature) || anyType;
58132         }
58133         function tryGetRestTypeOfSignature(signature) {
58134             if (signatureHasRestParameter(signature)) {
58135                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
58136                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
58137                 return restType && getIndexTypeOfType(restType, numberType);
58138             }
58139             return undefined;
58140         }
58141         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
58142             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
58143             if (inferredTypeParameters) {
58144                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
58145                 if (returnSignature) {
58146                     var newReturnSignature = cloneSignature(returnSignature);
58147                     newReturnSignature.typeParameters = inferredTypeParameters;
58148                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
58149                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
58150                     return newInstantiatedSignature;
58151                 }
58152             }
58153             return instantiatedSignature;
58154         }
58155         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
58156             var instantiations = signature.instantiations || (signature.instantiations = new ts.Map());
58157             var id = getTypeListId(typeArguments);
58158             var instantiation = instantiations.get(id);
58159             if (!instantiation) {
58160                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
58161             }
58162             return instantiation;
58163         }
58164         function createSignatureInstantiation(signature, typeArguments) {
58165             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
58166         }
58167         function createSignatureTypeMapper(signature, typeArguments) {
58168             return createTypeMapper(signature.typeParameters, typeArguments);
58169         }
58170         function getErasedSignature(signature) {
58171             return signature.typeParameters ?
58172                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
58173                 signature;
58174         }
58175         function createErasedSignature(signature) {
58176             // Create an instantiation of the signature where all type arguments are the any type.
58177             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
58178         }
58179         function getCanonicalSignature(signature) {
58180             return signature.typeParameters ?
58181                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
58182                 signature;
58183         }
58184         function createCanonicalSignature(signature) {
58185             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
58186             // its original. When a generic class or interface is instantiated, each generic method in the class or
58187             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
58188             // where different generations of the same type parameter are in scope). This leads to a lot of new type
58189             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
58190             // that uses the original type identities for all unconstrained type parameters.
58191             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
58192         }
58193         function getBaseSignature(signature) {
58194             var typeParameters = signature.typeParameters;
58195             if (typeParameters) {
58196                 if (signature.baseSignatureCache) {
58197                     return signature.baseSignatureCache;
58198                 }
58199                 var typeEraser = createTypeEraser(typeParameters);
58200                 var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; }));
58201                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; });
58202                 // Run N type params thru the immediate constraint mapper up to N times
58203                 // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies
58204                 for (var i = 0; i < typeParameters.length - 1; i++) {
58205                     baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1);
58206                 }
58207                 // and then apply a type eraser to remove any remaining circularly dependent type parameters
58208                 baseConstraints = instantiateTypes(baseConstraints, typeEraser);
58209                 return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
58210             }
58211             return signature;
58212         }
58213         function getOrCreateTypeFromSignature(signature) {
58214             // There are two ways to declare a construct signature, one is by declaring a class constructor
58215             // using the constructor keyword, and the other is declaring a bare construct signature in an
58216             // object type literal or interface (using the new keyword). Each way of declaring a constructor
58217             // will result in a different declaration kind.
58218             if (!signature.isolatedSignatureType) {
58219                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
58220                 var isConstructor = kind === 170 /* Constructor */ || kind === 174 /* ConstructSignature */ || kind === 179 /* ConstructorType */;
58221                 var type = createObjectType(16 /* Anonymous */);
58222                 type.members = emptySymbols;
58223                 type.properties = ts.emptyArray;
58224                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
58225                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
58226                 type.indexInfos = ts.emptyArray;
58227                 signature.isolatedSignatureType = type;
58228             }
58229             return signature.isolatedSignatureType;
58230         }
58231         function getIndexSymbol(symbol) {
58232             return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined;
58233         }
58234         function getIndexSymbolFromSymbolTable(symbolTable) {
58235             return symbolTable.get("__index" /* Index */);
58236         }
58237         function createIndexInfo(keyType, type, isReadonly, declaration) {
58238             return { keyType: keyType, type: type, isReadonly: isReadonly, declaration: declaration };
58239         }
58240         function getIndexInfosOfSymbol(symbol) {
58241             var indexSymbol = getIndexSymbol(symbol);
58242             return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol) : ts.emptyArray;
58243         }
58244         function getIndexInfosOfIndexSymbol(indexSymbol) {
58245             if (indexSymbol.declarations) {
58246                 var indexInfos_2 = [];
58247                 var _loop_14 = function (declaration) {
58248                     if (declaration.parameters.length === 1) {
58249                         var parameter = declaration.parameters[0];
58250                         if (parameter.type) {
58251                             forEachType(getTypeFromTypeNode(parameter.type), function (keyType) {
58252                                 if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos_2, keyType)) {
58253                                     indexInfos_2.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration));
58254                                 }
58255                             });
58256                         }
58257                     }
58258                 };
58259                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
58260                     var declaration = _a[_i];
58261                     _loop_14(declaration);
58262                 }
58263                 return indexInfos_2;
58264             }
58265             return ts.emptyArray;
58266         }
58267         function isValidIndexKeyType(type) {
58268             return !!(type.flags & (4 /* String */ | 8 /* Number */ | 4096 /* ESSymbol */)) || isPatternLiteralType(type) ||
58269                 !!(type.flags & 2097152 /* Intersection */) && !isGenericType(type) && ts.some(type.types, isValidIndexKeyType);
58270         }
58271         function getConstraintDeclaration(type) {
58272             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
58273         }
58274         function getInferredTypeParameterConstraint(typeParameter) {
58275             var _a;
58276             var inferences;
58277             if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) {
58278                 for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) {
58279                     var declaration = _b[_i];
58280                     if (declaration.parent.kind === 189 /* InferType */) {
58281                         // When an 'infer T' declaration is immediately contained in a type reference node
58282                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
58283                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
58284                         // present, we form an intersection of the inferred constraint types.
58285                         var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1];
58286                         if (grandParent.kind === 177 /* TypeReference */) {
58287                             var typeReference = grandParent;
58288                             var typeParameters = getTypeParametersForTypeReference(typeReference);
58289                             if (typeParameters) {
58290                                 var index = typeReference.typeArguments.indexOf(childTypeParameter);
58291                                 if (index < typeParameters.length) {
58292                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
58293                                     if (declaredConstraint) {
58294                                         // Type parameter constraints can reference other type parameters so
58295                                         // constraints need to be instantiated. If instantiation produces the
58296                                         // type parameter itself, we discard that inference. For example, in
58297                                         //   type Foo<T extends string, U extends T> = [T, U];
58298                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
58299                                         // the instantiated constraint for U is X, so we discard that inference.
58300                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
58301                                         var constraint = instantiateType(declaredConstraint, mapper);
58302                                         if (constraint !== typeParameter) {
58303                                             inferences = ts.append(inferences, constraint);
58304                                         }
58305                                     }
58306                                 }
58307                             }
58308                         }
58309                         // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type
58310                         // or a named rest tuple element, we infer an 'unknown[]' constraint.
58311                         else if (grandParent.kind === 163 /* Parameter */ && grandParent.dotDotDotToken ||
58312                             grandParent.kind === 185 /* RestType */ ||
58313                             grandParent.kind === 196 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
58314                             inferences = ts.append(inferences, createArrayType(unknownType));
58315                         }
58316                         // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string'
58317                         // constraint.
58318                         else if (grandParent.kind === 198 /* TemplateLiteralTypeSpan */) {
58319                             inferences = ts.append(inferences, stringType);
58320                         }
58321                         // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any'
58322                         // constraint.
58323                         else if (grandParent.kind === 162 /* TypeParameter */ && grandParent.parent.kind === 194 /* MappedType */) {
58324                             inferences = ts.append(inferences, keyofConstraintType);
58325                         }
58326                         // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends
58327                         // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template
58328                         // of the check type's mapped type
58329                         else if (grandParent.kind === 194 /* MappedType */ && grandParent.type &&
58330                             ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 188 /* ConditionalType */ &&
58331                             grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 194 /* MappedType */ &&
58332                             grandParent.parent.checkType.type) {
58333                             var checkMappedType_1 = grandParent.parent.checkType;
58334                             var nodeType = getTypeFromTypeNode(checkMappedType_1.type);
58335                             inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType)));
58336                         }
58337                     }
58338                 }
58339             }
58340             return inferences && getIntersectionType(inferences);
58341         }
58342         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
58343         function getConstraintFromTypeParameter(typeParameter) {
58344             if (!typeParameter.constraint) {
58345                 if (typeParameter.target) {
58346                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
58347                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
58348                 }
58349                 else {
58350                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
58351                     if (!constraintDeclaration) {
58352                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
58353                     }
58354                     else {
58355                         var type = getTypeFromTypeNode(constraintDeclaration);
58356                         if (type.flags & 1 /* Any */ && !isErrorType(type)) { // Allow errorType to propegate to keep downstream errors suppressed
58357                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
58358                             // use unknown otherwise
58359                             type = constraintDeclaration.parent.parent.kind === 194 /* MappedType */ ? keyofConstraintType : unknownType;
58360                         }
58361                         typeParameter.constraint = type;
58362                     }
58363                 }
58364             }
58365             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
58366         }
58367         function getParentSymbolOfTypeParameter(typeParameter) {
58368             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 162 /* TypeParameter */);
58369             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent;
58370             return host && getSymbolOfNode(host);
58371         }
58372         function getTypeListId(types) {
58373             var result = "";
58374             if (types) {
58375                 var length_4 = types.length;
58376                 var i = 0;
58377                 while (i < length_4) {
58378                     var startId = types[i].id;
58379                     var count = 1;
58380                     while (i + count < length_4 && types[i + count].id === startId + count) {
58381                         count++;
58382                     }
58383                     if (result.length) {
58384                         result += ",";
58385                     }
58386                     result += startId;
58387                     if (count > 1) {
58388                         result += ":" + count;
58389                     }
58390                     i += count;
58391                 }
58392             }
58393             return result;
58394         }
58395         function getAliasId(aliasSymbol, aliasTypeArguments) {
58396             return aliasSymbol ? "@".concat(getSymbolId(aliasSymbol)) + (aliasTypeArguments ? ":".concat(getTypeListId(aliasTypeArguments)) : "") : "";
58397         }
58398         // This function is used to propagate certain flags when creating new object type references and union types.
58399         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
58400         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
58401         // that care about the presence of such types at arbitrary depth in a containing type.
58402         function getPropagatingFlagsOfTypes(types, excludeKinds) {
58403             var result = 0;
58404             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
58405                 var type = types_8[_i];
58406                 if (!(type.flags & excludeKinds)) {
58407                     result |= ts.getObjectFlags(type);
58408                 }
58409             }
58410             return result & 917504 /* PropagatingFlags */;
58411         }
58412         function createTypeReference(target, typeArguments) {
58413             var id = getTypeListId(typeArguments);
58414             var type = target.instantiations.get(id);
58415             if (!type) {
58416                 type = createObjectType(4 /* Reference */, target.symbol);
58417                 target.instantiations.set(id, type);
58418                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
58419                 type.target = target;
58420                 type.resolvedTypeArguments = typeArguments;
58421             }
58422             return type;
58423         }
58424         function cloneTypeReference(source) {
58425             var type = createType(source.flags);
58426             type.symbol = source.symbol;
58427             type.objectFlags = source.objectFlags;
58428             type.target = source.target;
58429             type.resolvedTypeArguments = source.resolvedTypeArguments;
58430             return type;
58431         }
58432         function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) {
58433             if (!aliasSymbol) {
58434                 aliasSymbol = getAliasSymbolForTypeNode(node);
58435                 var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
58436                 aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments;
58437             }
58438             var type = createObjectType(4 /* Reference */, target.symbol);
58439             type.target = target;
58440             type.node = node;
58441             type.mapper = mapper;
58442             type.aliasSymbol = aliasSymbol;
58443             type.aliasTypeArguments = aliasTypeArguments;
58444             return type;
58445         }
58446         function getTypeArguments(type) {
58447             var _a, _b;
58448             if (!type.resolvedTypeArguments) {
58449                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
58450                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
58451                 }
58452                 var node = type.node;
58453                 var typeArguments = !node ? ts.emptyArray :
58454                     node.kind === 177 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
58455                         node.kind === 182 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
58456                             ts.map(node.elements, getTypeFromTypeNode);
58457                 if (popTypeResolution()) {
58458                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
58459                 }
58460                 else {
58461                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
58462                     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));
58463                 }
58464             }
58465             return type.resolvedTypeArguments;
58466         }
58467         function getTypeReferenceArity(type) {
58468             return ts.length(type.target.typeParameters);
58469         }
58470         /**
58471          * Get type from type-reference that reference to class or interface
58472          */
58473         function getTypeFromClassOrInterfaceReference(node, symbol) {
58474             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
58475             var typeParameters = type.localTypeParameters;
58476             if (typeParameters) {
58477                 var numTypeArguments = ts.length(node.typeArguments);
58478                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
58479                 var isJs = ts.isInJSFile(node);
58480                 var isJsImplicitAny = !noImplicitAny && isJs;
58481                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
58482                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
58483                     var diag = minTypeArgumentCount === typeParameters.length ?
58484                         missingAugmentsTag ?
58485                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
58486                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
58487                         missingAugmentsTag ?
58488                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
58489                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
58490                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
58491                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
58492                     if (!isJs) {
58493                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
58494                         return errorType;
58495                     }
58496                 }
58497                 if (node.kind === 177 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
58498                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
58499                 }
58500                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
58501                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
58502                 // of the class or interface.
58503                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
58504                 return createTypeReference(type, typeArguments);
58505             }
58506             return checkNoTypeArguments(node, symbol) ? type : errorType;
58507         }
58508         function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) {
58509             var type = getDeclaredTypeOfSymbol(symbol);
58510             if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) {
58511                 return getStringMappingType(symbol, typeArguments[0]);
58512             }
58513             var links = getSymbolLinks(symbol);
58514             var typeParameters = links.typeParameters;
58515             var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
58516             var instantiation = links.instantiations.get(id);
58517             if (!instantiation) {
58518                 links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments));
58519             }
58520             return instantiation;
58521         }
58522         /**
58523          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
58524          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
58525          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
58526          */
58527         function getTypeFromTypeAliasReference(node, symbol) {
58528             if (ts.getCheckFlags(symbol) & 1048576 /* Unresolved */) {
58529                 var typeArguments = typeArgumentsFromTypeReferenceNode(node);
58530                 var id = getAliasId(symbol, typeArguments);
58531                 var errorType_1 = errorTypes.get(id);
58532                 if (!errorType_1) {
58533                     errorType_1 = createIntrinsicType(1 /* Any */, "error");
58534                     errorType_1.aliasSymbol = symbol;
58535                     errorType_1.aliasTypeArguments = typeArguments;
58536                     errorTypes.set(id, errorType_1);
58537                 }
58538                 return errorType_1;
58539             }
58540             var type = getDeclaredTypeOfSymbol(symbol);
58541             var typeParameters = getSymbolLinks(symbol).typeParameters;
58542             if (typeParameters) {
58543                 var numTypeArguments = ts.length(node.typeArguments);
58544                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
58545                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
58546                     error(node, minTypeArgumentCount === typeParameters.length ?
58547                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
58548                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
58549                     return errorType;
58550                 }
58551                 // We refrain from associating a local type alias with an instantiation of a top-level type alias
58552                 // because the local alias may end up being referenced in an inferred return type where it is not
58553                 // accessible--which in turn may lead to a large structural expansion of the type when generating
58554                 // a .d.ts file. See #43622 for an example.
58555                 var aliasSymbol = getAliasSymbolForTypeNode(node);
58556                 var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined;
58557                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol));
58558             }
58559             return checkNoTypeArguments(node, symbol) ? type : errorType;
58560         }
58561         function isLocalTypeAlias(symbol) {
58562             var _a;
58563             var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias);
58564             return !!(declaration && ts.getContainingFunction(declaration));
58565         }
58566         function getTypeReferenceName(node) {
58567             switch (node.kind) {
58568                 case 177 /* TypeReference */:
58569                     return node.typeName;
58570                 case 227 /* ExpressionWithTypeArguments */:
58571                     // We only support expressions that are simple qualified names. For other
58572                     // expressions this produces undefined.
58573                     var expr = node.expression;
58574                     if (ts.isEntityNameExpression(expr)) {
58575                         return expr;
58576                     }
58577                 // fall through;
58578             }
58579             return undefined;
58580         }
58581         function getSymbolPath(symbol) {
58582             return symbol.parent ? "".concat(getSymbolPath(symbol.parent), ".").concat(symbol.escapedName) : symbol.escapedName;
58583         }
58584         function getUnresolvedSymbolForEntityName(name) {
58585             var identifier = name.kind === 160 /* QualifiedName */ ? name.right :
58586                 name.kind === 205 /* PropertyAccessExpression */ ? name.name :
58587                     name;
58588             var text = identifier.escapedText;
58589             if (text) {
58590                 var parentSymbol = name.kind === 160 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) :
58591                     name.kind === 205 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) :
58592                         undefined;
58593                 var path = parentSymbol ? "".concat(getSymbolPath(parentSymbol), ".").concat(text) : text;
58594                 var result = unresolvedSymbols.get(path);
58595                 if (!result) {
58596                     unresolvedSymbols.set(path, result = createSymbol(524288 /* TypeAlias */, text, 1048576 /* Unresolved */));
58597                     result.parent = parentSymbol;
58598                     result.declaredType = unresolvedType;
58599                 }
58600                 return result;
58601             }
58602             return unknownSymbol;
58603         }
58604         function resolveTypeReferenceName(typeReference, meaning, ignoreErrors) {
58605             var name = getTypeReferenceName(typeReference);
58606             if (!name) {
58607                 return unknownSymbol;
58608             }
58609             var symbol = resolveEntityName(name, meaning, ignoreErrors);
58610             return symbol && symbol !== unknownSymbol ? symbol :
58611                 ignoreErrors ? unknownSymbol : getUnresolvedSymbolForEntityName(name);
58612         }
58613         function getTypeReferenceType(node, symbol) {
58614             if (symbol === unknownSymbol) {
58615                 return errorType;
58616             }
58617             symbol = getExpandoSymbol(symbol) || symbol;
58618             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
58619                 return getTypeFromClassOrInterfaceReference(node, symbol);
58620             }
58621             if (symbol.flags & 524288 /* TypeAlias */) {
58622                 return getTypeFromTypeAliasReference(node, symbol);
58623             }
58624             // Get type from reference to named type that cannot be generic (enum or type parameter)
58625             var res = tryGetDeclaredTypeOfSymbol(symbol);
58626             if (res) {
58627                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
58628             }
58629             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
58630                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
58631                 if (jsdocType) {
58632                     return jsdocType;
58633                 }
58634                 else {
58635                     // Resolve the type reference as a Type for the purpose of reporting errors.
58636                     resolveTypeReferenceName(node, 788968 /* Type */);
58637                     return getTypeOfSymbol(symbol);
58638                 }
58639             }
58640             return errorType;
58641         }
58642         /**
58643          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
58644          * Example: import('./b').ConstructorFunction
58645          */
58646         function getTypeFromJSDocValueReference(node, symbol) {
58647             var links = getNodeLinks(node);
58648             if (!links.resolvedJSDocType) {
58649                 var valueType = getTypeOfSymbol(symbol);
58650                 var typeType = valueType;
58651                 if (symbol.valueDeclaration) {
58652                     var isImportTypeWithQualifier = node.kind === 199 /* ImportType */ && node.qualifier;
58653                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
58654                     if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
58655                         typeType = getTypeReferenceType(node, valueType.symbol);
58656                     }
58657                 }
58658                 links.resolvedJSDocType = typeType;
58659             }
58660             return links.resolvedJSDocType;
58661         }
58662         function getSubstitutionType(baseType, substitute) {
58663             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
58664                 return baseType;
58665             }
58666             var id = "".concat(getTypeId(baseType), ">").concat(getTypeId(substitute));
58667             var cached = substitutionTypes.get(id);
58668             if (cached) {
58669                 return cached;
58670             }
58671             var result = createType(33554432 /* Substitution */);
58672             result.baseType = baseType;
58673             result.substitute = substitute;
58674             substitutionTypes.set(id, result);
58675             return result;
58676         }
58677         function isUnaryTupleTypeNode(node) {
58678             return node.kind === 183 /* TupleType */ && node.elements.length === 1;
58679         }
58680         function getImpliedConstraint(type, checkNode, extendsNode) {
58681             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) :
58682                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
58683                     undefined;
58684         }
58685         function getConditionalFlowTypeOfType(type, node) {
58686             var constraints;
58687             var covariant = true;
58688             while (node && !ts.isStatement(node) && node.kind !== 318 /* JSDocComment */) {
58689                 var parent = node.parent;
58690                 // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but
58691                 // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax
58692                 if (parent.kind === 163 /* Parameter */) {
58693                     covariant = !covariant;
58694                 }
58695                 // Always substitute on type parameters, regardless of variance, since even
58696                 // in contravariant positions, they may rely on substituted constraints to be valid
58697                 if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 188 /* ConditionalType */ && node === parent.trueType) {
58698                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
58699                     if (constraint) {
58700                         constraints = ts.append(constraints, constraint);
58701                     }
58702                 }
58703                 node = parent;
58704             }
58705             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
58706         }
58707         function isJSDocTypeReference(node) {
58708             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 177 /* TypeReference */ || node.kind === 199 /* ImportType */);
58709         }
58710         function checkNoTypeArguments(node, symbol) {
58711             if (node.typeArguments) {
58712                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
58713                 return false;
58714             }
58715             return true;
58716         }
58717         function getIntendedTypeFromJSDocTypeReference(node) {
58718             if (ts.isIdentifier(node.typeName)) {
58719                 var typeArgs = node.typeArguments;
58720                 switch (node.typeName.escapedText) {
58721                     case "String":
58722                         checkNoTypeArguments(node);
58723                         return stringType;
58724                     case "Number":
58725                         checkNoTypeArguments(node);
58726                         return numberType;
58727                     case "Boolean":
58728                         checkNoTypeArguments(node);
58729                         return booleanType;
58730                     case "Void":
58731                         checkNoTypeArguments(node);
58732                         return voidType;
58733                     case "Undefined":
58734                         checkNoTypeArguments(node);
58735                         return undefinedType;
58736                     case "Null":
58737                         checkNoTypeArguments(node);
58738                         return nullType;
58739                     case "Function":
58740                     case "function":
58741                         checkNoTypeArguments(node);
58742                         return globalFunctionType;
58743                     case "array":
58744                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
58745                     case "promise":
58746                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
58747                     case "Object":
58748                         if (typeArgs && typeArgs.length === 2) {
58749                             if (ts.isJSDocIndexSignature(node)) {
58750                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
58751                                 var target = getTypeFromTypeNode(typeArgs[1]);
58752                                 var indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo(indexed, target, /*isReadonly*/ false)] : ts.emptyArray;
58753                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexInfo);
58754                             }
58755                             return anyType;
58756                         }
58757                         checkNoTypeArguments(node);
58758                         return !noImplicitAny ? anyType : undefined;
58759                 }
58760             }
58761         }
58762         function getTypeFromJSDocNullableTypeNode(node) {
58763             var type = getTypeFromTypeNode(node.type);
58764             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
58765         }
58766         function getTypeFromTypeReference(node) {
58767             var links = getNodeLinks(node);
58768             if (!links.resolvedType) {
58769                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
58770                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
58771                     links.resolvedSymbol = unknownSymbol;
58772                     return links.resolvedType = checkExpressionCached(node.parent.expression);
58773                 }
58774                 var symbol = void 0;
58775                 var type = void 0;
58776                 var meaning = 788968 /* Type */;
58777                 if (isJSDocTypeReference(node)) {
58778                     type = getIntendedTypeFromJSDocTypeReference(node);
58779                     if (!type) {
58780                         symbol = resolveTypeReferenceName(node, meaning, /*ignoreErrors*/ true);
58781                         if (symbol === unknownSymbol) {
58782                             symbol = resolveTypeReferenceName(node, meaning | 111551 /* Value */);
58783                         }
58784                         else {
58785                             resolveTypeReferenceName(node, meaning); // Resolve again to mark errors, if any
58786                         }
58787                         type = getTypeReferenceType(node, symbol);
58788                     }
58789                 }
58790                 if (!type) {
58791                     symbol = resolveTypeReferenceName(node, meaning);
58792                     type = getTypeReferenceType(node, symbol);
58793                 }
58794                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
58795                 // type reference in checkTypeReferenceNode.
58796                 links.resolvedSymbol = symbol;
58797                 links.resolvedType = type;
58798             }
58799             return links.resolvedType;
58800         }
58801         function typeArgumentsFromTypeReferenceNode(node) {
58802             return ts.map(node.typeArguments, getTypeFromTypeNode);
58803         }
58804         function getTypeFromTypeQueryNode(node) {
58805             var links = getNodeLinks(node);
58806             if (!links.resolvedType) {
58807                 // TypeScript 1.0 spec (April 2014): 3.6.3
58808                 // The expression is processed as an identifier expression (section 4.3)
58809                 // or property access expression(section 4.10),
58810                 // the widened type(section 3.9) of which becomes the result.
58811                 var type = ts.isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName);
58812                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(type));
58813             }
58814             return links.resolvedType;
58815         }
58816         function getTypeOfGlobalSymbol(symbol, arity) {
58817             function getTypeDeclaration(symbol) {
58818                 var declarations = symbol.declarations;
58819                 if (declarations) {
58820                     for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
58821                         var declaration = declarations_3[_i];
58822                         switch (declaration.kind) {
58823                             case 256 /* ClassDeclaration */:
58824                             case 257 /* InterfaceDeclaration */:
58825                             case 259 /* EnumDeclaration */:
58826                                 return declaration;
58827                         }
58828                     }
58829                 }
58830             }
58831             if (!symbol) {
58832                 return arity ? emptyGenericType : emptyObjectType;
58833             }
58834             var type = getDeclaredTypeOfSymbol(symbol);
58835             if (!(type.flags & 524288 /* Object */)) {
58836                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
58837                 return arity ? emptyGenericType : emptyObjectType;
58838             }
58839             if (ts.length(type.typeParameters) !== arity) {
58840                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
58841                 return arity ? emptyGenericType : emptyObjectType;
58842             }
58843             return type;
58844         }
58845         function getGlobalValueSymbol(name, reportErrors) {
58846             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
58847         }
58848         function getGlobalTypeSymbol(name, reportErrors) {
58849             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
58850         }
58851         function getGlobalTypeAliasSymbol(name, arity, reportErrors) {
58852             var symbol = getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
58853             if (symbol) {
58854                 // Resolve the declared type of the symbol. This resolves type parameters for the type
58855                 // alias so that we can check arity.
58856                 getDeclaredTypeOfSymbol(symbol);
58857                 if (ts.length(getSymbolLinks(symbol).typeParameters) !== arity) {
58858                     var decl = symbol.declarations && ts.find(symbol.declarations, ts.isTypeAliasDeclaration);
58859                     error(decl, ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
58860                     return undefined;
58861                 }
58862             }
58863             return symbol;
58864         }
58865         function getGlobalSymbol(name, meaning, diagnostic) {
58866             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
58867             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
58868         }
58869         function getGlobalType(name, arity, reportErrors) {
58870             var symbol = getGlobalTypeSymbol(name, reportErrors);
58871             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
58872         }
58873         function getGlobalTypedPropertyDescriptorType() {
58874             // We always report an error, so store a result in the event we could not resolve the symbol to prevent reporting it multiple times
58875             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true) || emptyGenericType);
58876         }
58877         function getGlobalTemplateStringsArrayType() {
58878             // We always report an error, so store a result in the event we could not resolve the symbol to prevent reporting it multiple times
58879             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true) || emptyObjectType);
58880         }
58881         function getGlobalImportMetaType() {
58882             // We always report an error, so store a result in the event we could not resolve the symbol to prevent reporting it multiple times
58883             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true) || emptyObjectType);
58884         }
58885         function getGlobalImportMetaExpressionType() {
58886             if (!deferredGlobalImportMetaExpressionType) {
58887                 // Create a synthetic type `ImportMetaExpression { meta: MetaProperty }`
58888                 var symbol = createSymbol(0 /* None */, "ImportMetaExpression");
58889                 var importMetaType = getGlobalImportMetaType();
58890                 var metaPropertySymbol = createSymbol(4 /* Property */, "meta", 8 /* Readonly */);
58891                 metaPropertySymbol.parent = symbol;
58892                 metaPropertySymbol.type = importMetaType;
58893                 var members = ts.createSymbolTable([metaPropertySymbol]);
58894                 symbol.members = members;
58895                 deferredGlobalImportMetaExpressionType = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, ts.emptyArray);
58896             }
58897             return deferredGlobalImportMetaExpressionType;
58898         }
58899         function getGlobalImportCallOptionsType(reportErrors) {
58900             return (deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType("ImportCallOptions", /*arity*/ 0, reportErrors))) || emptyObjectType;
58901         }
58902         function getGlobalESSymbolConstructorSymbol(reportErrors) {
58903             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
58904         }
58905         function getGlobalESSymbolConstructorTypeSymbol(reportErrors) {
58906             return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors));
58907         }
58908         function getGlobalESSymbolType(reportErrors) {
58909             return (deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors))) || emptyObjectType;
58910         }
58911         function getGlobalPromiseType(reportErrors) {
58912             return (deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors))) || emptyGenericType;
58913         }
58914         function getGlobalPromiseLikeType(reportErrors) {
58915             return (deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors))) || emptyGenericType;
58916         }
58917         function getGlobalPromiseConstructorSymbol(reportErrors) {
58918             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
58919         }
58920         function getGlobalPromiseConstructorLikeType(reportErrors) {
58921             return (deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors))) || emptyObjectType;
58922         }
58923         function getGlobalAsyncIterableType(reportErrors) {
58924             return (deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors))) || emptyGenericType;
58925         }
58926         function getGlobalAsyncIteratorType(reportErrors) {
58927             return (deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors))) || emptyGenericType;
58928         }
58929         function getGlobalAsyncIterableIteratorType(reportErrors) {
58930             return (deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors))) || emptyGenericType;
58931         }
58932         function getGlobalAsyncGeneratorType(reportErrors) {
58933             return (deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors))) || emptyGenericType;
58934         }
58935         function getGlobalIterableType(reportErrors) {
58936             return (deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors))) || emptyGenericType;
58937         }
58938         function getGlobalIteratorType(reportErrors) {
58939             return (deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors))) || emptyGenericType;
58940         }
58941         function getGlobalIterableIteratorType(reportErrors) {
58942             return (deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors))) || emptyGenericType;
58943         }
58944         function getGlobalGeneratorType(reportErrors) {
58945             return (deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors))) || emptyGenericType;
58946         }
58947         function getGlobalIteratorYieldResultType(reportErrors) {
58948             return (deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors))) || emptyGenericType;
58949         }
58950         function getGlobalIteratorReturnResultType(reportErrors) {
58951             return (deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors))) || emptyGenericType;
58952         }
58953         function getGlobalTypeOrUndefined(name, arity) {
58954             if (arity === void 0) { arity = 0; }
58955             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
58956             return symbol && getTypeOfGlobalSymbol(symbol, arity);
58957         }
58958         function getGlobalExtractSymbol() {
58959             // We always report an error, so cache a result in the event we could not resolve the symbol to prevent reporting it multiple times
58960             deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol("Extract", /*arity*/ 2, /*reportErrors*/ true) || unknownSymbol);
58961             return deferredGlobalExtractSymbol === unknownSymbol ? undefined : deferredGlobalExtractSymbol;
58962         }
58963         function getGlobalOmitSymbol() {
58964             // We always report an error, so cache a result in the event we could not resolve the symbol to prevent reporting it multiple times
58965             deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol("Omit", /*arity*/ 2, /*reportErrors*/ true) || unknownSymbol);
58966             return deferredGlobalOmitSymbol === unknownSymbol ? undefined : deferredGlobalOmitSymbol;
58967         }
58968         function getGlobalAwaitedSymbol(reportErrors) {
58969             // Only cache `unknownSymbol` if we are reporting errors so that we don't report the error more than once.
58970             deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol("Awaited", /*arity*/ 1, reportErrors) || (reportErrors ? unknownSymbol : undefined));
58971             return deferredGlobalAwaitedSymbol === unknownSymbol ? undefined : deferredGlobalAwaitedSymbol;
58972         }
58973         function getGlobalBigIntType(reportErrors) {
58974             return (deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors))) || emptyObjectType;
58975         }
58976         /**
58977          * Instantiates a global type that is generic with some element type, and returns that instantiation.
58978          */
58979         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
58980             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
58981         }
58982         function createTypedPropertyDescriptorType(propertyType) {
58983             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
58984         }
58985         function createIterableType(iteratedType) {
58986             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
58987         }
58988         function createArrayType(elementType, readonly) {
58989             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
58990         }
58991         function getTupleElementFlags(node) {
58992             switch (node.kind) {
58993                 case 184 /* OptionalType */:
58994                     return 2 /* Optional */;
58995                 case 185 /* RestType */:
58996                     return getRestTypeElementFlags(node);
58997                 case 196 /* NamedTupleMember */:
58998                     return node.questionToken ? 2 /* Optional */ :
58999                         node.dotDotDotToken ? getRestTypeElementFlags(node) :
59000                             1 /* Required */;
59001                 default:
59002                     return 1 /* Required */;
59003             }
59004         }
59005         function getRestTypeElementFlags(node) {
59006             return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */;
59007         }
59008         function getArrayOrTupleTargetType(node) {
59009             var readonly = isReadonlyTypeOperator(node.parent);
59010             var elementType = getArrayElementTypeNode(node);
59011             if (elementType) {
59012                 return readonly ? globalReadonlyArrayType : globalArrayType;
59013             }
59014             var elementFlags = ts.map(node.elements, getTupleElementFlags);
59015             var missingName = ts.some(node.elements, function (e) { return e.kind !== 196 /* NamedTupleMember */; });
59016             return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements);
59017         }
59018         // Return true if the given type reference node is directly aliased or if it needs to be deferred
59019         // because it is possibly contained in a circular chain of eagerly resolved types.
59020         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
59021             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 182 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
59022                 node.kind === 183 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) :
59023                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
59024         }
59025         // Return true when the given node is transitively contained in type constructs that eagerly
59026         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
59027         // of type aliases are eagerly resolved.
59028         function isResolvedByTypeAlias(node) {
59029             var parent = node.parent;
59030             switch (parent.kind) {
59031                 case 190 /* ParenthesizedType */:
59032                 case 196 /* NamedTupleMember */:
59033                 case 177 /* TypeReference */:
59034                 case 186 /* UnionType */:
59035                 case 187 /* IntersectionType */:
59036                 case 193 /* IndexedAccessType */:
59037                 case 188 /* ConditionalType */:
59038                 case 192 /* TypeOperator */:
59039                 case 182 /* ArrayType */:
59040                 case 183 /* TupleType */:
59041                     return isResolvedByTypeAlias(parent);
59042                 case 258 /* TypeAliasDeclaration */:
59043                     return true;
59044             }
59045             return false;
59046         }
59047         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
59048         // of a type alias.
59049         function mayResolveTypeAlias(node) {
59050             switch (node.kind) {
59051                 case 177 /* TypeReference */:
59052                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, 788968 /* Type */).flags & 524288 /* TypeAlias */);
59053                 case 180 /* TypeQuery */:
59054                     return true;
59055                 case 192 /* TypeOperator */:
59056                     return node.operator !== 153 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
59057                 case 190 /* ParenthesizedType */:
59058                 case 184 /* OptionalType */:
59059                 case 196 /* NamedTupleMember */:
59060                 case 314 /* JSDocOptionalType */:
59061                 case 312 /* JSDocNullableType */:
59062                 case 313 /* JSDocNonNullableType */:
59063                 case 307 /* JSDocTypeExpression */:
59064                     return mayResolveTypeAlias(node.type);
59065                 case 185 /* RestType */:
59066                     return node.type.kind !== 182 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
59067                 case 186 /* UnionType */:
59068                 case 187 /* IntersectionType */:
59069                     return ts.some(node.types, mayResolveTypeAlias);
59070                 case 193 /* IndexedAccessType */:
59071                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
59072                 case 188 /* ConditionalType */:
59073                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
59074                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
59075             }
59076             return false;
59077         }
59078         function getTypeFromArrayOrTupleTypeNode(node) {
59079             var links = getNodeLinks(node);
59080             if (!links.resolvedType) {
59081                 var target = getArrayOrTupleTargetType(node);
59082                 if (target === emptyGenericType) {
59083                     links.resolvedType = emptyObjectType;
59084                 }
59085                 else if (!(node.kind === 183 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) {
59086                     links.resolvedType = node.kind === 183 /* TupleType */ && node.elements.length === 0 ? target :
59087                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
59088                 }
59089                 else {
59090                     var elementTypes = node.kind === 182 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode);
59091                     links.resolvedType = createNormalizedTypeReference(target, elementTypes);
59092                 }
59093             }
59094             return links.resolvedType;
59095         }
59096         function isReadonlyTypeOperator(node) {
59097             return ts.isTypeOperatorNode(node) && node.operator === 144 /* ReadonlyKeyword */;
59098         }
59099         function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) {
59100             if (readonly === void 0) { readonly = false; }
59101             var tupleTarget = getTupleTargetType(elementFlags || ts.map(elementTypes, function (_) { return 1 /* Required */; }), readonly, namedMemberDeclarations);
59102             return tupleTarget === emptyGenericType ? emptyObjectType :
59103                 elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) :
59104                     tupleTarget;
59105         }
59106         function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
59107             if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
59108                 // [...X[]] is equivalent to just X[]
59109                 return readonly ? globalReadonlyArrayType : globalArrayType;
59110             }
59111             var key = ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*"; }).join() +
59112                 (readonly ? "R" : "") +
59113                 (namedMemberDeclarations && namedMemberDeclarations.length ? "," + ts.map(namedMemberDeclarations, getNodeId).join(",") : "");
59114             var type = tupleTypes.get(key);
59115             if (!type) {
59116                 tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
59117             }
59118             return type;
59119         }
59120         // We represent tuple types as type references to synthesized generic interface types created by
59121         // this function. The types are of the form:
59122         //
59123         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
59124         //
59125         // Note that the generic type created by this function has no symbol associated with it. The same
59126         // is true for each of the synthesized type parameters.
59127         function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
59128             var arity = elementFlags.length;
59129             var minLength = ts.countWhere(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); });
59130             var typeParameters;
59131             var properties = [];
59132             var combinedFlags = 0;
59133             if (arity) {
59134                 typeParameters = new Array(arity);
59135                 for (var i = 0; i < arity; i++) {
59136                     var typeParameter = typeParameters[i] = createTypeParameter();
59137                     var flags = elementFlags[i];
59138                     combinedFlags |= flags;
59139                     if (!(combinedFlags & 12 /* Variable */)) {
59140                         var property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
59141                         property.tupleLabelDeclaration = namedMemberDeclarations === null || namedMemberDeclarations === void 0 ? void 0 : namedMemberDeclarations[i];
59142                         property.type = typeParameter;
59143                         properties.push(property);
59144                     }
59145                 }
59146             }
59147             var fixedLength = properties.length;
59148             var lengthSymbol = createSymbol(4 /* Property */, "length");
59149             if (combinedFlags & 12 /* Variable */) {
59150                 lengthSymbol.type = numberType;
59151             }
59152             else {
59153                 var literalTypes = [];
59154                 for (var i = minLength; i <= arity; i++)
59155                     literalTypes.push(getNumberLiteralType(i));
59156                 lengthSymbol.type = getUnionType(literalTypes);
59157             }
59158             properties.push(lengthSymbol);
59159             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
59160             type.typeParameters = typeParameters;
59161             type.outerTypeParameters = undefined;
59162             type.localTypeParameters = typeParameters;
59163             type.instantiations = new ts.Map();
59164             type.instantiations.set(getTypeListId(type.typeParameters), type);
59165             type.target = type;
59166             type.resolvedTypeArguments = type.typeParameters;
59167             type.thisType = createTypeParameter();
59168             type.thisType.isThisType = true;
59169             type.thisType.constraint = type;
59170             type.declaredProperties = properties;
59171             type.declaredCallSignatures = ts.emptyArray;
59172             type.declaredConstructSignatures = ts.emptyArray;
59173             type.declaredIndexInfos = ts.emptyArray;
59174             type.elementFlags = elementFlags;
59175             type.minLength = minLength;
59176             type.fixedLength = fixedLength;
59177             type.hasRestElement = !!(combinedFlags & 12 /* Variable */);
59178             type.combinedFlags = combinedFlags;
59179             type.readonly = readonly;
59180             type.labeledElementDeclarations = namedMemberDeclarations;
59181             return type;
59182         }
59183         function createNormalizedTypeReference(target, typeArguments) {
59184             return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments);
59185         }
59186         function createNormalizedTupleType(target, elementTypes) {
59187             var _a, _b, _c;
59188             if (!(target.combinedFlags & 14 /* NonRequired */)) {
59189                 // No need to normalize when we only have regular required elements
59190                 return createTypeReference(target, elementTypes);
59191             }
59192             if (target.combinedFlags & 8 /* Variadic */) {
59193                 // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
59194                 var unionIndex_1 = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
59195                 if (unionIndex_1 >= 0) {
59196                     return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
59197                         mapType(elementTypes[unionIndex_1], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex_1, t)); }) :
59198                         errorType;
59199                 }
59200             }
59201             // We have optional, rest, or variadic elements that may need normalizing. Normalization ensures that all variadic
59202             // elements are generic and that the tuple type has one of the following layouts, disregarding variadic elements:
59203             // (1) Zero or more required elements, followed by zero or more optional elements, followed by zero or one rest element.
59204             // (2) Zero or more required elements, followed by a rest element, followed by zero or more required elements.
59205             // In either layout, zero or more generic variadic elements may be present at any location.
59206             var expandedTypes = [];
59207             var expandedFlags = [];
59208             var expandedDeclarations = [];
59209             var lastRequiredIndex = -1;
59210             var firstRestIndex = -1;
59211             var lastOptionalOrRestIndex = -1;
59212             var _loop_15 = function (i) {
59213                 var type = elementTypes[i];
59214                 var flags = target.elementFlags[i];
59215                 if (flags & 8 /* Variadic */) {
59216                     if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
59217                         // Generic variadic elements stay as they are.
59218                         addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
59219                     }
59220                     else if (isTupleType(type)) {
59221                         var elements = getTypeArguments(type);
59222                         if (elements.length + expandedTypes.length >= 10000) {
59223                             error(currentNode, ts.isPartOfTypeNode(currentNode)
59224                                 ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent
59225                                 : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent);
59226                             return { value: errorType };
59227                         }
59228                         // Spread variadic elements with tuple types into the resulting tuple.
59229                         ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); });
59230                     }
59231                     else {
59232                         // Treat everything else as an array type and create a rest element.
59233                         addElement(isArrayLikeType(type) && getIndexTypeOfType(type, numberType) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
59234                     }
59235                 }
59236                 else {
59237                     // Copy other element kinds with no change.
59238                     addElement(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
59239                 }
59240             };
59241             for (var i = 0; i < elementTypes.length; i++) {
59242                 var state_4 = _loop_15(i);
59243                 if (typeof state_4 === "object")
59244                     return state_4.value;
59245             }
59246             // Turn optional elements preceding the last required element into required elements
59247             for (var i = 0; i < lastRequiredIndex; i++) {
59248                 if (expandedFlags[i] & 2 /* Optional */)
59249                     expandedFlags[i] = 1 /* Required */;
59250             }
59251             if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) {
59252                 // Turn elements between first rest and last optional/rest into a single rest element
59253                 expandedTypes[firstRestIndex] = getUnionType(ts.sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), function (t, i) { return expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; }));
59254                 expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
59255                 expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
59256                 expandedDeclarations === null || expandedDeclarations === void 0 ? void 0 : expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
59257             }
59258             var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
59259             return tupleTarget === emptyGenericType ? emptyObjectType :
59260                 expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
59261                     tupleTarget;
59262             function addElement(type, flags, declaration) {
59263                 if (flags & 1 /* Required */) {
59264                     lastRequiredIndex = expandedFlags.length;
59265                 }
59266                 if (flags & 4 /* Rest */ && firstRestIndex < 0) {
59267                     firstRestIndex = expandedFlags.length;
59268                 }
59269                 if (flags & (2 /* Optional */ | 4 /* Rest */)) {
59270                     lastOptionalOrRestIndex = expandedFlags.length;
59271                 }
59272                 expandedTypes.push(type);
59273                 expandedFlags.push(flags);
59274                 if (expandedDeclarations && declaration) {
59275                     expandedDeclarations.push(declaration);
59276                 }
59277                 else {
59278                     expandedDeclarations = undefined;
59279                 }
59280             }
59281         }
59282         function sliceTupleType(type, index, endSkipCount) {
59283             if (endSkipCount === void 0) { endSkipCount = 0; }
59284             var target = type.target;
59285             var endIndex = getTypeReferenceArity(type) - endSkipCount;
59286             return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(ts.emptyArray) :
59287                 createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), 
59288                 /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
59289         }
59290         function getKnownKeysOfTupleType(type) {
59291             return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getStringLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
59292         }
59293         // Return count of starting consecutive tuple elements of the given kind(s)
59294         function getStartElementCount(type, flags) {
59295             var index = ts.findIndex(type.elementFlags, function (f) { return !(f & flags); });
59296             return index >= 0 ? index : type.elementFlags.length;
59297         }
59298         // Return count of ending consecutive tuple elements of the given kind(s)
59299         function getEndElementCount(type, flags) {
59300             return type.elementFlags.length - ts.findLastIndex(type.elementFlags, function (f) { return !(f & flags); }) - 1;
59301         }
59302         function getTypeFromOptionalTypeNode(node) {
59303             return addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true);
59304         }
59305         function getTypeId(type) {
59306             return type.id;
59307         }
59308         function containsType(types, type) {
59309             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
59310         }
59311         function insertType(types, type) {
59312             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
59313             if (index < 0) {
59314                 types.splice(~index, 0, type);
59315                 return true;
59316             }
59317             return false;
59318         }
59319         function addTypeToUnion(typeSet, includes, type) {
59320             var flags = type.flags;
59321             if (flags & 1048576 /* Union */) {
59322                 return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types);
59323             }
59324             // We ignore 'never' types in unions
59325             if (!(flags & 131072 /* Never */)) {
59326                 includes |= flags & 205258751 /* IncludesMask */;
59327                 if (flags & 465829888 /* Instantiable */)
59328                     includes |= 33554432 /* IncludesInstantiable */;
59329                 if (type === wildcardType)
59330                     includes |= 8388608 /* IncludesWildcard */;
59331                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
59332                     if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
59333                         includes |= 4194304 /* IncludesNonWideningType */;
59334                 }
59335                 else {
59336                     var len = typeSet.length;
59337                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
59338                     if (index < 0) {
59339                         typeSet.splice(~index, 0, type);
59340                     }
59341                 }
59342             }
59343             return includes;
59344         }
59345         // Add the given types to the given type set. Order is preserved, duplicates are removed,
59346         // and nested types of the given kind are flattened into the set.
59347         function addTypesToUnion(typeSet, includes, types) {
59348             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
59349                 var type = types_9[_i];
59350                 includes = addTypeToUnion(typeSet, includes, type);
59351             }
59352             return includes;
59353         }
59354         function removeSubtypes(types, hasObjectTypes) {
59355             var id = getTypeListId(types);
59356             var match = subtypeReductionCache.get(id);
59357             if (match) {
59358                 return match;
59359             }
59360             // We assume that redundant primitive types have already been removed from the types array and that there
59361             // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty
59362             // object types, and if none of those are present we can exclude primitive types from the subtype check.
59363             var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); });
59364             var len = types.length;
59365             var i = len;
59366             var count = 0;
59367             while (i > 0) {
59368                 i--;
59369                 var source = types[i];
59370                 if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) {
59371                     // Find the first property with a unit type, if any. When constituents have a property by the same name
59372                     // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype
59373                     // reduction of large discriminated union types.
59374                     var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ?
59375                         ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) :
59376                         undefined;
59377                     var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty));
59378                     for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
59379                         var target = types_10[_i];
59380                         if (source !== target) {
59381                             if (count === 100000) {
59382                                 // After 100000 subtype checks we estimate the remaining amount of work by assuming the
59383                                 // same ratio of checks per element. If the estimated number of remaining type checks is
59384                                 // greater than 1M we deem the union type too complex to represent. This for example
59385                                 // caps union types at 1000 unique object types.
59386                                 var estimatedCount = (count / (len - i)) * len;
59387                                 if (estimatedCount > 1000000) {
59388                                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
59389                                     error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
59390                                     return undefined;
59391                                 }
59392                             }
59393                             count++;
59394                             if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) {
59395                                 var t = getTypeOfPropertyOfType(target, keyProperty.escapedName);
59396                                 if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) {
59397                                     continue;
59398                                 }
59399                             }
59400                             if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
59401                                 !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
59402                                 isTypeDerivedFrom(source, target))) {
59403                                 ts.orderedRemoveItemAt(types, i);
59404                                 break;
59405                             }
59406                         }
59407                     }
59408                 }
59409             }
59410             subtypeReductionCache.set(id, types);
59411             return types;
59412         }
59413         function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) {
59414             var i = types.length;
59415             while (i > 0) {
59416                 i--;
59417                 var t = types[i];
59418                 var flags = t.flags;
59419                 var remove = flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && includes & 4 /* String */ ||
59420                     flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
59421                     flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
59422                     flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
59423                     reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ ||
59424                     isFreshLiteralType(t) && containsType(types, t.regularType);
59425                 if (remove) {
59426                     ts.orderedRemoveItemAt(types, i);
59427                 }
59428             }
59429         }
59430         function removeStringLiteralsMatchedByTemplateLiterals(types) {
59431             var templates = ts.filter(types, isPatternLiteralType);
59432             if (templates.length) {
59433                 var i = types.length;
59434                 var _loop_16 = function () {
59435                     i--;
59436                     var t = types[i];
59437                     if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) {
59438                         ts.orderedRemoveItemAt(types, i);
59439                     }
59440                 };
59441                 while (i > 0) {
59442                     _loop_16();
59443                 }
59444             }
59445         }
59446         function isNamedUnionType(type) {
59447             return !!(type.flags & 1048576 /* Union */ && (type.aliasSymbol || type.origin));
59448         }
59449         function addNamedUnions(namedUnions, types) {
59450             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
59451                 var t = types_11[_i];
59452                 if (t.flags & 1048576 /* Union */) {
59453                     var origin = t.origin;
59454                     if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) {
59455                         ts.pushIfUnique(namedUnions, t);
59456                     }
59457                     else if (origin && origin.flags & 1048576 /* Union */) {
59458                         addNamedUnions(namedUnions, origin.types);
59459                     }
59460                 }
59461             }
59462         }
59463         function createOriginUnionOrIntersectionType(flags, types) {
59464             var result = createOriginType(flags);
59465             result.types = types;
59466             return result;
59467         }
59468         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
59469         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
59470         // of other types. Subtype reduction is expensive for large union types and is possible only when union
59471         // types are known not to circularly reference themselves (as is the case with union types created by
59472         // expression constructs such as array literals and the || and ?: operators). Named types can
59473         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
59474         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
59475         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) {
59476             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
59477             if (types.length === 0) {
59478                 return neverType;
59479             }
59480             if (types.length === 1) {
59481                 return types[0];
59482             }
59483             var typeSet = [];
59484             var includes = addTypesToUnion(typeSet, 0, types);
59485             if (unionReduction !== 0 /* None */) {
59486                 if (includes & 3 /* AnyOrUnknown */) {
59487                     return includes & 1 /* Any */ ?
59488                         includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType :
59489                         includes & 65536 /* Null */ || containsType(typeSet, unknownType) ? unknownType : nonNullUnknownType;
59490                 }
59491                 if (exactOptionalPropertyTypes && includes & 32768 /* Undefined */) {
59492                     var missingIndex = ts.binarySearch(typeSet, missingType, getTypeId, ts.compareValues);
59493                     if (missingIndex >= 0 && containsType(typeSet, undefinedType)) {
59494                         ts.orderedRemoveItemAt(typeSet, missingIndex);
59495                     }
59496                 }
59497                 if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) {
59498                     removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */));
59499                 }
59500                 if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
59501                     removeStringLiteralsMatchedByTemplateLiterals(typeSet);
59502                 }
59503                 if (unionReduction === 2 /* Subtype */) {
59504                     typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */));
59505                     if (!typeSet) {
59506                         return errorType;
59507                     }
59508                 }
59509                 if (typeSet.length === 0) {
59510                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
59511                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
59512                             neverType;
59513                 }
59514             }
59515             if (!origin && includes & 1048576 /* Union */) {
59516                 var namedUnions = [];
59517                 addNamedUnions(namedUnions, types);
59518                 var reducedTypes = [];
59519                 var _loop_17 = function (t) {
59520                     if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) {
59521                         reducedTypes.push(t);
59522                     }
59523                 };
59524                 for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) {
59525                     var t = typeSet_1[_i];
59526                     _loop_17(t);
59527                 }
59528                 if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) {
59529                     return namedUnions[0];
59530                 }
59531                 // We create a denormalized origin type only when the union was created from one or more named unions
59532                 // (unions with alias symbols or origins) and when there is no overlap between those named unions.
59533                 var namedTypesCount = ts.reduceLeft(namedUnions, function (sum, union) { return sum + union.types.length; }, 0);
59534                 if (namedTypesCount + reducedTypes.length === typeSet.length) {
59535                     for (var _a = 0, namedUnions_1 = namedUnions; _a < namedUnions_1.length; _a++) {
59536                         var t = namedUnions_1[_a];
59537                         insertType(reducedTypes, t);
59538                     }
59539                     origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes);
59540                 }
59541             }
59542             var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) |
59543                 (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0);
59544             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin);
59545         }
59546         function getUnionOrIntersectionTypePredicate(signatures, kind) {
59547             var first;
59548             var types = [];
59549             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
59550                 var sig = signatures_6[_i];
59551                 var pred = getTypePredicateOfSignature(sig);
59552                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
59553                     if (kind !== 2097152 /* Intersection */) {
59554                         continue;
59555                     }
59556                     else {
59557                         return; // intersections demand all members be type predicates for the result to have a predicate
59558                     }
59559                 }
59560                 if (first) {
59561                     if (!typePredicateKindsMatch(first, pred)) {
59562                         // No common type predicate.
59563                         return undefined;
59564                     }
59565                 }
59566                 else {
59567                     first = pred;
59568                 }
59569                 types.push(pred.type);
59570             }
59571             if (!first) {
59572                 // No signatures had a type predicate.
59573                 return undefined;
59574             }
59575             var compositeType = getUnionOrIntersectionType(types, kind);
59576             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType);
59577         }
59578         function typePredicateKindsMatch(a, b) {
59579             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
59580         }
59581         // This function assumes the constituent type list is sorted and deduplicated.
59582         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments, origin) {
59583             if (types.length === 0) {
59584                 return neverType;
59585             }
59586             if (types.length === 1) {
59587                 return types[0];
59588             }
59589             var typeKey = !origin ? getTypeListId(types) :
59590                 origin.flags & 1048576 /* Union */ ? "|".concat(getTypeListId(origin.types)) :
59591                     origin.flags & 2097152 /* Intersection */ ? "&".concat(getTypeListId(origin.types)) :
59592                         "#".concat(origin.type.id, "|").concat(getTypeListId(types)); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving
59593             var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments);
59594             var type = unionTypes.get(id);
59595             if (!type) {
59596                 type = createType(1048576 /* Union */);
59597                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
59598                 type.types = types;
59599                 type.origin = origin;
59600                 type.aliasSymbol = aliasSymbol;
59601                 type.aliasTypeArguments = aliasTypeArguments;
59602                 if (types.length === 2 && types[0].flags & 512 /* BooleanLiteral */ && types[1].flags & 512 /* BooleanLiteral */) {
59603                     type.flags |= 16 /* Boolean */;
59604                     type.intrinsicName = "boolean";
59605                 }
59606                 unionTypes.set(id, type);
59607             }
59608             return type;
59609         }
59610         function getTypeFromUnionTypeNode(node) {
59611             var links = getNodeLinks(node);
59612             if (!links.resolvedType) {
59613                 var aliasSymbol = getAliasSymbolForTypeNode(node);
59614                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
59615             }
59616             return links.resolvedType;
59617         }
59618         function addTypeToIntersection(typeSet, includes, type) {
59619             var flags = type.flags;
59620             if (flags & 2097152 /* Intersection */) {
59621                 return addTypesToIntersection(typeSet, includes, type.types);
59622             }
59623             if (isEmptyAnonymousObjectType(type)) {
59624                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
59625                     includes |= 16777216 /* IncludesEmptyObject */;
59626                     typeSet.set(type.id.toString(), type);
59627                 }
59628             }
59629             else {
59630                 if (flags & 3 /* AnyOrUnknown */) {
59631                     if (type === wildcardType)
59632                         includes |= 8388608 /* IncludesWildcard */;
59633                 }
59634                 else if (strictNullChecks || !(flags & 98304 /* Nullable */)) {
59635                     if (exactOptionalPropertyTypes && type === missingType) {
59636                         includes |= 262144 /* IncludesMissingType */;
59637                         type = undefinedType;
59638                     }
59639                     if (!typeSet.has(type.id.toString())) {
59640                         if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
59641                             // We have seen two distinct unit types which means we should reduce to an
59642                             // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
59643                             includes |= 67108864 /* NonPrimitive */;
59644                         }
59645                         typeSet.set(type.id.toString(), type);
59646                     }
59647                 }
59648                 includes |= flags & 205258751 /* IncludesMask */;
59649             }
59650             return includes;
59651         }
59652         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
59653         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
59654         function addTypesToIntersection(typeSet, includes, types) {
59655             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
59656                 var type = types_12[_i];
59657                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
59658             }
59659             return includes;
59660         }
59661         function removeRedundantPrimitiveTypes(types, includes) {
59662             var i = types.length;
59663             while (i > 0) {
59664                 i--;
59665                 var t = types[i];
59666                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
59667                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
59668                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
59669                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
59670                 if (remove) {
59671                     ts.orderedRemoveItemAt(types, i);
59672                 }
59673             }
59674         }
59675         // Check that the given type has a match in every union. A given type is matched by
59676         // an identical type, and a literal type is additionally matched by its corresponding
59677         // primitive type.
59678         function eachUnionContains(unionTypes, type) {
59679             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
59680                 var u = unionTypes_1[_i];
59681                 if (!containsType(u.types, type)) {
59682                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
59683                         type.flags & 256 /* NumberLiteral */ ? numberType :
59684                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
59685                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
59686                                     undefined;
59687                     if (!primitive || !containsType(u.types, primitive)) {
59688                         return false;
59689                     }
59690                 }
59691             }
59692             return true;
59693         }
59694         /**
59695          * 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`
59696          */
59697         function extractRedundantTemplateLiterals(types) {
59698             var i = types.length;
59699             var literals = ts.filter(types, function (t) { return !!(t.flags & 128 /* StringLiteral */); });
59700             while (i > 0) {
59701                 i--;
59702                 var t = types[i];
59703                 if (!(t.flags & 134217728 /* TemplateLiteral */))
59704                     continue;
59705                 for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) {
59706                     var t2 = literals_1[_i];
59707                     if (isTypeSubtypeOf(t2, t)) {
59708                         // eg, ``get${T}` & "getX"` is just `"getX"`
59709                         ts.orderedRemoveItemAt(types, i);
59710                         break;
59711                     }
59712                     else if (isPatternLiteralType(t)) {
59713                         return true;
59714                     }
59715                 }
59716             }
59717             return false;
59718         }
59719         function eachIsUnionContaining(types, flag) {
59720             return ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); });
59721         }
59722         function removeFromEach(types, flag) {
59723             for (var i = 0; i < types.length; i++) {
59724                 types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
59725             }
59726         }
59727         // If the given list of types contains more than one union of primitive types, replace the
59728         // first with a union containing an intersection of those primitive types, then remove the
59729         // other unions and return true. Otherwise, do nothing and return false.
59730         function intersectUnionsOfPrimitiveTypes(types) {
59731             var unionTypes;
59732             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
59733             if (index < 0) {
59734                 return false;
59735             }
59736             var i = index + 1;
59737             // Remove all but the first union of primitive types and collect them in
59738             // the unionTypes array.
59739             while (i < types.length) {
59740                 var t = types[i];
59741                 if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
59742                     (unionTypes || (unionTypes = [types[index]])).push(t);
59743                     ts.orderedRemoveItemAt(types, i);
59744                 }
59745                 else {
59746                     i++;
59747                 }
59748             }
59749             // Return false if there was only one union of primitive types
59750             if (!unionTypes) {
59751                 return false;
59752             }
59753             // We have more than one union of primitive types, now intersect them. For each
59754             // type in each union we check if the type is matched in every union and if so
59755             // we include it in the result.
59756             var checked = [];
59757             var result = [];
59758             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
59759                 var u = unionTypes_2[_i];
59760                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
59761                     var t = _b[_a];
59762                     if (insertType(checked, t)) {
59763                         if (eachUnionContains(unionTypes, t)) {
59764                             insertType(result, t);
59765                         }
59766                     }
59767                 }
59768             }
59769             // Finally replace the first union with the result
59770             types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
59771             return true;
59772         }
59773         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
59774             var result = createType(2097152 /* Intersection */);
59775             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
59776             result.types = types;
59777             result.aliasSymbol = aliasSymbol;
59778             result.aliasTypeArguments = aliasTypeArguments;
59779             return result;
59780         }
59781         // We normalize combinations of intersection and union types based on the distributive property of the '&'
59782         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
59783         // types with union type constituents into equivalent union types with intersection type constituents and
59784         // effectively ensure that union types are always at the top level in type representations.
59785         //
59786         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
59787         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
59788         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
59789         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
59790         // for intersections of types with signatures can be deterministic.
59791         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
59792             var typeMembershipMap = new ts.Map();
59793             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
59794             var typeSet = ts.arrayFrom(typeMembershipMap.values());
59795             // An intersection type is considered empty if it contains
59796             // the type never, or
59797             // more than one unit type or,
59798             // an object type and a nullable type (null or undefined), or
59799             // a string-like type and a type known to be non-string-like, or
59800             // a number-like type and a type known to be non-number-like, or
59801             // a symbol-like type and a type known to be non-symbol-like, or
59802             // a void-like type and a type known to be non-void-like, or
59803             // a non-primitive type and a type known to be primitive.
59804             if (includes & 131072 /* Never */) {
59805                 return ts.contains(typeSet, silentNeverType) ? silentNeverType : neverType;
59806             }
59807             if (strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
59808                 includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
59809                 includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) ||
59810                 includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) ||
59811                 includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
59812                 includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
59813                 includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
59814                 return neverType;
59815             }
59816             if (includes & 134217728 /* TemplateLiteral */ && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) {
59817                 return neverType;
59818             }
59819             if (includes & 1 /* Any */) {
59820                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
59821             }
59822             if (!strictNullChecks && includes & 98304 /* Nullable */) {
59823                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
59824             }
59825             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
59826                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
59827                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
59828                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
59829                 removeRedundantPrimitiveTypes(typeSet, includes);
59830             }
59831             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
59832                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
59833             }
59834             if (includes & 262144 /* IncludesMissingType */) {
59835                 typeSet[typeSet.indexOf(undefinedType)] = missingType;
59836             }
59837             if (typeSet.length === 0) {
59838                 return unknownType;
59839             }
59840             if (typeSet.length === 1) {
59841                 return typeSet[0];
59842             }
59843             var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments);
59844             var result = intersectionTypes.get(id);
59845             if (!result) {
59846                 if (includes & 1048576 /* Union */) {
59847                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
59848                         // When the intersection creates a reduced set (which might mean that *all* union types have
59849                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
59850                         // reduced we'll never reduce again, so this occurs at most once.
59851                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
59852                     }
59853                     else if (eachIsUnionContaining(typeSet, 32768 /* Undefined */)) {
59854                         var undefinedOrMissingType = exactOptionalPropertyTypes && ts.some(typeSet, function (t) { return containsType(t.types, missingType); }) ? missingType : undefinedType;
59855                         removeFromEach(typeSet, 32768 /* Undefined */);
59856                         result = getUnionType([getIntersectionType(typeSet), undefinedOrMissingType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
59857                     }
59858                     else if (eachIsUnionContaining(typeSet, 65536 /* Null */)) {
59859                         removeFromEach(typeSet, 65536 /* Null */);
59860                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
59861                     }
59862                     else {
59863                         // We are attempting to construct a type of the form X & (A | B) & (C | D). Transform this into a type of
59864                         // the form X & A & C | X & A & D | X & B & C | X & B & D. If the estimated size of the resulting union type
59865                         // exceeds 100000 constituents, report an error.
59866                         if (!checkCrossProductUnion(typeSet)) {
59867                             return errorType;
59868                         }
59869                         var constituents = getCrossProductIntersections(typeSet);
59870                         // We attach a denormalized origin type when at least one constituent of the cross-product union is an
59871                         // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions).
59872                         var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : undefined;
59873                         result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin);
59874                     }
59875                 }
59876                 else {
59877                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
59878                 }
59879                 intersectionTypes.set(id, result);
59880             }
59881             return result;
59882         }
59883         function getCrossProductUnionSize(types) {
59884             return ts.reduceLeft(types, function (n, t) { return t.flags & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n; }, 1);
59885         }
59886         function checkCrossProductUnion(types) {
59887             var size = getCrossProductUnionSize(types);
59888             if (size >= 100000) {
59889                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size });
59890                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
59891                 return false;
59892             }
59893             return true;
59894         }
59895         function getCrossProductIntersections(types) {
59896             var count = getCrossProductUnionSize(types);
59897             var intersections = [];
59898             for (var i = 0; i < count; i++) {
59899                 var constituents = types.slice();
59900                 var n = i;
59901                 for (var j = types.length - 1; j >= 0; j--) {
59902                     if (types[j].flags & 1048576 /* Union */) {
59903                         var sourceTypes = types[j].types;
59904                         var length_5 = sourceTypes.length;
59905                         constituents[j] = sourceTypes[n % length_5];
59906                         n = Math.floor(n / length_5);
59907                     }
59908                 }
59909                 var t = getIntersectionType(constituents);
59910                 if (!(t.flags & 131072 /* Never */))
59911                     intersections.push(t);
59912             }
59913             return intersections;
59914         }
59915         function getTypeFromIntersectionTypeNode(node) {
59916             var links = getNodeLinks(node);
59917             if (!links.resolvedType) {
59918                 var aliasSymbol = getAliasSymbolForTypeNode(node);
59919                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
59920             }
59921             return links.resolvedType;
59922         }
59923         function createIndexType(type, stringsOnly) {
59924             var result = createType(4194304 /* Index */);
59925             result.type = type;
59926             result.stringsOnly = stringsOnly;
59927             return result;
59928         }
59929         function createOriginIndexType(type) {
59930             var result = createOriginType(4194304 /* Index */);
59931             result.type = type;
59932             return result;
59933         }
59934         function getIndexTypeForGenericType(type, stringsOnly) {
59935             return stringsOnly ?
59936                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
59937                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
59938         }
59939         /**
59940          * This roughly mirrors `resolveMappedTypeMembers` in the nongeneric case, except only reports a union of the keys calculated,
59941          * rather than manufacturing the properties. We can't just fetch the `constraintType` since that would ignore mappings
59942          * and mapping the `constraintType` directly ignores how mapped types map _properties_ and not keys (thus ignoring subtype
59943          * reduction in the constraintType) when possible.
59944          * @param noIndexSignatures Indicates if _string_ index signatures should be elided. (other index signatures are always reported)
59945          */
59946         function getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) {
59947             var typeParameter = getTypeParameterFromMappedType(type);
59948             var constraintType = getConstraintTypeFromMappedType(type);
59949             var nameType = getNameTypeFromMappedType(type.target || type);
59950             if (!nameType && !noIndexSignatures) {
59951                 // no mapping and no filtering required, just quickly bail to returning the constraint in the common case
59952                 return constraintType;
59953             }
59954             var keyTypes = [];
59955             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
59956                 // We have a { [P in keyof T]: X }
59957                 // `getApparentType` on the T in a generic mapped type can trigger a circularity
59958                 // (conditionals and `infer` types create a circular dependency in the constraint resolution)
59959                 // so we only eagerly manifest the keys if the constraint is nongeneric
59960                 if (!isGenericIndexType(constraintType)) {
59961                     var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
59962                     forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */, stringsOnly, addMemberForKeyType);
59963                 }
59964                 else {
59965                     // we have a generic index and a homomorphic mapping (but a distributive key remapping) - we need to defer the whole `keyof whatever` for later
59966                     // since it's not safe to resolve the shape of modifier type
59967                     return getIndexTypeForGenericType(type, stringsOnly);
59968                 }
59969             }
59970             else {
59971                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
59972             }
59973             if (isGenericIndexType(constraintType)) { // include the generic component in the resulting type
59974                 forEachType(constraintType, addMemberForKeyType);
59975             }
59976             // we had to pick apart the constraintType to potentially map/filter it - compare the final resulting list with the original constraintType,
59977             // so we can return the union that preserves aliases/origin data if possible
59978             var result = noIndexSignatures ? filterType(getUnionType(keyTypes), function (t) { return !(t.flags & (1 /* Any */ | 4 /* String */)); }) : getUnionType(keyTypes);
59979             if (result.flags & 1048576 /* Union */ && constraintType.flags & 1048576 /* Union */ && getTypeListId(result.types) === getTypeListId(constraintType.types)) {
59980                 return constraintType;
59981             }
59982             return result;
59983             function addMemberForKeyType(keyType) {
59984                 var propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
59985                 // `keyof` currently always returns `string | number` for concrete `string` index signatures - the below ternary keeps that behavior for mapped types
59986                 // See `getLiteralTypeFromProperties` where there's a similar ternary to cause the same behavior.
59987                 keyTypes.push(propNameType === stringType ? stringOrNumberType : propNameType);
59988             }
59989         }
59990         // 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
59991         // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. Specifically, we only
59992         // want to perform the reduction when the name type of a mapped type is distributive with respect to the type variable
59993         // introduced by the 'in' clause of the mapped type. Note that non-generic types are considered to be distributive because
59994         // they're the same type regardless of what's being distributed over.
59995         function hasDistributiveNameType(mappedType) {
59996             var typeVariable = getTypeParameterFromMappedType(mappedType);
59997             return isDistributive(getNameTypeFromMappedType(mappedType) || typeVariable);
59998             function isDistributive(type) {
59999                 return type.flags & (3 /* AnyOrUnknown */ | 131068 /* Primitive */ | 131072 /* Never */ | 262144 /* TypeParameter */ | 524288 /* Object */ | 67108864 /* NonPrimitive */) ? true :
60000                     type.flags & 16777216 /* Conditional */ ? type.root.isDistributive && type.checkType === typeVariable :
60001                         type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) ? ts.every(type.types, isDistributive) :
60002                             type.flags & 8388608 /* IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) :
60003                                 type.flags & 33554432 /* Substitution */ ? isDistributive(type.substitute) :
60004                                     type.flags & 268435456 /* StringMapping */ ? isDistributive(type.type) :
60005                                         false;
60006             }
60007         }
60008         function getLiteralTypeFromPropertyName(name) {
60009             if (ts.isPrivateIdentifier(name)) {
60010                 return neverType;
60011             }
60012             return ts.isIdentifier(name) ? getStringLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
60013                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
60014         }
60015         function getLiteralTypeFromProperty(prop, include, includeNonPublic) {
60016             if (includeNonPublic || !(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
60017                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
60018                 if (!type) {
60019                     var name = ts.getNameOfDeclaration(prop.valueDeclaration);
60020                     type = prop.escapedName === "default" /* Default */ ? getStringLiteralType("default") :
60021                         name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getStringLiteralType(ts.symbolName(prop)) : undefined);
60022                 }
60023                 if (type && type.flags & include) {
60024                     return type;
60025                 }
60026             }
60027             return neverType;
60028         }
60029         function isKeyTypeIncluded(keyType, include) {
60030             return !!(keyType.flags & include || keyType.flags & 2097152 /* Intersection */ && ts.some(keyType.types, function (t) { return isKeyTypeIncluded(t, include); }));
60031         }
60032         function getLiteralTypeFromProperties(type, include, includeOrigin) {
60033             var origin = includeOrigin && (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */) || type.aliasSymbol) ? createOriginIndexType(type) : undefined;
60034             var propertyTypes = ts.map(getPropertiesOfType(type), function (prop) { return getLiteralTypeFromProperty(prop, include); });
60035             var indexKeyTypes = ts.map(getIndexInfosOfType(type), function (info) { return info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ?
60036                 info.keyType === stringType && include & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType; });
60037             return getUnionType(ts.concatenate(propertyTypes, indexKeyTypes), 1 /* Literal */, 
60038             /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, origin);
60039         }
60040         function getIndexType(type, stringsOnly, noIndexSignatures) {
60041             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
60042             type = getReducedType(type);
60043             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
60044                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
60045                     type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) :
60046                         ts.getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) :
60047                             type === wildcardType ? wildcardType :
60048                                 type.flags & 2 /* Unknown */ ? neverType :
60049                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
60050                                         getLiteralTypeFromProperties(type, (noIndexSignatures ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (stringsOnly ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), stringsOnly === keyofStringsOnly && !noIndexSignatures);
60051         }
60052         function getExtractStringType(type) {
60053             if (keyofStringsOnly) {
60054                 return type;
60055             }
60056             var extractTypeAlias = getGlobalExtractSymbol();
60057             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
60058         }
60059         function getIndexTypeOrString(type) {
60060             var indexType = getExtractStringType(getIndexType(type));
60061             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
60062         }
60063         function getTypeFromTypeOperatorNode(node) {
60064             var links = getNodeLinks(node);
60065             if (!links.resolvedType) {
60066                 switch (node.operator) {
60067                     case 140 /* KeyOfKeyword */:
60068                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
60069                         break;
60070                     case 153 /* UniqueKeyword */:
60071                         links.resolvedType = node.type.kind === 150 /* SymbolKeyword */
60072                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
60073                             : errorType;
60074                         break;
60075                     case 144 /* ReadonlyKeyword */:
60076                         links.resolvedType = getTypeFromTypeNode(node.type);
60077                         break;
60078                     default:
60079                         throw ts.Debug.assertNever(node.operator);
60080                 }
60081             }
60082             return links.resolvedType;
60083         }
60084         function getTypeFromTemplateTypeNode(node) {
60085             var links = getNodeLinks(node);
60086             if (!links.resolvedType) {
60087                 links.resolvedType = getTemplateLiteralType(__spreadArray([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; }), true), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
60088             }
60089             return links.resolvedType;
60090         }
60091         function getTemplateLiteralType(texts, types) {
60092             var unionIndex = ts.findIndex(types, function (t) { return !!(t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
60093             if (unionIndex >= 0) {
60094                 return checkCrossProductUnion(types) ?
60095                     mapType(types[unionIndex], function (t) { return getTemplateLiteralType(texts, ts.replaceElement(types, unionIndex, t)); }) :
60096                     errorType;
60097             }
60098             if (ts.contains(types, wildcardType)) {
60099                 return wildcardType;
60100             }
60101             var newTypes = [];
60102             var newTexts = [];
60103             var text = texts[0];
60104             if (!addSpans(texts, types)) {
60105                 return stringType;
60106             }
60107             if (newTypes.length === 0) {
60108                 return getStringLiteralType(text);
60109             }
60110             newTexts.push(text);
60111             if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* String */); })) {
60112                 return stringType;
60113             }
60114             var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join(""));
60115             var type = templateLiteralTypes.get(id);
60116             if (!type) {
60117                 templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes));
60118             }
60119             return type;
60120             function addSpans(texts, types) {
60121                 for (var i = 0; i < types.length; i++) {
60122                     var t = types[i];
60123                     if (t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) {
60124                         text += getTemplateStringForType(t) || "";
60125                         text += texts[i + 1];
60126                     }
60127                     else if (t.flags & 134217728 /* TemplateLiteral */) {
60128                         text += t.texts[0];
60129                         if (!addSpans(t.texts, t.types))
60130                             return false;
60131                         text += texts[i + 1];
60132                     }
60133                     else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) {
60134                         newTypes.push(t);
60135                         newTexts.push(text);
60136                         text = texts[i + 1];
60137                     }
60138                     else {
60139                         return false;
60140                     }
60141                 }
60142                 return true;
60143             }
60144         }
60145         function getTemplateStringForType(type) {
60146             return type.flags & 128 /* StringLiteral */ ? type.value :
60147                 type.flags & 256 /* NumberLiteral */ ? "" + type.value :
60148                     type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) :
60149                         type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName :
60150                             undefined;
60151         }
60152         function createTemplateLiteralType(texts, types) {
60153             var type = createType(134217728 /* TemplateLiteral */);
60154             type.texts = texts;
60155             type.types = types;
60156             return type;
60157         }
60158         function getStringMappingType(symbol, type) {
60159             return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) :
60160                 isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) :
60161                     type.flags & 128 /* StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) :
60162                         type;
60163         }
60164         function applyStringMapping(symbol, str) {
60165             switch (intrinsicTypeKinds.get(symbol.escapedName)) {
60166                 case 0 /* Uppercase */: return str.toUpperCase();
60167                 case 1 /* Lowercase */: return str.toLowerCase();
60168                 case 2 /* Capitalize */: return str.charAt(0).toUpperCase() + str.slice(1);
60169                 case 3 /* Uncapitalize */: return str.charAt(0).toLowerCase() + str.slice(1);
60170             }
60171             return str;
60172         }
60173         function getStringMappingTypeForGenericType(symbol, type) {
60174             var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type));
60175             var result = stringMappingTypes.get(id);
60176             if (!result) {
60177                 stringMappingTypes.set(id, result = createStringMappingType(symbol, type));
60178             }
60179             return result;
60180         }
60181         function createStringMappingType(symbol, type) {
60182             var result = createType(268435456 /* StringMapping */);
60183             result.symbol = symbol;
60184             result.type = type;
60185             return result;
60186         }
60187         function createIndexedAccessType(objectType, indexType, accessFlags, aliasSymbol, aliasTypeArguments) {
60188             var type = createType(8388608 /* IndexedAccess */);
60189             type.objectType = objectType;
60190             type.indexType = indexType;
60191             type.accessFlags = accessFlags;
60192             type.aliasSymbol = aliasSymbol;
60193             type.aliasTypeArguments = aliasTypeArguments;
60194             return type;
60195         }
60196         /**
60197          * Returns if a type is or consists of a JSLiteral object type
60198          * In addition to objects which are directly literals,
60199          * * unions where every element is a jsliteral
60200          * * intersections where at least one element is a jsliteral
60201          * * and instantiable types constrained to a jsliteral
60202          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
60203          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
60204          */
60205         function isJSLiteralType(type) {
60206             if (noImplicitAny) {
60207                 return false; // Flag is meaningless under `noImplicitAny` mode
60208             }
60209             if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) {
60210                 return true;
60211             }
60212             if (type.flags & 1048576 /* Union */) {
60213                 return ts.every(type.types, isJSLiteralType);
60214             }
60215             if (type.flags & 2097152 /* Intersection */) {
60216                 return ts.some(type.types, isJSLiteralType);
60217             }
60218             if (type.flags & 465829888 /* Instantiable */) {
60219                 var constraint = getResolvedBaseConstraint(type);
60220                 return constraint !== type && isJSLiteralType(constraint);
60221             }
60222             return false;
60223         }
60224         function getPropertyNameFromIndex(indexType, accessNode) {
60225             return isTypeUsableAsPropertyName(indexType) ?
60226                 getPropertyNameFromType(indexType) :
60227                 accessNode && ts.isPropertyName(accessNode) ?
60228                     // late bound names are handled in the first branch, so here we only need to handle normal names
60229                     ts.getPropertyNameForPropertyNameNode(accessNode) :
60230                     undefined;
60231         }
60232         function isUncalledFunctionReference(node, symbol) {
60233             if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
60234                 var parent = ts.findAncestor(node.parent, function (n) { return !ts.isAccessExpression(n); }) || node.parent;
60235                 if (ts.isCallLikeExpression(parent)) {
60236                     return ts.isCallOrNewExpression(parent) && ts.isIdentifier(node) && hasMatchingArgument(parent, node);
60237                 }
60238                 return ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
60239             }
60240             return true;
60241         }
60242         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) {
60243             var _a;
60244             var accessExpression = accessNode && accessNode.kind === 206 /* ElementAccessExpression */ ? accessNode : undefined;
60245             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
60246             if (propName !== undefined) {
60247                 if (accessFlags & 256 /* Contextual */) {
60248                     return getTypeOfPropertyOfContextualType(objectType, propName) || anyType;
60249                 }
60250                 var prop = getPropertyOfType(objectType, propName);
60251                 if (prop) {
60252                     if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
60253                         var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
60254                         addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName);
60255                     }
60256                     if (accessExpression) {
60257                         markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol));
60258                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
60259                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
60260                             return undefined;
60261                         }
60262                         if (accessFlags & 8 /* CacheSymbol */) {
60263                             getNodeLinks(accessNode).resolvedSymbol = prop;
60264                         }
60265                         if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
60266                             return autoType;
60267                         }
60268                     }
60269                     var propType = getTypeOfSymbol(prop);
60270                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
60271                         getFlowTypeOfReference(accessExpression, propType) :
60272                         propType;
60273                 }
60274                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
60275                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) {
60276                         var indexNode = getIndexNodeForAccessExpression(accessNode);
60277                         if (isTupleType(objectType)) {
60278                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
60279                         }
60280                         else {
60281                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
60282                         }
60283                     }
60284                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType));
60285                     return mapType(objectType, function (t) {
60286                         var restType = getRestTypeOfTupleType(t) || undefinedType;
60287                         return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType;
60288                     });
60289                 }
60290             }
60291             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
60292                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
60293                     return objectType;
60294                 }
60295                 // If no index signature is applicable, we default to the string index signature. In effect, this means the string
60296                 // index signature applies even when accessing with a symbol-like type.
60297                 var indexInfo = getApplicableIndexInfo(objectType, indexType) || getIndexInfoOfType(objectType, stringType);
60298                 if (indexInfo) {
60299                     if (accessFlags & 2 /* NoIndexSignatures */ && indexInfo.keyType !== numberType) {
60300                         if (accessExpression) {
60301                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
60302                         }
60303                         return undefined;
60304                     }
60305                     if (accessNode && indexInfo.keyType === stringType && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
60306                         var indexNode = getIndexNodeForAccessExpression(accessNode);
60307                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
60308                         return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
60309                     }
60310                     errorIfWritingToReadonlyIndex(indexInfo);
60311                     return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
60312                 }
60313                 if (indexType.flags & 131072 /* Never */) {
60314                     return neverType;
60315                 }
60316                 if (isJSLiteralType(objectType)) {
60317                     return anyType;
60318                 }
60319                 if (accessExpression && !isConstEnumObjectType(objectType)) {
60320                     if (isObjectLiteralType(objectType)) {
60321                         if (noImplicitAny && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
60322                             diagnostics.add(ts.createDiagnosticForNode(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)));
60323                             return undefinedType;
60324                         }
60325                         else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
60326                             var types = ts.map(objectType.properties, function (property) {
60327                                 return getTypeOfSymbol(property);
60328                             });
60329                             return getUnionType(ts.append(types, undefinedType));
60330                         }
60331                     }
60332                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
60333                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
60334                     }
60335                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !(accessFlags & 128 /* SuppressNoImplicitAnyError */)) {
60336                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
60337                             var typeName = typeToString(objectType);
60338                             error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + ts.getTextOfNode(accessExpression.argumentExpression) + "]");
60339                         }
60340                         else if (getIndexTypeOfType(objectType, numberType)) {
60341                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
60342                         }
60343                         else {
60344                             var suggestion = void 0;
60345                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
60346                                 if (suggestion !== undefined) {
60347                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
60348                                 }
60349                             }
60350                             else {
60351                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
60352                                 if (suggestion_1 !== undefined) {
60353                                     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);
60354                                 }
60355                                 else {
60356                                     var errorInfo = void 0;
60357                                     if (indexType.flags & 1024 /* EnumLiteral */) {
60358                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
60359                                     }
60360                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
60361                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
60362                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
60363                                     }
60364                                     else if (indexType.flags & 128 /* StringLiteral */) {
60365                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
60366                                     }
60367                                     else if (indexType.flags & 256 /* NumberLiteral */) {
60368                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
60369                                     }
60370                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
60371                                         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));
60372                                     }
60373                                     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));
60374                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
60375                                 }
60376                             }
60377                         }
60378                     }
60379                     return undefined;
60380                 }
60381             }
60382             if (isJSLiteralType(objectType)) {
60383                 return anyType;
60384             }
60385             if (accessNode) {
60386                 var indexNode = getIndexNodeForAccessExpression(accessNode);
60387                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
60388                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
60389                 }
60390                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
60391                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
60392                 }
60393                 else {
60394                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
60395                 }
60396             }
60397             if (isTypeAny(indexType)) {
60398                 return indexType;
60399             }
60400             return undefined;
60401             function errorIfWritingToReadonlyIndex(indexInfo) {
60402                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
60403                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
60404                 }
60405             }
60406         }
60407         function getIndexNodeForAccessExpression(accessNode) {
60408             return accessNode.kind === 206 /* ElementAccessExpression */ ? accessNode.argumentExpression :
60409                 accessNode.kind === 193 /* IndexedAccessType */ ? accessNode.indexType :
60410                     accessNode.kind === 161 /* ComputedPropertyName */ ? accessNode.expression :
60411                         accessNode;
60412         }
60413         function isPatternLiteralPlaceholderType(type) {
60414             return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */));
60415         }
60416         function isPatternLiteralType(type) {
60417             return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType);
60418         }
60419         function isGenericType(type) {
60420             return !!getGenericObjectFlags(type);
60421         }
60422         function isGenericObjectType(type) {
60423             return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericObjectType */);
60424         }
60425         function isGenericIndexType(type) {
60426             return !!(getGenericObjectFlags(type) & 16777216 /* IsGenericIndexType */);
60427         }
60428         function getGenericObjectFlags(type) {
60429             if (type.flags & 3145728 /* UnionOrIntersection */) {
60430                 if (!(type.objectFlags & 4194304 /* IsGenericTypeComputed */)) {
60431                     type.objectFlags |= 4194304 /* IsGenericTypeComputed */ |
60432                         ts.reduceLeft(type.types, function (flags, t) { return flags | getGenericObjectFlags(t); }, 0);
60433                 }
60434                 return type.objectFlags & 25165824 /* IsGenericType */;
60435             }
60436             if (type.flags & 33554432 /* Substitution */) {
60437                 if (!(type.objectFlags & 4194304 /* IsGenericTypeComputed */)) {
60438                     type.objectFlags |= 4194304 /* IsGenericTypeComputed */ |
60439                         getGenericObjectFlags(type.substitute) | getGenericObjectFlags(type.baseType);
60440                 }
60441                 return type.objectFlags & 25165824 /* IsGenericType */;
60442             }
60443             return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 8388608 /* IsGenericObjectType */ : 0) |
60444                 (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 16777216 /* IsGenericIndexType */ : 0);
60445         }
60446         function isThisTypeParameter(type) {
60447             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
60448         }
60449         function getSimplifiedType(type, writing) {
60450             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
60451                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
60452                     type;
60453         }
60454         function distributeIndexOverObjectType(objectType, indexType, writing) {
60455             // (T | U)[K] -> T[K] | U[K] (reading)
60456             // (T | U)[K] -> T[K] & U[K] (writing)
60457             // (T & U)[K] -> T[K] & U[K]
60458             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
60459                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
60460                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
60461             }
60462         }
60463         function distributeObjectOverIndexType(objectType, indexType, writing) {
60464             // T[A | B] -> T[A] | T[B] (reading)
60465             // T[A | B] -> T[A] & T[B] (writing)
60466             if (indexType.flags & 1048576 /* Union */) {
60467                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
60468                 return writing ? getIntersectionType(types) : getUnionType(types);
60469             }
60470         }
60471         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
60472         // the type itself if no transformation is possible. The writing flag indicates that the type is
60473         // the target of an assignment.
60474         function getSimplifiedIndexedAccessType(type, writing) {
60475             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
60476             if (type[cache]) {
60477                 return type[cache] === circularConstraintType ? type : type[cache];
60478             }
60479             type[cache] = circularConstraintType;
60480             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
60481             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
60482             var objectType = getSimplifiedType(type.objectType, writing);
60483             var indexType = getSimplifiedType(type.indexType, writing);
60484             // T[A | B] -> T[A] | T[B] (reading)
60485             // T[A | B] -> T[A] & T[B] (writing)
60486             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
60487             if (distributedOverIndex) {
60488                 return type[cache] = distributedOverIndex;
60489             }
60490             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
60491             if (!(indexType.flags & 465829888 /* Instantiable */)) {
60492                 // (T | U)[K] -> T[K] | U[K] (reading)
60493                 // (T | U)[K] -> T[K] & U[K] (writing)
60494                 // (T & U)[K] -> T[K] & U[K]
60495                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
60496                 if (distributedOverObject) {
60497                     return type[cache] = distributedOverObject;
60498                 }
60499             }
60500             // So ultimately (reading):
60501             // ((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]
60502             // A generic tuple type indexed by a number exists only when the index type doesn't select a
60503             // fixed element. We simplify to either the combined type of all elements (when the index type
60504             // the actual number type) or to the combined type of all non-fixed elements.
60505             if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
60506                 var elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ 0, writing);
60507                 if (elementType) {
60508                     return type[cache] = elementType;
60509                 }
60510             }
60511             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
60512             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
60513             // construct the type Box<T[X]>.
60514             if (isGenericMappedType(objectType)) {
60515                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
60516             }
60517             return type[cache] = type;
60518         }
60519         function getSimplifiedConditionalType(type, writing) {
60520             var checkType = type.checkType;
60521             var extendsType = type.extendsType;
60522             var trueType = getTrueTypeFromConditionalType(type);
60523             var falseType = getFalseTypeFromConditionalType(type);
60524             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
60525             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
60526                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
60527                     return getSimplifiedType(trueType, writing);
60528                 }
60529                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
60530                     return neverType;
60531                 }
60532             }
60533             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
60534                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
60535                     return neverType;
60536                 }
60537                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
60538                     return getSimplifiedType(falseType, writing);
60539                 }
60540             }
60541             return type;
60542         }
60543         /**
60544          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
60545          */
60546         function isIntersectionEmpty(type1, type2) {
60547             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
60548         }
60549         function substituteIndexedMappedType(objectType, index) {
60550             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
60551             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
60552             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
60553         }
60554         function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) {
60555             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
60556             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
60557         }
60558         function indexTypeLessThan(indexType, limit) {
60559             return everyType(indexType, function (t) {
60560                 if (t.flags & 384 /* StringOrNumberLiteral */) {
60561                     var propName = getPropertyNameFromType(t);
60562                     if (isNumericLiteralName(propName)) {
60563                         var index = +propName;
60564                         return index >= 0 && index < limit;
60565                     }
60566                 }
60567                 return false;
60568             });
60569         }
60570         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) {
60571             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
60572             if (objectType === wildcardType || indexType === wildcardType) {
60573                 return wildcardType;
60574             }
60575             // If the object type has a string index signature and no other members we know that the result will
60576             // always be the type of that index signature and we can simplify accordingly.
60577             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
60578                 indexType = stringType;
60579             }
60580             // In noUncheckedIndexedAccess mode, indexed access operations that occur in an expression in a read position and resolve to
60581             // an index signature have 'undefined' included in their type.
60582             if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */)
60583                 accessFlags |= 1 /* IncludeUndefined */;
60584             // If the index type is generic, or if the object type is generic and doesn't originate in an expression and
60585             // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing
60586             // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that
60587             // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
60588             // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
60589             // eagerly using the constraint type of 'this' at the given location.
60590             if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 193 /* IndexedAccessType */ ?
60591                 isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) :
60592                 isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) {
60593                 if (objectType.flags & 3 /* AnyOrUnknown */) {
60594                     return objectType;
60595                 }
60596                 // Defer the operation by creating an indexed access type.
60597                 var persistentAccessFlags = accessFlags & 1 /* Persistent */;
60598                 var id = objectType.id + "," + indexType.id + "," + persistentAccessFlags + getAliasId(aliasSymbol, aliasTypeArguments);
60599                 var type = indexedAccessTypes.get(id);
60600                 if (!type) {
60601                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, persistentAccessFlags, aliasSymbol, aliasTypeArguments));
60602                 }
60603                 return type;
60604             }
60605             // In the following we resolve T[K] to the type of the property in T selected by K.
60606             // We treat boolean as different from other unions to improve errors;
60607             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
60608             var apparentObjectType = getReducedApparentType(objectType);
60609             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
60610                 var propTypes = [];
60611                 var wasMissingProp = false;
60612                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
60613                     var t = _a[_i];
60614                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, accessNode, accessFlags | (wasMissingProp ? 128 /* SuppressNoImplicitAnyError */ : 0));
60615                     if (propType) {
60616                         propTypes.push(propType);
60617                     }
60618                     else if (!accessNode) {
60619                         // If there's no error node, we can immeditely stop, since error reporting is off
60620                         return undefined;
60621                     }
60622                     else {
60623                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
60624                         wasMissingProp = true;
60625                     }
60626                 }
60627                 if (wasMissingProp) {
60628                     return undefined;
60629                 }
60630                 return accessFlags & 4 /* Writing */
60631                     ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments)
60632                     : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
60633             }
60634             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* ReportDeprecated */);
60635         }
60636         function getTypeFromIndexedAccessTypeNode(node) {
60637             var links = getNodeLinks(node);
60638             if (!links.resolvedType) {
60639                 var objectType = getTypeFromTypeNode(node.objectType);
60640                 var indexType = getTypeFromTypeNode(node.indexType);
60641                 var potentialAlias = getAliasSymbolForTypeNode(node);
60642                 var resolved = getIndexedAccessType(objectType, indexType, 0 /* None */, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
60643                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
60644                     resolved.objectType === objectType &&
60645                     resolved.indexType === indexType ?
60646                     getConditionalFlowTypeOfType(resolved, node) : resolved;
60647             }
60648             return links.resolvedType;
60649         }
60650         function getTypeFromMappedTypeNode(node) {
60651             var links = getNodeLinks(node);
60652             if (!links.resolvedType) {
60653                 var type = createObjectType(32 /* Mapped */, node.symbol);
60654                 type.declaration = node;
60655                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
60656                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
60657                 links.resolvedType = type;
60658                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
60659                 // references itself through one or more type aliases.
60660                 getConstraintTypeFromMappedType(type);
60661             }
60662             return links.resolvedType;
60663         }
60664         function getActualTypeVariable(type) {
60665             if (type.flags & 33554432 /* Substitution */) {
60666                 return type.baseType;
60667             }
60668             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
60669                 type.indexType.flags & 33554432 /* Substitution */)) {
60670                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
60671             }
60672             return type;
60673         }
60674         function isTypicalNondistributiveConditional(root) {
60675             return !root.isDistributive && isSingletonTupleType(root.node.checkType) && isSingletonTupleType(root.node.extendsType);
60676         }
60677         function isSingletonTupleType(node) {
60678             return ts.isTupleTypeNode(node) && ts.length(node.elements) === 1 && !ts.isOptionalTypeNode(node.elements[0]) && !ts.isRestTypeNode(node.elements[0]);
60679         }
60680         /**
60681          * We syntactually check for common nondistributive conditional shapes and unwrap them into
60682          * the intended comparison - we do this so we can check if the unwrapped types are generic or
60683          * not and appropriately defer condition calculation
60684          */
60685         function unwrapNondistributiveConditionalTuple(root, type) {
60686             return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type;
60687         }
60688         function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) {
60689             var result;
60690             var extraTypes;
60691             var tailCount = 0;
60692             // We loop here for an immediately nested conditional type in the false position, effectively treating
60693             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
60694             // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of
60695             // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive
60696             // cases we increment the tail recursion counter and stop after 1000 iterations.
60697             while (true) {
60698                 if (tailCount === 1000) {
60699                     error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
60700                     result = errorType;
60701                     break;
60702                 }
60703                 var isUnwrapped = isTypicalNondistributiveConditional(root);
60704                 var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper);
60705                 var checkTypeInstantiable = isGenericType(checkType);
60706                 var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper);
60707                 if (checkType === wildcardType || extendsType === wildcardType) {
60708                     return wildcardType;
60709                 }
60710                 var combinedMapper = void 0;
60711                 if (root.inferTypeParameters) {
60712                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
60713                     if (!checkTypeInstantiable) {
60714                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
60715                         // conditional type instead of deferring resolution. Also, we always want strict function
60716                         // types rules (i.e. proper contravariance) for inferences.
60717                         inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */);
60718                     }
60719                     // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the
60720                     // those type parameters are used in type references (see getInferredTypeParameterConstraint). For
60721                     // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples.
60722                     combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper;
60723                 }
60724                 // Instantiate the extends type including inferences for 'infer T' type parameters
60725                 var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType;
60726                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
60727                 if (!checkTypeInstantiable && !isGenericType(inferredExtendsType)) {
60728                     // Return falseType for a definitely false extends check. We check an instantiations of the two
60729                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
60730                     // possible (the wildcard type is assignable to and from all types). If those are not related,
60731                     // then no instantiations will be and we can just return the false branch type.
60732                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
60733                         // Return union of trueType and falseType for 'any' since it matches anything
60734                         if (checkType.flags & 1 /* Any */ && !isUnwrapped) {
60735                             (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
60736                         }
60737                         // If falseType is an immediately nested conditional type that isn't distributive or has an
60738                         // identical checkType, switch to that type and loop.
60739                         var falseType_1 = getTypeFromTypeNode(root.node.falseType);
60740                         if (falseType_1.flags & 16777216 /* Conditional */) {
60741                             var newRoot = falseType_1.root;
60742                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
60743                                 root = newRoot;
60744                                 continue;
60745                             }
60746                             if (canTailRecurse(falseType_1, mapper)) {
60747                                 continue;
60748                             }
60749                         }
60750                         result = instantiateType(falseType_1, mapper);
60751                         break;
60752                     }
60753                     // Return trueType for a definitely true extends check. We check instantiations of the two
60754                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
60755                     // that has no constraint. This ensures that, for example, the type
60756                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
60757                     // doesn't immediately resolve to 'string' instead of being deferred.
60758                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
60759                         var trueType_1 = getTypeFromTypeNode(root.node.trueType);
60760                         var trueMapper = combinedMapper || mapper;
60761                         if (canTailRecurse(trueType_1, trueMapper)) {
60762                             continue;
60763                         }
60764                         result = instantiateType(trueType_1, trueMapper);
60765                         break;
60766                     }
60767                 }
60768                 // Return a deferred type for a check that is neither definitely true nor definitely false
60769                 result = createType(16777216 /* Conditional */);
60770                 result.root = root;
60771                 result.checkType = instantiateType(root.checkType, mapper);
60772                 result.extendsType = instantiateType(root.extendsType, mapper);
60773                 result.mapper = mapper;
60774                 result.combinedMapper = combinedMapper;
60775                 result.aliasSymbol = aliasSymbol || root.aliasSymbol;
60776                 result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
60777                 break;
60778             }
60779             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
60780             // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and
60781             // (b) are non distributive, have a check type that is unaffected by instantiation, or have a non-union check
60782             // type. Note that recursion is possible only through aliased conditional types, so we only increment the tail
60783             // recursion counter for those.
60784             function canTailRecurse(newType, newMapper) {
60785                 if (newType.flags & 16777216 /* Conditional */ && newMapper) {
60786                     var newRoot = newType.root;
60787                     if (newRoot.outerTypeParameters) {
60788                         var typeParamMapper_1 = combineTypeMappers(newType.mapper, newMapper);
60789                         var typeArguments = ts.map(newRoot.outerTypeParameters, function (t) { return getMappedType(t, typeParamMapper_1); });
60790                         var newRootMapper = createTypeMapper(newRoot.outerTypeParameters, typeArguments);
60791                         var newCheckType = newRoot.isDistributive ? getMappedType(newRoot.checkType, newRootMapper) : undefined;
60792                         if (!newCheckType || newCheckType === newRoot.checkType || !(newCheckType.flags & (1048576 /* Union */ | 131072 /* Never */))) {
60793                             root = newRoot;
60794                             mapper = newRootMapper;
60795                             aliasSymbol = undefined;
60796                             aliasTypeArguments = undefined;
60797                             if (newRoot.aliasSymbol) {
60798                                 tailCount++;
60799                             }
60800                             return true;
60801                         }
60802                     }
60803                 }
60804                 return false;
60805             }
60806         }
60807         function getTrueTypeFromConditionalType(type) {
60808             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper));
60809         }
60810         function getFalseTypeFromConditionalType(type) {
60811             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper));
60812         }
60813         function getInferredTrueTypeFromConditionalType(type) {
60814             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type));
60815         }
60816         function getInferTypeParameters(node) {
60817             var result;
60818             if (node.locals) {
60819                 node.locals.forEach(function (symbol) {
60820                     if (symbol.flags & 262144 /* TypeParameter */) {
60821                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
60822                     }
60823                 });
60824             }
60825             return result;
60826         }
60827         function isDistributionDependent(root) {
60828             return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) ||
60829                 isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType));
60830         }
60831         function getTypeFromConditionalTypeNode(node) {
60832             var links = getNodeLinks(node);
60833             if (!links.resolvedType) {
60834                 var checkType = getTypeFromTypeNode(node.checkType);
60835                 var aliasSymbol = getAliasSymbolForTypeNode(node);
60836                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
60837                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
60838                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
60839                 var root = {
60840                     node: node,
60841                     checkType: checkType,
60842                     extendsType: getTypeFromTypeNode(node.extendsType),
60843                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
60844                     inferTypeParameters: getInferTypeParameters(node),
60845                     outerTypeParameters: outerTypeParameters,
60846                     instantiations: undefined,
60847                     aliasSymbol: aliasSymbol,
60848                     aliasTypeArguments: aliasTypeArguments
60849                 };
60850                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
60851                 if (outerTypeParameters) {
60852                     root.instantiations = new ts.Map();
60853                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
60854                 }
60855             }
60856             return links.resolvedType;
60857         }
60858         function getTypeFromInferTypeNode(node) {
60859             var links = getNodeLinks(node);
60860             if (!links.resolvedType) {
60861                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
60862             }
60863             return links.resolvedType;
60864         }
60865         function getIdentifierChain(node) {
60866             if (ts.isIdentifier(node)) {
60867                 return [node];
60868             }
60869             else {
60870                 return ts.append(getIdentifierChain(node.left), node.right);
60871             }
60872         }
60873         function getTypeFromImportTypeNode(node) {
60874             var links = getNodeLinks(node);
60875             if (!links.resolvedType) {
60876                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
60877                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
60878                     links.resolvedSymbol = unknownSymbol;
60879                     return links.resolvedType = errorType;
60880                 }
60881                 if (!ts.isLiteralImportTypeNode(node)) {
60882                     error(node.argument, ts.Diagnostics.String_literal_expected);
60883                     links.resolvedSymbol = unknownSymbol;
60884                     return links.resolvedType = errorType;
60885                 }
60886                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
60887                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
60888                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
60889                 if (!innerModuleSymbol) {
60890                     links.resolvedSymbol = unknownSymbol;
60891                     return links.resolvedType = errorType;
60892                 }
60893                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
60894                 if (!ts.nodeIsMissing(node.qualifier)) {
60895                     var nameStack = getIdentifierChain(node.qualifier);
60896                     var currentNamespace = moduleSymbol;
60897                     var current = void 0;
60898                     while (current = nameStack.shift()) {
60899                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
60900                         // typeof a.b.c is normally resolved using `checkExpression` which in turn defers to `checkQualifiedName`
60901                         // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from
60902                         // the `exports` lookup process that only looks up namespace members which is used for most type references
60903                         var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace));
60904                         var next = node.isTypeOf
60905                             ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText)
60906                             : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
60907                         if (!next) {
60908                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
60909                             return links.resolvedType = errorType;
60910                         }
60911                         getNodeLinks(current).resolvedSymbol = next;
60912                         getNodeLinks(current.parent).resolvedSymbol = next;
60913                         currentNamespace = next;
60914                     }
60915                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
60916                 }
60917                 else {
60918                     if (moduleSymbol.flags & targetMeaning) {
60919                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
60920                     }
60921                     else {
60922                         var errorMessage = targetMeaning === 111551 /* Value */
60923                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
60924                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
60925                         error(node, errorMessage, node.argument.literal.text);
60926                         links.resolvedSymbol = unknownSymbol;
60927                         links.resolvedType = errorType;
60928                     }
60929                 }
60930             }
60931             return links.resolvedType;
60932         }
60933         function resolveImportSymbolType(node, links, symbol, meaning) {
60934             var resolvedSymbol = resolveSymbol(symbol);
60935             links.resolvedSymbol = resolvedSymbol;
60936             if (meaning === 111551 /* Value */) {
60937                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
60938             }
60939             else {
60940                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
60941             }
60942         }
60943         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
60944             var links = getNodeLinks(node);
60945             if (!links.resolvedType) {
60946                 // Deferred resolution of members is handled by resolveObjectTypeMembers
60947                 var aliasSymbol = getAliasSymbolForTypeNode(node);
60948                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
60949                     links.resolvedType = emptyTypeLiteralType;
60950                 }
60951                 else {
60952                     var type = createObjectType(16 /* Anonymous */, node.symbol);
60953                     type.aliasSymbol = aliasSymbol;
60954                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
60955                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
60956                         type = createArrayType(type);
60957                     }
60958                     links.resolvedType = type;
60959                 }
60960             }
60961             return links.resolvedType;
60962         }
60963         function getAliasSymbolForTypeNode(node) {
60964             var host = node.parent;
60965             while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 144 /* ReadonlyKeyword */) {
60966                 host = host.parent;
60967             }
60968             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
60969         }
60970         function getTypeArgumentsForAliasSymbol(symbol) {
60971             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
60972         }
60973         function isNonGenericObjectType(type) {
60974             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
60975         }
60976         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
60977             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
60978         }
60979         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
60980             if (!(type.flags & 1048576 /* Union */)) {
60981                 return type;
60982             }
60983             if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
60984                 return ts.find(type.types, isEmptyObjectType) || emptyObjectType;
60985             }
60986             var firstType = ts.find(type.types, function (t) { return !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
60987             if (!firstType) {
60988                 return type;
60989             }
60990             var secondType = ts.find(type.types, function (t) { return t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
60991             if (secondType) {
60992                 return type;
60993             }
60994             return getAnonymousPartialType(firstType);
60995             function getAnonymousPartialType(type) {
60996                 // gets the type as if it had been spread, but where everything in the spread is made optional
60997                 var members = ts.createSymbolTable();
60998                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
60999                     var prop = _a[_i];
61000                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
61001                         // do nothing, skip privates
61002                     }
61003                     else if (isSpreadableProperty(prop)) {
61004                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
61005                         var flags = 4 /* Property */ | 16777216 /* Optional */;
61006                         var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
61007                         result.type = isSetonlyAccessor ? undefinedType : addOptionality(getTypeOfSymbol(prop), /*isProperty*/ true);
61008                         result.declarations = prop.declarations;
61009                         result.nameType = getSymbolLinks(prop).nameType;
61010                         result.syntheticOrigin = prop;
61011                         members.set(prop.escapedName, result);
61012                     }
61013                 }
61014                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfosOfType(type));
61015                 spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */;
61016                 return spread;
61017             }
61018         }
61019         /**
61020          * Since the source of spread types are object literals, which are not binary,
61021          * this function should be called in a left folding style, with left = previous result of getSpreadType
61022          * and right = the new element to be spread.
61023          */
61024         function getSpreadType(left, right, symbol, objectFlags, readonly) {
61025             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
61026                 return anyType;
61027             }
61028             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
61029                 return unknownType;
61030             }
61031             if (left.flags & 131072 /* Never */) {
61032                 return right;
61033             }
61034             if (right.flags & 131072 /* Never */) {
61035                 return left;
61036             }
61037             left = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
61038             if (left.flags & 1048576 /* Union */) {
61039                 return checkCrossProductUnion([left, right])
61040                     ? mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); })
61041                     : errorType;
61042             }
61043             right = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
61044             if (right.flags & 1048576 /* Union */) {
61045                 return checkCrossProductUnion([left, right])
61046                     ? mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); })
61047                     : errorType;
61048             }
61049             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
61050                 return left;
61051             }
61052             if (isGenericObjectType(left) || isGenericObjectType(right)) {
61053                 if (isEmptyObjectType(left)) {
61054                     return right;
61055                 }
61056                 // When the left type is an intersection, we may need to merge the last constituent of the
61057                 // intersection with the right type. For example when the left type is 'T & { a: string }'
61058                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
61059                 if (left.flags & 2097152 /* Intersection */) {
61060                     var types = left.types;
61061                     var lastLeft = types[types.length - 1];
61062                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
61063                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
61064                     }
61065                 }
61066                 return getIntersectionType([left, right]);
61067             }
61068             var members = ts.createSymbolTable();
61069             var skippedPrivateMembers = new ts.Set();
61070             var indexInfos = left === emptyObjectType ? getIndexInfosOfType(right) : getUnionIndexInfos([left, right]);
61071             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
61072                 var rightProp = _a[_i];
61073                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
61074                     skippedPrivateMembers.add(rightProp.escapedName);
61075                 }
61076                 else if (isSpreadableProperty(rightProp)) {
61077                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
61078                 }
61079             }
61080             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
61081                 var leftProp = _c[_b];
61082                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
61083                     continue;
61084                 }
61085                 if (members.has(leftProp.escapedName)) {
61086                     var rightProp = members.get(leftProp.escapedName);
61087                     var rightType = getTypeOfSymbol(rightProp);
61088                     if (rightProp.flags & 16777216 /* Optional */) {
61089                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
61090                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
61091                         var result = createSymbol(flags, leftProp.escapedName);
61092                         result.type = getUnionType([getTypeOfSymbol(leftProp), removeMissingOrUndefinedType(rightType)]);
61093                         result.leftSpread = leftProp;
61094                         result.rightSpread = rightProp;
61095                         result.declarations = declarations;
61096                         result.nameType = getSymbolLinks(leftProp).nameType;
61097                         members.set(leftProp.escapedName, result);
61098                     }
61099                 }
61100                 else {
61101                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
61102                 }
61103             }
61104             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, ts.sameMap(indexInfos, function (info) { return getIndexInfoWithReadonly(info, readonly); }));
61105             spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags;
61106             return spread;
61107         }
61108         /** We approximate own properties as non-methods plus methods that are inside the object literal */
61109         function isSpreadableProperty(prop) {
61110             var _a;
61111             return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) &&
61112                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
61113                     !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); })));
61114         }
61115         function getSpreadSymbol(prop, readonly) {
61116             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
61117             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
61118                 return prop;
61119             }
61120             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
61121             var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
61122             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
61123             result.declarations = prop.declarations;
61124             result.nameType = getSymbolLinks(prop).nameType;
61125             result.syntheticOrigin = prop;
61126             return result;
61127         }
61128         function getIndexInfoWithReadonly(info, readonly) {
61129             return info.isReadonly !== readonly ? createIndexInfo(info.keyType, info.type, readonly, info.declaration) : info;
61130         }
61131         function createLiteralType(flags, value, symbol, regularType) {
61132             var type = createType(flags);
61133             type.symbol = symbol;
61134             type.value = value;
61135             type.regularType = regularType || type;
61136             return type;
61137         }
61138         function getFreshTypeOfLiteralType(type) {
61139             if (type.flags & 2944 /* Literal */) {
61140                 if (!type.freshType) {
61141                     var freshType = createLiteralType(type.flags, type.value, type.symbol, type);
61142                     freshType.freshType = freshType;
61143                     type.freshType = freshType;
61144                 }
61145                 return type.freshType;
61146             }
61147             return type;
61148         }
61149         function getRegularTypeOfLiteralType(type) {
61150             return type.flags & 2944 /* Literal */ ? type.regularType :
61151                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) :
61152                     type;
61153         }
61154         function isFreshLiteralType(type) {
61155             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
61156         }
61157         function getStringLiteralType(value) {
61158             var type;
61159             return stringLiteralTypes.get(value) ||
61160                 (stringLiteralTypes.set(value, type = createLiteralType(128 /* StringLiteral */, value)), type);
61161         }
61162         function getNumberLiteralType(value) {
61163             var type;
61164             return numberLiteralTypes.get(value) ||
61165                 (numberLiteralTypes.set(value, type = createLiteralType(256 /* NumberLiteral */, value)), type);
61166         }
61167         function getBigIntLiteralType(value) {
61168             var type;
61169             var key = ts.pseudoBigIntToString(value);
61170             return bigIntLiteralTypes.get(key) ||
61171                 (bigIntLiteralTypes.set(key, type = createLiteralType(2048 /* BigIntLiteral */, value)), type);
61172         }
61173         function getEnumLiteralType(value, enumId, symbol) {
61174             var type;
61175             var qualifier = typeof value === "string" ? "@" : "#";
61176             var key = enumId + qualifier + value;
61177             var flags = 1024 /* EnumLiteral */ | (typeof value === "string" ? 128 /* StringLiteral */ : 256 /* NumberLiteral */);
61178             return enumLiteralTypes.get(key) ||
61179                 (enumLiteralTypes.set(key, type = createLiteralType(flags, value, symbol)), type);
61180         }
61181         function getTypeFromLiteralTypeNode(node) {
61182             if (node.literal.kind === 104 /* NullKeyword */) {
61183                 return nullType;
61184             }
61185             var links = getNodeLinks(node);
61186             if (!links.resolvedType) {
61187                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
61188             }
61189             return links.resolvedType;
61190         }
61191         function createUniqueESSymbolType(symbol) {
61192             var type = createType(8192 /* UniqueESSymbol */);
61193             type.symbol = symbol;
61194             type.escapedName = "__@".concat(type.symbol.escapedName, "@").concat(getSymbolId(type.symbol));
61195             return type;
61196         }
61197         function getESSymbolLikeTypeForNode(node) {
61198             if (ts.isValidESSymbolDeclaration(node)) {
61199                 var symbol = getSymbolOfNode(node);
61200                 var links = getSymbolLinks(symbol);
61201                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
61202             }
61203             return esSymbolType;
61204         }
61205         function getThisType(node) {
61206             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
61207             var parent = container && container.parent;
61208             if (parent && (ts.isClassLike(parent) || parent.kind === 257 /* InterfaceDeclaration */)) {
61209                 if (!ts.isStatic(container) &&
61210                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
61211                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
61212                 }
61213             }
61214             // inside x.prototype = { ... }
61215             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
61216                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
61217             }
61218             // /** @return {this} */
61219             // x.prototype.m = function() { ... }
61220             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
61221             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
61222                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
61223             }
61224             // inside constructor function C() { ... }
61225             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
61226                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
61227             }
61228             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
61229             return errorType;
61230         }
61231         function getTypeFromThisTypeNode(node) {
61232             var links = getNodeLinks(node);
61233             if (!links.resolvedType) {
61234                 links.resolvedType = getThisType(node);
61235             }
61236             return links.resolvedType;
61237         }
61238         function getTypeFromRestTypeNode(node) {
61239             return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
61240         }
61241         function getArrayElementTypeNode(node) {
61242             switch (node.kind) {
61243                 case 190 /* ParenthesizedType */:
61244                     return getArrayElementTypeNode(node.type);
61245                 case 183 /* TupleType */:
61246                     if (node.elements.length === 1) {
61247                         node = node.elements[0];
61248                         if (node.kind === 185 /* RestType */ || node.kind === 196 /* NamedTupleMember */ && node.dotDotDotToken) {
61249                             return getArrayElementTypeNode(node.type);
61250                         }
61251                     }
61252                     break;
61253                 case 182 /* ArrayType */:
61254                     return node.elementType;
61255             }
61256             return undefined;
61257         }
61258         function getTypeFromNamedTupleTypeNode(node) {
61259             var links = getNodeLinks(node);
61260             return links.resolvedType || (links.resolvedType =
61261                 node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
61262                     addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true, !!node.questionToken));
61263         }
61264         function getTypeFromTypeNode(node) {
61265             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
61266         }
61267         function getTypeFromTypeNodeWorker(node) {
61268             switch (node.kind) {
61269                 case 130 /* AnyKeyword */:
61270                 case 310 /* JSDocAllType */:
61271                 case 311 /* JSDocUnknownType */:
61272                     return anyType;
61273                 case 154 /* UnknownKeyword */:
61274                     return unknownType;
61275                 case 149 /* StringKeyword */:
61276                     return stringType;
61277                 case 146 /* NumberKeyword */:
61278                     return numberType;
61279                 case 157 /* BigIntKeyword */:
61280                     return bigintType;
61281                 case 133 /* BooleanKeyword */:
61282                     return booleanType;
61283                 case 150 /* SymbolKeyword */:
61284                     return esSymbolType;
61285                 case 114 /* VoidKeyword */:
61286                     return voidType;
61287                 case 152 /* UndefinedKeyword */:
61288                     return undefinedType;
61289                 case 104 /* NullKeyword */:
61290                     // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service.
61291                     return nullType;
61292                 case 143 /* NeverKeyword */:
61293                     return neverType;
61294                 case 147 /* ObjectKeyword */:
61295                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
61296                 case 138 /* IntrinsicKeyword */:
61297                     return intrinsicMarkerType;
61298                 case 191 /* ThisType */:
61299                 case 108 /* ThisKeyword */:
61300                     // 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`.
61301                     return getTypeFromThisTypeNode(node);
61302                 case 195 /* LiteralType */:
61303                     return getTypeFromLiteralTypeNode(node);
61304                 case 177 /* TypeReference */:
61305                     return getTypeFromTypeReference(node);
61306                 case 176 /* TypePredicate */:
61307                     return node.assertsModifier ? voidType : booleanType;
61308                 case 227 /* ExpressionWithTypeArguments */:
61309                     return getTypeFromTypeReference(node);
61310                 case 180 /* TypeQuery */:
61311                     return getTypeFromTypeQueryNode(node);
61312                 case 182 /* ArrayType */:
61313                 case 183 /* TupleType */:
61314                     return getTypeFromArrayOrTupleTypeNode(node);
61315                 case 184 /* OptionalType */:
61316                     return getTypeFromOptionalTypeNode(node);
61317                 case 186 /* UnionType */:
61318                     return getTypeFromUnionTypeNode(node);
61319                 case 187 /* IntersectionType */:
61320                     return getTypeFromIntersectionTypeNode(node);
61321                 case 312 /* JSDocNullableType */:
61322                     return getTypeFromJSDocNullableTypeNode(node);
61323                 case 314 /* JSDocOptionalType */:
61324                     return addOptionality(getTypeFromTypeNode(node.type));
61325                 case 196 /* NamedTupleMember */:
61326                     return getTypeFromNamedTupleTypeNode(node);
61327                 case 190 /* ParenthesizedType */:
61328                 case 313 /* JSDocNonNullableType */:
61329                 case 307 /* JSDocTypeExpression */:
61330                     return getTypeFromTypeNode(node.type);
61331                 case 185 /* RestType */:
61332                     return getTypeFromRestTypeNode(node);
61333                 case 316 /* JSDocVariadicType */:
61334                     return getTypeFromJSDocVariadicType(node);
61335                 case 178 /* FunctionType */:
61336                 case 179 /* ConstructorType */:
61337                 case 181 /* TypeLiteral */:
61338                 case 320 /* JSDocTypeLiteral */:
61339                 case 315 /* JSDocFunctionType */:
61340                 case 321 /* JSDocSignature */:
61341                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
61342                 case 192 /* TypeOperator */:
61343                     return getTypeFromTypeOperatorNode(node);
61344                 case 193 /* IndexedAccessType */:
61345                     return getTypeFromIndexedAccessTypeNode(node);
61346                 case 194 /* MappedType */:
61347                     return getTypeFromMappedTypeNode(node);
61348                 case 188 /* ConditionalType */:
61349                     return getTypeFromConditionalTypeNode(node);
61350                 case 189 /* InferType */:
61351                     return getTypeFromInferTypeNode(node);
61352                 case 197 /* TemplateLiteralType */:
61353                     return getTypeFromTemplateTypeNode(node);
61354                 case 199 /* ImportType */:
61355                     return getTypeFromImportTypeNode(node);
61356                 // This function assumes that an identifier, qualified name, or property access expression is a type expression
61357                 // Callers should first ensure this by calling `isPartOfTypeNode`
61358                 // 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.
61359                 case 79 /* Identifier */:
61360                 case 160 /* QualifiedName */:
61361                 case 205 /* PropertyAccessExpression */:
61362                     var symbol = getSymbolAtLocation(node);
61363                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
61364                 default:
61365                     return errorType;
61366             }
61367         }
61368         function instantiateList(items, mapper, instantiator) {
61369             if (items && items.length) {
61370                 for (var i = 0; i < items.length; i++) {
61371                     var item = items[i];
61372                     var mapped = instantiator(item, mapper);
61373                     if (item !== mapped) {
61374                         var result = i === 0 ? [] : items.slice(0, i);
61375                         result.push(mapped);
61376                         for (i++; i < items.length; i++) {
61377                             result.push(instantiator(items[i], mapper));
61378                         }
61379                         return result;
61380                     }
61381                 }
61382             }
61383             return items;
61384         }
61385         function instantiateTypes(types, mapper) {
61386             return instantiateList(types, mapper, instantiateType);
61387         }
61388         function instantiateSignatures(signatures, mapper) {
61389             return instantiateList(signatures, mapper, instantiateSignature);
61390         }
61391         function instantiateIndexInfos(indexInfos, mapper) {
61392             return instantiateList(indexInfos, mapper, instantiateIndexInfo);
61393         }
61394         function createTypeMapper(sources, targets) {
61395             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
61396         }
61397         function getMappedType(type, mapper) {
61398             switch (mapper.kind) {
61399                 case 0 /* Simple */:
61400                     return type === mapper.source ? mapper.target : type;
61401                 case 1 /* Array */:
61402                     var sources = mapper.sources;
61403                     var targets = mapper.targets;
61404                     for (var i = 0; i < sources.length; i++) {
61405                         if (type === sources[i]) {
61406                             return targets ? targets[i] : anyType;
61407                         }
61408                     }
61409                     return type;
61410                 case 2 /* Function */:
61411                     return mapper.func(type);
61412                 case 3 /* Composite */:
61413                 case 4 /* Merged */:
61414                     var t1 = getMappedType(type, mapper.mapper1);
61415                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
61416             }
61417         }
61418         function makeUnaryTypeMapper(source, target) {
61419             return { kind: 0 /* Simple */, source: source, target: target };
61420         }
61421         function makeArrayTypeMapper(sources, targets) {
61422             return { kind: 1 /* Array */, sources: sources, targets: targets };
61423         }
61424         function makeFunctionTypeMapper(func) {
61425             return { kind: 2 /* Function */, func: func };
61426         }
61427         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
61428             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
61429         }
61430         function createTypeEraser(sources) {
61431             return createTypeMapper(sources, /*targets*/ undefined);
61432         }
61433         /**
61434          * Maps forward-references to later types parameters to the empty object type.
61435          * This is used during inference when instantiating type parameter defaults.
61436          */
61437         function createBackreferenceMapper(context, index) {
61438             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
61439         }
61440         function combineTypeMappers(mapper1, mapper2) {
61441             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
61442         }
61443         function mergeTypeMappers(mapper1, mapper2) {
61444             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
61445         }
61446         function prependTypeMapping(source, target, mapper) {
61447             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
61448         }
61449         function appendTypeMapping(mapper, source, target) {
61450             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
61451         }
61452         function getRestrictiveTypeParameter(tp) {
61453             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
61454                 tp.restrictiveInstantiation.constraint = unknownType,
61455                 tp.restrictiveInstantiation);
61456         }
61457         function cloneTypeParameter(typeParameter) {
61458             var result = createTypeParameter(typeParameter.symbol);
61459             result.target = typeParameter;
61460             return result;
61461         }
61462         function instantiateTypePredicate(predicate, mapper) {
61463             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
61464         }
61465         function instantiateSignature(signature, mapper, eraseTypeParameters) {
61466             var freshTypeParameters;
61467             if (signature.typeParameters && !eraseTypeParameters) {
61468                 // First create a fresh set of type parameters, then include a mapping from the old to the
61469                 // new type parameters in the mapper function. Finally store this mapper in the new type
61470                 // parameters such that we can use it when instantiating constraints.
61471                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
61472                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
61473                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
61474                     var tp = freshTypeParameters_1[_i];
61475                     tp.mapper = mapper;
61476                 }
61477             }
61478             // Don't compute resolvedReturnType and resolvedTypePredicate now,
61479             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
61480             // See GH#17600.
61481             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
61482             /*resolvedReturnType*/ undefined, 
61483             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 39 /* PropagatingFlags */);
61484             result.target = signature;
61485             result.mapper = mapper;
61486             return result;
61487         }
61488         function instantiateSymbol(symbol, mapper) {
61489             var links = getSymbolLinks(symbol);
61490             if (links.type && !couldContainTypeVariables(links.type)) {
61491                 // If the type of the symbol is already resolved, and if that type could not possibly
61492                 // be affected by instantiation, simply return the symbol itself.
61493                 return symbol;
61494             }
61495             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
61496                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
61497                 // type mappers. This ensures that original type identities are properly preserved and that aliases
61498                 // always reference a non-aliases.
61499                 symbol = links.target;
61500                 mapper = combineTypeMappers(links.mapper, mapper);
61501             }
61502             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
61503             // also transient so that we can just store data on it directly.
61504             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
61505             result.declarations = symbol.declarations;
61506             result.parent = symbol.parent;
61507             result.target = symbol;
61508             result.mapper = mapper;
61509             if (symbol.valueDeclaration) {
61510                 result.valueDeclaration = symbol.valueDeclaration;
61511             }
61512             if (links.nameType) {
61513                 result.nameType = links.nameType;
61514             }
61515             return result;
61516         }
61517         function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
61518             var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
61519             var links = getNodeLinks(declaration);
61520             var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType :
61521                 type.objectFlags & 64 /* Instantiated */ ? type.target : type;
61522             var typeParameters = links.outerTypeParameters;
61523             if (!typeParameters) {
61524                 // The first time an anonymous type is instantiated we compute and store a list of the type
61525                 // parameters that are in scope (and therefore potentially referenced). For type literals that
61526                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
61527                 // set of type parameters to those that are possibly referenced in the literal.
61528                 var outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true);
61529                 if (isJSConstructor(declaration)) {
61530                     var templateTagParameters = getTypeParametersFromDeclaration(declaration);
61531                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
61532                 }
61533                 typeParameters = outerTypeParameters || ts.emptyArray;
61534                 var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations;
61535                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
61536                     ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) :
61537                     typeParameters;
61538                 links.outerTypeParameters = typeParameters;
61539             }
61540             if (typeParameters.length) {
61541                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
61542                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
61543                 // instantiation cache key from the type IDs of the type arguments.
61544                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
61545                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
61546                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
61547                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
61548                 var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments);
61549                 if (!target.instantiations) {
61550                     target.instantiations = new ts.Map();
61551                     target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target);
61552                 }
61553                 var result = target.instantiations.get(id);
61554                 if (!result) {
61555                     var newMapper = createTypeMapper(typeParameters, typeArguments);
61556                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) :
61557                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) :
61558                             instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments);
61559                     target.instantiations.set(id, result);
61560                 }
61561                 return result;
61562             }
61563             return type;
61564         }
61565         function maybeTypeParameterReference(node) {
61566             return !(node.parent.kind === 177 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
61567                 node.parent.kind === 199 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
61568         }
61569         function isTypeParameterPossiblyReferenced(tp, node) {
61570             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
61571             // between the node and the type parameter declaration, if the node contains actual references to the
61572             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
61573             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
61574                 var container = tp.symbol.declarations[0].parent;
61575                 for (var n = node; n !== container; n = n.parent) {
61576                     if (!n || n.kind === 234 /* Block */ || n.kind === 188 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
61577                         return true;
61578                     }
61579                 }
61580                 return containsReference(node);
61581             }
61582             return true;
61583             function containsReference(node) {
61584                 switch (node.kind) {
61585                     case 191 /* ThisType */:
61586                         return !!tp.isThisType;
61587                     case 79 /* Identifier */:
61588                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
61589                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
61590                     case 180 /* TypeQuery */:
61591                         return true;
61592                     case 168 /* MethodDeclaration */:
61593                     case 167 /* MethodSignature */:
61594                         return !node.type && !!node.body ||
61595                             ts.some(node.typeParameters, containsReference) ||
61596                             ts.some(node.parameters, containsReference) ||
61597                             !!node.type && containsReference(node.type);
61598                 }
61599                 return !!ts.forEachChild(node, containsReference);
61600             }
61601         }
61602         function getHomomorphicTypeVariable(type) {
61603             var constraintType = getConstraintTypeFromMappedType(type);
61604             if (constraintType.flags & 4194304 /* Index */) {
61605                 var typeVariable = getActualTypeVariable(constraintType.type);
61606                 if (typeVariable.flags & 262144 /* TypeParameter */) {
61607                     return typeVariable;
61608                 }
61609             }
61610             return undefined;
61611         }
61612         function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) {
61613             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
61614             // operation depends on T as follows:
61615             // * If T is a primitive type no mapping is performed and the result is simply T.
61616             // * If T is a union type we distribute the mapped type over the union.
61617             // * If T is an array we map to an array where the element type has been transformed.
61618             // * If T is a tuple we map to a tuple where the element types have been transformed.
61619             // * Otherwise we map to an object type where the type of each property has been transformed.
61620             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
61621             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
61622             // { [P in keyof A]: X } | undefined.
61623             var typeVariable = getHomomorphicTypeVariable(type);
61624             if (typeVariable) {
61625                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
61626                 if (typeVariable !== mappedTypeVariable) {
61627                     return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) {
61628                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) {
61629                             if (!type.declaration.nameType) {
61630                                 var constraint = void 0;
61631                                 if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 &&
61632                                     (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) {
61633                                     return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper));
61634                                 }
61635                                 if (isGenericTupleType(t)) {
61636                                     return instantiateMappedGenericTupleType(t, type, typeVariable, mapper);
61637                                 }
61638                                 if (isTupleType(t)) {
61639                                     return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper));
61640                                 }
61641                             }
61642                             return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
61643                         }
61644                         return t;
61645                     }, aliasSymbol, aliasTypeArguments);
61646                 }
61647             }
61648             // If the constraint type of the instantiation is the wildcard type, return the wildcard type.
61649             return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments);
61650         }
61651         function getModifiedReadonlyState(state, modifiers) {
61652             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
61653         }
61654         function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) {
61655             // When a tuple type is generic (i.e. when it contains variadic elements), we want to eagerly map the
61656             // non-generic elements and defer mapping the generic elements. In order to facilitate this, we transform
61657             // M<[A, B?, ...T, ...C[]] into [...M<[A]>, ...M<[B?]>, ...M<T>, ...M<C[]>] and then rely on tuple type
61658             // normalization to resolve the non-generic parts of the resulting tuple.
61659             var elementFlags = tupleType.target.elementFlags;
61660             var elementTypes = ts.map(getTypeArguments(tupleType), function (t, i) {
61661                 var singleton = elementFlags[i] & 8 /* Variadic */ ? t :
61662                     elementFlags[i] & 4 /* Rest */ ? createArrayType(t) :
61663                         createTupleType([t], [elementFlags[i]]);
61664                 // The singleton is never a generic tuple type, so it is safe to recurse here.
61665                 return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper));
61666             });
61667             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
61668             return createTupleType(elementTypes, ts.map(elementTypes, function (_) { return 8 /* Variadic */; }), newReadonly);
61669         }
61670         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
61671             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
61672             return isErrorType(elementType) ? errorType :
61673                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
61674         }
61675         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
61676             var elementFlags = tupleType.target.elementFlags;
61677             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
61678                 return instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper);
61679             });
61680             var modifiers = getMappedTypeModifiers(mappedType);
61681             var newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? 2 /* Optional */ : f; }) :
61682                 modifiers & 8 /* ExcludeOptional */ ? ts.map(elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
61683                     elementFlags;
61684             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
61685             return ts.contains(elementTypes, errorType) ? errorType :
61686                 createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations);
61687         }
61688         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
61689             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
61690             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
61691             var modifiers = getMappedTypeModifiers(type);
61692             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType, /*isProperty*/ true) :
61693                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
61694                     propType;
61695         }
61696         function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) {
61697             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
61698             if (type.objectFlags & 32 /* Mapped */) {
61699                 result.declaration = type.declaration;
61700                 // C.f. instantiateSignature
61701                 var origTypeParameter = getTypeParameterFromMappedType(type);
61702                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
61703                 result.typeParameter = freshTypeParameter;
61704                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
61705                 freshTypeParameter.mapper = mapper;
61706             }
61707             result.target = type;
61708             result.mapper = mapper;
61709             result.aliasSymbol = aliasSymbol || type.aliasSymbol;
61710             result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
61711             return result;
61712         }
61713         function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
61714             var root = type.root;
61715             if (root.outerTypeParameters) {
61716                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
61717                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
61718                 // instantiation cache key from the type IDs of the type arguments.
61719                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
61720                 var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
61721                 var result = root.instantiations.get(id);
61722                 if (!result) {
61723                     var newMapper_1 = createTypeMapper(root.outerTypeParameters, typeArguments);
61724                     var checkType_1 = root.checkType;
61725                     var distributionType = root.isDistributive ? getMappedType(checkType_1, newMapper_1) : undefined;
61726                     // Distributive conditional types are distributed over union types. For example, when the
61727                     // distributive conditional type T extends U ? X : Y is instantiated with A | B for T, the
61728                     // result is (A extends U ? X : Y) | (B extends U ? X : Y).
61729                     result = distributionType && checkType_1 !== distributionType && distributionType.flags & (1048576 /* Union */ | 131072 /* Never */) ?
61730                         mapTypeWithAlias(distributionType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, newMapper_1)); }, aliasSymbol, aliasTypeArguments) :
61731                         getConditionalType(root, newMapper_1, aliasSymbol, aliasTypeArguments);
61732                     root.instantiations.set(id, result);
61733                 }
61734                 return result;
61735             }
61736             return type;
61737         }
61738         function instantiateType(type, mapper) {
61739             return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type;
61740         }
61741         function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
61742             if (!couldContainTypeVariables(type)) {
61743                 return type;
61744             }
61745             if (instantiationDepth === 100 || instantiationCount >= 5000000) {
61746                 // We have reached 100 recursive type instantiations, or 5M type instantiations caused by the same statement
61747                 // or expression. There is a very high likelyhood we're dealing with a combination of infinite generic types
61748                 // that perpetually generate new type identities, so we stop the recursion here by yielding the error type.
61749                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
61750                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
61751                 return errorType;
61752             }
61753             totalInstantiationCount++;
61754             instantiationCount++;
61755             instantiationDepth++;
61756             var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments);
61757             instantiationDepth--;
61758             return result;
61759         }
61760         function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) {
61761             var flags = type.flags;
61762             if (flags & 262144 /* TypeParameter */) {
61763                 return getMappedType(type, mapper);
61764             }
61765             if (flags & 524288 /* Object */) {
61766                 var objectFlags = type.objectFlags;
61767                 if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
61768                     if (objectFlags & 4 /* Reference */ && !type.node) {
61769                         var resolvedTypeArguments = type.resolvedTypeArguments;
61770                         var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
61771                         return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
61772                     }
61773                     if (objectFlags & 1024 /* ReverseMapped */) {
61774                         return instantiateReverseMappedType(type, mapper);
61775                     }
61776                     return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments);
61777                 }
61778                 return type;
61779             }
61780             if (flags & 3145728 /* UnionOrIntersection */) {
61781                 var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined;
61782                 var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types;
61783                 var newTypes = instantiateTypes(types, mapper);
61784                 if (newTypes === types && aliasSymbol === type.aliasSymbol) {
61785                     return type;
61786                 }
61787                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
61788                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
61789                 return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ?
61790                     getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) :
61791                     getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments);
61792             }
61793             if (flags & 4194304 /* Index */) {
61794                 return getIndexType(instantiateType(type.type, mapper));
61795             }
61796             if (flags & 134217728 /* TemplateLiteral */) {
61797                 return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
61798             }
61799             if (flags & 268435456 /* StringMapping */) {
61800                 return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
61801             }
61802             if (flags & 8388608 /* IndexedAccess */) {
61803                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
61804                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
61805                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.accessFlags, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments);
61806             }
61807             if (flags & 16777216 /* Conditional */) {
61808                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments);
61809             }
61810             if (flags & 33554432 /* Substitution */) {
61811                 var maybeVariable = instantiateType(type.baseType, mapper);
61812                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
61813                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
61814                 }
61815                 else {
61816                     var sub = instantiateType(type.substitute, mapper);
61817                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
61818                         return maybeVariable;
61819                     }
61820                     return sub;
61821                 }
61822             }
61823             return type;
61824         }
61825         function instantiateReverseMappedType(type, mapper) {
61826             var innerMappedType = instantiateType(type.mappedType, mapper);
61827             if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) {
61828                 return type;
61829             }
61830             var innerIndexType = instantiateType(type.constraintType, mapper);
61831             if (!(innerIndexType.flags & 4194304 /* Index */)) {
61832                 return type;
61833             }
61834             var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType);
61835             if (instantiated) {
61836                 return instantiated;
61837             }
61838             return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable
61839         }
61840         function getPermissiveInstantiation(type) {
61841             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
61842                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
61843         }
61844         function getRestrictiveInstantiation(type) {
61845             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
61846                 return type;
61847             }
61848             if (type.restrictiveInstantiation) {
61849                 return type.restrictiveInstantiation;
61850             }
61851             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
61852             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
61853             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
61854             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
61855             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
61856             // are constrained to `unknown` and produce tons of false positives/negatives!
61857             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
61858             return type.restrictiveInstantiation;
61859         }
61860         function instantiateIndexInfo(info, mapper) {
61861             return createIndexInfo(info.keyType, instantiateType(info.type, mapper), info.isReadonly, info.declaration);
61862         }
61863         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
61864         // that is subject to contextual typing.
61865         function isContextSensitive(node) {
61866             ts.Debug.assert(node.kind !== 168 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
61867             switch (node.kind) {
61868                 case 212 /* FunctionExpression */:
61869                 case 213 /* ArrowFunction */:
61870                 case 168 /* MethodDeclaration */:
61871                 case 255 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
61872                     return isContextSensitiveFunctionLikeDeclaration(node);
61873                 case 204 /* ObjectLiteralExpression */:
61874                     return ts.some(node.properties, isContextSensitive);
61875                 case 203 /* ArrayLiteralExpression */:
61876                     return ts.some(node.elements, isContextSensitive);
61877                 case 221 /* ConditionalExpression */:
61878                     return isContextSensitive(node.whenTrue) ||
61879                         isContextSensitive(node.whenFalse);
61880                 case 220 /* BinaryExpression */:
61881                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
61882                         (isContextSensitive(node.left) || isContextSensitive(node.right));
61883                 case 294 /* PropertyAssignment */:
61884                     return isContextSensitive(node.initializer);
61885                 case 211 /* ParenthesizedExpression */:
61886                     return isContextSensitive(node.expression);
61887                 case 285 /* JsxAttributes */:
61888                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
61889                 case 284 /* JsxAttribute */: {
61890                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
61891                     var initializer = node.initializer;
61892                     return !!initializer && isContextSensitive(initializer);
61893                 }
61894                 case 287 /* JsxExpression */: {
61895                     // It is possible to that node.expression is undefined (e.g <div x={} />)
61896                     var expression = node.expression;
61897                     return !!expression && isContextSensitive(expression);
61898                 }
61899             }
61900             return false;
61901         }
61902         function isContextSensitiveFunctionLikeDeclaration(node) {
61903             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
61904                 (ts.hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
61905         }
61906         function hasContextSensitiveReturnExpression(node) {
61907             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
61908             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 234 /* Block */ && isContextSensitive(node.body);
61909         }
61910         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
61911             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || ts.isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
61912                 isContextSensitiveFunctionLikeDeclaration(func);
61913         }
61914         function getTypeWithoutSignatures(type) {
61915             if (type.flags & 524288 /* Object */) {
61916                 var resolved = resolveStructuredTypeMembers(type);
61917                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
61918                     var result = createObjectType(16 /* Anonymous */, type.symbol);
61919                     result.members = resolved.members;
61920                     result.properties = resolved.properties;
61921                     result.callSignatures = ts.emptyArray;
61922                     result.constructSignatures = ts.emptyArray;
61923                     result.indexInfos = ts.emptyArray;
61924                     return result;
61925                 }
61926             }
61927             else if (type.flags & 2097152 /* Intersection */) {
61928                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
61929             }
61930             return type;
61931         }
61932         // TYPE CHECKING
61933         function isTypeIdenticalTo(source, target) {
61934             return isTypeRelatedTo(source, target, identityRelation);
61935         }
61936         function compareTypesIdentical(source, target) {
61937             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
61938         }
61939         function compareTypesAssignable(source, target) {
61940             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
61941         }
61942         function compareTypesSubtypeOf(source, target) {
61943             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
61944         }
61945         function isTypeSubtypeOf(source, target) {
61946             return isTypeRelatedTo(source, target, subtypeRelation);
61947         }
61948         function isTypeAssignableTo(source, target) {
61949             return isTypeRelatedTo(source, target, assignableRelation);
61950         }
61951         // An object type S is considered to be derived from an object type T if
61952         // S is a union type and every constituent of S is derived from T,
61953         // T is a union type and S is derived from at least one constituent of T, or
61954         // S is a type variable with a base constraint that is derived from T,
61955         // T is one of the global types Object and Function and S is a subtype of T, or
61956         // T occurs directly or indirectly in an 'extends' clause of S.
61957         // Note that this check ignores type parameters and only considers the
61958         // inheritance hierarchy.
61959         function isTypeDerivedFrom(source, target) {
61960             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
61961                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
61962                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
61963                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
61964                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
61965                                 hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType));
61966         }
61967         /**
61968          * This is *not* a bi-directional relationship.
61969          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
61970          *
61971          * 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.
61972          * It is used to check following cases:
61973          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
61974          *   - the types of `case` clause expressions and their respective `switch` expressions.
61975          *   - the type of an expression in a type assertion with the type being asserted.
61976          */
61977         function isTypeComparableTo(source, target) {
61978             return isTypeRelatedTo(source, target, comparableRelation);
61979         }
61980         function areTypesComparable(type1, type2) {
61981             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
61982         }
61983         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
61984             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
61985         }
61986         /**
61987          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
61988          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
61989          */
61990         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
61991             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
61992         }
61993         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
61994             if (isTypeRelatedTo(source, target, relation))
61995                 return true;
61996             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
61997                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
61998             }
61999             return false;
62000         }
62001         function isOrHasGenericConditional(type) {
62002             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
62003         }
62004         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
62005             if (!node || isOrHasGenericConditional(target))
62006                 return false;
62007             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
62008                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
62009                 return true;
62010             }
62011             switch (node.kind) {
62012                 case 287 /* JsxExpression */:
62013                 case 211 /* ParenthesizedExpression */:
62014                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
62015                 case 220 /* BinaryExpression */:
62016                     switch (node.operatorToken.kind) {
62017                         case 63 /* EqualsToken */:
62018                         case 27 /* CommaToken */:
62019                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
62020                     }
62021                     break;
62022                 case 204 /* ObjectLiteralExpression */:
62023                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
62024                 case 203 /* ArrayLiteralExpression */:
62025                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
62026                 case 285 /* JsxAttributes */:
62027                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
62028                 case 213 /* ArrowFunction */:
62029                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
62030             }
62031             return false;
62032         }
62033         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
62034             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
62035             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
62036             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
62037                 var signatures = _a[_i];
62038                 if (ts.some(signatures, function (s) {
62039                     var returnType = getReturnTypeOfSignature(s);
62040                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
62041                 })) {
62042                     var resultObj = errorOutputContainer || {};
62043                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
62044                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
62045                     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));
62046                     return true;
62047                 }
62048             }
62049             return false;
62050         }
62051         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
62052             // Don't elaborate blocks
62053             if (ts.isBlock(node.body)) {
62054                 return false;
62055             }
62056             // Or functions with annotated parameter types
62057             if (ts.some(node.parameters, ts.hasType)) {
62058                 return false;
62059             }
62060             var sourceSig = getSingleCallSignature(source);
62061             if (!sourceSig) {
62062                 return false;
62063             }
62064             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
62065             if (!ts.length(targetSignatures)) {
62066                 return false;
62067             }
62068             var returnExpression = node.body;
62069             var sourceReturn = getReturnTypeOfSignature(sourceSig);
62070             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
62071             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
62072                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
62073                 if (elaborated) {
62074                     return elaborated;
62075                 }
62076                 var resultObj = errorOutputContainer || {};
62077                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
62078                 if (resultObj.errors) {
62079                     if (target.symbol && ts.length(target.symbol.declarations)) {
62080                         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));
62081                     }
62082                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
62083                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
62084                         // an IPromise and a Promise that are slightly different
62085                         && !getTypeOfPropertyOfType(sourceReturn, "then")
62086                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
62087                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
62088                     }
62089                     return true;
62090                 }
62091             }
62092             return false;
62093         }
62094         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
62095             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
62096             if (idx) {
62097                 return idx;
62098             }
62099             if (target.flags & 1048576 /* Union */) {
62100                 var best = getBestMatchingType(source, target);
62101                 if (best) {
62102                     return getIndexedAccessTypeOrUndefined(best, nameType);
62103                 }
62104             }
62105         }
62106         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
62107             next.contextualType = sourcePropType;
62108             try {
62109                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
62110             }
62111             finally {
62112                 next.contextualType = undefined;
62113             }
62114         }
62115         /**
62116          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
62117          * 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`
62118          * Otherwise, we issue an error on _every_ element which fail the assignability check
62119          */
62120         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
62121             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
62122             var reportedError = false;
62123             for (var status = iterator.next(); !status.done; status = iterator.next()) {
62124                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
62125                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
62126                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
62127                     continue; // Don't elaborate on indexes on generic variables
62128                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
62129                 if (!sourcePropType)
62130                     continue;
62131                 var propName = getPropertyNameFromIndex(nameType, /*accessNode*/ undefined);
62132                 if (!checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
62133                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
62134                     reportedError = true;
62135                     if (!elaborated) {
62136                         // Issue error on the prop itself, since the prop couldn't elaborate the error
62137                         var resultObj = errorOutputContainer || {};
62138                         // Use the expression type, if available
62139                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
62140                         if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) {
62141                             var diag = ts.createDiagnosticForNode(prop, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, typeToString(specificSource), typeToString(targetPropType));
62142                             diagnostics.add(diag);
62143                             resultObj.errors = [diag];
62144                         }
62145                         else {
62146                             var targetIsOptional = !!(propName && (getPropertyOfType(target, propName) || unknownSymbol).flags & 16777216 /* Optional */);
62147                             var sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216 /* Optional */);
62148                             targetPropType = removeMissingType(targetPropType, targetIsOptional);
62149                             sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
62150                             var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
62151                             if (result && specificSource !== sourcePropType) {
62152                                 // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
62153                                 checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
62154                             }
62155                         }
62156                         if (resultObj.errors) {
62157                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
62158                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
62159                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
62160                             var issuedElaboration = false;
62161                             if (!targetProp) {
62162                                 var indexInfo = getApplicableIndexInfo(target, nameType);
62163                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
62164                                     issuedElaboration = true;
62165                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
62166                                 }
62167                             }
62168                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
62169                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
62170                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
62171                                     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)));
62172                                 }
62173                             }
62174                         }
62175                     }
62176                 }
62177             }
62178             return reportedError;
62179         }
62180         function generateJsxAttributes(node) {
62181             var _i, _a, prop;
62182             return __generator(this, function (_b) {
62183                 switch (_b.label) {
62184                     case 0:
62185                         if (!ts.length(node.properties))
62186                             return [2 /*return*/];
62187                         _i = 0, _a = node.properties;
62188                         _b.label = 1;
62189                     case 1:
62190                         if (!(_i < _a.length)) return [3 /*break*/, 4];
62191                         prop = _a[_i];
62192                         if (ts.isJsxSpreadAttribute(prop) || isHyphenatedJsxName(ts.idText(prop.name)))
62193                             return [3 /*break*/, 3];
62194                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(ts.idText(prop.name)) }];
62195                     case 2:
62196                         _b.sent();
62197                         _b.label = 3;
62198                     case 3:
62199                         _i++;
62200                         return [3 /*break*/, 1];
62201                     case 4: return [2 /*return*/];
62202                 }
62203             });
62204         }
62205         function generateJsxChildren(node, getInvalidTextDiagnostic) {
62206             var memberOffset, i, child, nameType, elem;
62207             return __generator(this, function (_a) {
62208                 switch (_a.label) {
62209                     case 0:
62210                         if (!ts.length(node.children))
62211                             return [2 /*return*/];
62212                         memberOffset = 0;
62213                         i = 0;
62214                         _a.label = 1;
62215                     case 1:
62216                         if (!(i < node.children.length)) return [3 /*break*/, 5];
62217                         child = node.children[i];
62218                         nameType = getNumberLiteralType(i - memberOffset);
62219                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
62220                         if (!elem) return [3 /*break*/, 3];
62221                         return [4 /*yield*/, elem];
62222                     case 2:
62223                         _a.sent();
62224                         return [3 /*break*/, 4];
62225                     case 3:
62226                         memberOffset++;
62227                         _a.label = 4;
62228                     case 4:
62229                         i++;
62230                         return [3 /*break*/, 1];
62231                     case 5: return [2 /*return*/];
62232                 }
62233             });
62234         }
62235         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
62236             switch (child.kind) {
62237                 case 287 /* JsxExpression */:
62238                     // child is of the type of the expression
62239                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
62240                 case 11 /* JsxText */:
62241                     if (child.containsOnlyTriviaWhiteSpaces) {
62242                         break; // Whitespace only jsx text isn't real jsx text
62243                     }
62244                     // child is a string
62245                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
62246                 case 277 /* JsxElement */:
62247                 case 278 /* JsxSelfClosingElement */:
62248                 case 281 /* JsxFragment */:
62249                     // child is of type JSX.Element
62250                     return { errorNode: child, innerExpression: child, nameType: nameType };
62251                 default:
62252                     return ts.Debug.assertNever(child, "Found invalid jsx child");
62253             }
62254         }
62255         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
62256             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
62257             var invalidTextDiagnostic;
62258             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
62259                 var containingElement = node.parent.parent;
62260                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
62261                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
62262                 var childrenNameType = getStringLiteralType(childrenPropName);
62263                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
62264                 var validChildren = ts.getSemanticJsxChildren(containingElement.children);
62265                 if (!ts.length(validChildren)) {
62266                     return result;
62267                 }
62268                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
62269                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
62270                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
62271                 if (moreThanOneRealChildren) {
62272                     if (arrayLikeTargetParts !== neverType) {
62273                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
62274                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
62275                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
62276                     }
62277                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
62278                         // arity mismatch
62279                         result = true;
62280                         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));
62281                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
62282                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
62283                         }
62284                     }
62285                 }
62286                 else {
62287                     if (nonArrayLikeTargetParts !== neverType) {
62288                         var child = validChildren[0];
62289                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
62290                         if (elem_1) {
62291                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
62292                                 switch (_a.label) {
62293                                     case 0: return [4 /*yield*/, elem_1];
62294                                     case 1:
62295                                         _a.sent();
62296                                         return [2 /*return*/];
62297                                 }
62298                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
62299                         }
62300                     }
62301                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
62302                         // arity mismatch
62303                         result = true;
62304                         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));
62305                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
62306                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
62307                         }
62308                     }
62309                 }
62310             }
62311             return result;
62312             function getInvalidTextualChildDiagnostic() {
62313                 if (!invalidTextDiagnostic) {
62314                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
62315                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
62316                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
62317                     var childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName));
62318                     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;
62319                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
62320                 }
62321                 return invalidTextDiagnostic;
62322             }
62323         }
62324         function generateLimitedTupleElements(node, target) {
62325             var len, i, elem, nameType;
62326             return __generator(this, function (_a) {
62327                 switch (_a.label) {
62328                     case 0:
62329                         len = ts.length(node.elements);
62330                         if (!len)
62331                             return [2 /*return*/];
62332                         i = 0;
62333                         _a.label = 1;
62334                     case 1:
62335                         if (!(i < len)) return [3 /*break*/, 4];
62336                         // 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
62337                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
62338                             return [3 /*break*/, 3];
62339                         elem = node.elements[i];
62340                         if (ts.isOmittedExpression(elem))
62341                             return [3 /*break*/, 3];
62342                         nameType = getNumberLiteralType(i);
62343                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
62344                     case 2:
62345                         _a.sent();
62346                         _a.label = 3;
62347                     case 3:
62348                         i++;
62349                         return [3 /*break*/, 1];
62350                     case 4: return [2 /*return*/];
62351                 }
62352             });
62353         }
62354         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
62355             if (target.flags & 131068 /* Primitive */)
62356                 return false;
62357             if (isTupleLikeType(source)) {
62358                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
62359             }
62360             // recreate a tuple from the elements, if possible
62361             // Since we're re-doing the expression type, we need to reapply the contextual type
62362             var oldContext = node.contextualType;
62363             node.contextualType = target;
62364             try {
62365                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
62366                 node.contextualType = oldContext;
62367                 if (isTupleLikeType(tupleizedType)) {
62368                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
62369                 }
62370                 return false;
62371             }
62372             finally {
62373                 node.contextualType = oldContext;
62374             }
62375         }
62376         function generateObjectLiteralElements(node) {
62377             var _i, _a, prop, type, _b;
62378             return __generator(this, function (_c) {
62379                 switch (_c.label) {
62380                     case 0:
62381                         if (!ts.length(node.properties))
62382                             return [2 /*return*/];
62383                         _i = 0, _a = node.properties;
62384                         _c.label = 1;
62385                     case 1:
62386                         if (!(_i < _a.length)) return [3 /*break*/, 8];
62387                         prop = _a[_i];
62388                         if (ts.isSpreadAssignment(prop))
62389                             return [3 /*break*/, 7];
62390                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
62391                         if (!type || (type.flags & 131072 /* Never */)) {
62392                             return [3 /*break*/, 7];
62393                         }
62394                         _b = prop.kind;
62395                         switch (_b) {
62396                             case 172 /* SetAccessor */: return [3 /*break*/, 2];
62397                             case 171 /* GetAccessor */: return [3 /*break*/, 2];
62398                             case 168 /* MethodDeclaration */: return [3 /*break*/, 2];
62399                             case 295 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
62400                             case 294 /* PropertyAssignment */: return [3 /*break*/, 4];
62401                         }
62402                         return [3 /*break*/, 6];
62403                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
62404                     case 3:
62405                         _c.sent();
62406                         return [3 /*break*/, 7];
62407                     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 }];
62408                     case 5:
62409                         _c.sent();
62410                         return [3 /*break*/, 7];
62411                     case 6:
62412                         ts.Debug.assertNever(prop);
62413                         _c.label = 7;
62414                     case 7:
62415                         _i++;
62416                         return [3 /*break*/, 1];
62417                     case 8: return [2 /*return*/];
62418                 }
62419             });
62420         }
62421         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
62422             if (target.flags & 131068 /* Primitive */)
62423                 return false;
62424             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
62425         }
62426         /**
62427          * This is *not* a bi-directional relationship.
62428          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
62429          */
62430         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
62431             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
62432         }
62433         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
62434             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
62435             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
62436         }
62437         /**
62438          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
62439          */
62440         function isAnySignature(s) {
62441             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
62442                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
62443                 isTypeAny(getReturnTypeOfSignature(s));
62444         }
62445         /**
62446          * See signatureRelatedTo, compareSignaturesIdentical
62447          */
62448         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
62449             // TODO (drosen): De-duplicate code between related functions.
62450             if (source === target) {
62451                 return -1 /* True */;
62452             }
62453             if (isAnySignature(target)) {
62454                 return -1 /* True */;
62455             }
62456             var targetCount = getParameterCount(target);
62457             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
62458                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
62459             if (sourceHasMoreParameters) {
62460                 return 0 /* False */;
62461             }
62462             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
62463                 target = getCanonicalSignature(target);
62464                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
62465             }
62466             var sourceCount = getParameterCount(source);
62467             var sourceRestType = getNonArrayRestType(source);
62468             var targetRestType = getNonArrayRestType(target);
62469             if (sourceRestType || targetRestType) {
62470                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
62471             }
62472             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
62473                 // We're not able to relate misaligned complex rest parameters
62474                 return 0 /* False */;
62475             }
62476             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
62477             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 168 /* MethodDeclaration */ &&
62478                 kind !== 167 /* MethodSignature */ && kind !== 170 /* Constructor */;
62479             var result = -1 /* True */;
62480             var sourceThisType = getThisTypeOfSignature(source);
62481             if (sourceThisType && sourceThisType !== voidType) {
62482                 var targetThisType = getThisTypeOfSignature(target);
62483                 if (targetThisType) {
62484                     // void sources are assignable to anything.
62485                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
62486                         || compareTypes(targetThisType, sourceThisType, reportErrors);
62487                     if (!related) {
62488                         if (reportErrors) {
62489                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
62490                         }
62491                         return 0 /* False */;
62492                     }
62493                     result &= related;
62494                 }
62495             }
62496             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
62497             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
62498             for (var i = 0; i < paramCount; i++) {
62499                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i);
62500                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i);
62501                 if (sourceType && targetType) {
62502                     // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
62503                     // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
62504                     // they naturally relate only contra-variantly). However, if the source and target parameters both have
62505                     // function types with a single call signature, we know we are relating two callback parameters. In
62506                     // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
62507                     // similar to return values, callback parameters are output positions. This means that a Promise<T>,
62508                     // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
62509                     // with respect to T.
62510                     var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
62511                     var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
62512                     var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
62513                         (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
62514                     var related = callbacks ?
62515                         compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
62516                         !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
62517                     // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
62518                     if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
62519                         related = 0 /* False */;
62520                     }
62521                     if (!related) {
62522                         if (reportErrors) {
62523                             errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
62524                         }
62525                         return 0 /* False */;
62526                     }
62527                     result &= related;
62528                 }
62529             }
62530             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
62531                 // If a signature resolution is already in-flight, skip issuing a circularity error
62532                 // here and just use the `any` type directly
62533                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
62534                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
62535                         : getReturnTypeOfSignature(target);
62536                 if (targetReturnType === voidType) {
62537                     return result;
62538                 }
62539                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
62540                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
62541                         : getReturnTypeOfSignature(source);
62542                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
62543                 var targetTypePredicate = getTypePredicateOfSignature(target);
62544                 if (targetTypePredicate) {
62545                     var sourceTypePredicate = getTypePredicateOfSignature(source);
62546                     if (sourceTypePredicate) {
62547                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
62548                     }
62549                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
62550                         if (reportErrors) {
62551                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
62552                         }
62553                         return 0 /* False */;
62554                     }
62555                 }
62556                 else {
62557                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
62558                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
62559                     // wouldn't be co-variant for T without this rule.
62560                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
62561                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
62562                     if (!result && reportErrors && incompatibleErrorReporter) {
62563                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
62564                     }
62565                 }
62566             }
62567             return result;
62568         }
62569         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
62570             if (source.kind !== target.kind) {
62571                 if (reportErrors) {
62572                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
62573                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
62574                 }
62575                 return 0 /* False */;
62576             }
62577             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
62578                 if (source.parameterIndex !== target.parameterIndex) {
62579                     if (reportErrors) {
62580                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
62581                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
62582                     }
62583                     return 0 /* False */;
62584                 }
62585             }
62586             var related = source.type === target.type ? -1 /* True */ :
62587                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
62588                     0 /* False */;
62589             if (related === 0 /* False */ && reportErrors) {
62590                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
62591             }
62592             return related;
62593         }
62594         function isImplementationCompatibleWithOverload(implementation, overload) {
62595             var erasedSource = getErasedSignature(implementation);
62596             var erasedTarget = getErasedSignature(overload);
62597             // First see if the return types are compatible in either direction.
62598             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
62599             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
62600             if (targetReturnType === voidType
62601                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
62602                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
62603                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
62604             }
62605             return false;
62606         }
62607         function isEmptyResolvedType(t) {
62608             return t !== anyFunctionType &&
62609                 t.properties.length === 0 &&
62610                 t.callSignatures.length === 0 &&
62611                 t.constructSignatures.length === 0 &&
62612                 t.indexInfos.length === 0;
62613         }
62614         function isEmptyObjectType(type) {
62615             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
62616                 type.flags & 67108864 /* NonPrimitive */ ? true :
62617                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
62618                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
62619                             false;
62620         }
62621         function isEmptyAnonymousObjectType(type) {
62622             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) ||
62623                 type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
62624         }
62625         function isStringIndexSignatureOnlyType(type) {
62626             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) ||
62627                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
62628                 false;
62629         }
62630         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
62631             if (sourceSymbol === targetSymbol) {
62632                 return true;
62633             }
62634             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
62635             var entry = enumRelation.get(id);
62636             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
62637                 return !!(entry & 1 /* Succeeded */);
62638             }
62639             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
62640                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
62641                 return false;
62642             }
62643             var targetEnumType = getTypeOfSymbol(targetSymbol);
62644             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
62645                 var property = _a[_i];
62646                 if (property.flags & 8 /* EnumMember */) {
62647                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
62648                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
62649                         if (errorReporter) {
62650                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
62651                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
62652                         }
62653                         else {
62654                             enumRelation.set(id, 2 /* Failed */);
62655                         }
62656                         return false;
62657                     }
62658                 }
62659             }
62660             enumRelation.set(id, 1 /* Succeeded */);
62661             return true;
62662         }
62663         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
62664             var s = source.flags;
62665             var t = target.flags;
62666             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
62667                 return true;
62668             if (t & 131072 /* Never */)
62669                 return false;
62670             if (s & 402653316 /* StringLike */ && t & 4 /* String */)
62671                 return true;
62672             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
62673                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
62674                 source.value === target.value)
62675                 return true;
62676             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
62677                 return true;
62678             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
62679                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
62680                 source.value === target.value)
62681                 return true;
62682             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
62683                 return true;
62684             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
62685                 return true;
62686             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
62687                 return true;
62688             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
62689                 return true;
62690             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
62691                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
62692                     return true;
62693                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
62694                     source.value === target.value &&
62695                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
62696                     return true;
62697             }
62698             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
62699                 return true;
62700             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
62701                 return true;
62702             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
62703                 return true;
62704             if (relation === assignableRelation || relation === comparableRelation) {
62705                 if (s & 1 /* Any */)
62706                     return true;
62707                 // Type number or any numeric literal type is assignable to any numeric enum type or any
62708                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
62709                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
62710                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
62711                     return true;
62712             }
62713             return false;
62714         }
62715         function isTypeRelatedTo(source, target, relation) {
62716             if (isFreshLiteralType(source)) {
62717                 source = source.regularType;
62718             }
62719             if (isFreshLiteralType(target)) {
62720                 target = target.regularType;
62721             }
62722             if (source === target) {
62723                 return true;
62724             }
62725             if (relation !== identityRelation) {
62726                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
62727                     return true;
62728                 }
62729             }
62730             else {
62731                 if (source.flags !== target.flags)
62732                     return false;
62733                 if (source.flags & 67358815 /* Singleton */)
62734                     return true;
62735             }
62736             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
62737                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
62738                 if (related !== undefined) {
62739                     return !!(related & 1 /* Succeeded */);
62740                 }
62741             }
62742             if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
62743                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
62744             }
62745             return false;
62746         }
62747         function isIgnoredJsxProperty(source, sourceProp) {
62748             return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && isHyphenatedJsxName(sourceProp.escapedName);
62749         }
62750         function getNormalizedType(type, writing) {
62751             while (true) {
62752                 var t = isFreshLiteralType(type) ? type.regularType :
62753                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
62754                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
62755                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
62756                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
62757                                     type;
62758                 t = getSingleBaseForNonAugmentingSubtype(t) || t;
62759                 if (t === type)
62760                     break;
62761                 type = t;
62762             }
62763             return type;
62764         }
62765         /**
62766          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
62767          * @param source The left-hand-side of the relation.
62768          * @param target The right-hand-side of the relation.
62769          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
62770          * Used as both to determine which checks are performed and as a cache of previously computed results.
62771          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
62772          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
62773          * @param containingMessageChain A chain of errors to prepend any new errors found.
62774          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
62775          */
62776         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
62777             var errorInfo;
62778             var relatedInfo;
62779             var maybeKeys;
62780             var sourceStack;
62781             var targetStack;
62782             var maybeCount = 0;
62783             var sourceDepth = 0;
62784             var targetDepth = 0;
62785             var expandingFlags = 0 /* None */;
62786             var overflow = false;
62787             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
62788             var lastSkippedInfo;
62789             var incompatibleStack = [];
62790             var inPropertyCheck = false;
62791             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
62792             var result = isRelatedTo(source, target, 3 /* Both */, /*reportErrors*/ !!errorNode, headMessage);
62793             if (incompatibleStack.length) {
62794                 reportIncompatibleStack();
62795             }
62796             if (overflow) {
62797                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth: targetDepth });
62798                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
62799                 if (errorOutputContainer) {
62800                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
62801                 }
62802             }
62803             else if (errorInfo) {
62804                 if (containingMessageChain) {
62805                     var chain = containingMessageChain();
62806                     if (chain) {
62807                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
62808                         errorInfo = chain;
62809                     }
62810                 }
62811                 var relatedInformation = void 0;
62812                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
62813                 if (headMessage && errorNode && !result && source.symbol) {
62814                     var links = getSymbolLinks(source.symbol);
62815                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
62816                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
62817                         if (helpfulRetry) {
62818                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
62819                             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);
62820                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
62821                         }
62822                     }
62823                 }
62824                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
62825                 if (relatedInfo) {
62826                     ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInfo, false));
62827                 }
62828                 if (errorOutputContainer) {
62829                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
62830                 }
62831                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
62832                     diagnostics.add(diag);
62833                 }
62834             }
62835             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
62836                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
62837             }
62838             return result !== 0 /* False */;
62839             function resetErrorInfo(saved) {
62840                 errorInfo = saved.errorInfo;
62841                 lastSkippedInfo = saved.lastSkippedInfo;
62842                 incompatibleStack = saved.incompatibleStack;
62843                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
62844                 relatedInfo = saved.relatedInfo;
62845             }
62846             function captureErrorCalculationState() {
62847                 return {
62848                     errorInfo: errorInfo,
62849                     lastSkippedInfo: lastSkippedInfo,
62850                     incompatibleStack: incompatibleStack.slice(),
62851                     overrideNextErrorInfo: overrideNextErrorInfo,
62852                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
62853                 };
62854             }
62855             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
62856                 overrideNextErrorInfo++; // Suppress the next relation error
62857                 lastSkippedInfo = undefined; // Reset skipped info cache
62858                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
62859             }
62860             function reportIncompatibleStack() {
62861                 var stack = incompatibleStack;
62862                 incompatibleStack = [];
62863                 var info = lastSkippedInfo;
62864                 lastSkippedInfo = undefined;
62865                 if (stack.length === 1) {
62866                     reportError.apply(void 0, stack[0]);
62867                     if (info) {
62868                         // Actually do the last relation error
62869                         reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info, false));
62870                     }
62871                     return;
62872                 }
62873                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
62874                 // we can build from left to right
62875                 var path = "";
62876                 var secondaryRootErrors = [];
62877                 while (stack.length) {
62878                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
62879                     switch (msg.code) {
62880                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
62881                             // Parenthesize a `new` if there is one
62882                             if (path.indexOf("new ") === 0) {
62883                                 path = "(".concat(path, ")");
62884                             }
62885                             var str = "" + args[0];
62886                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
62887                             if (path.length === 0) {
62888                                 path = "".concat(str);
62889                             }
62890                             // Otherwise write a dotted name if possible
62891                             else if (ts.isIdentifierText(str, ts.getEmitScriptTarget(compilerOptions))) {
62892                                 path = "".concat(path, ".").concat(str);
62893                             }
62894                             // Failing that, check if the name is already a computed name
62895                             else if (str[0] === "[" && str[str.length - 1] === "]") {
62896                                 path = "".concat(path).concat(str);
62897                             }
62898                             // And finally write out a computed name as a last resort
62899                             else {
62900                                 path = "".concat(path, "[").concat(str, "]");
62901                             }
62902                             break;
62903                         }
62904                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
62905                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
62906                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
62907                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
62908                             if (path.length === 0) {
62909                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
62910                                 // to unify (the with no arguments bit is excessive for printback) and print them back
62911                                 var mappedMsg = msg;
62912                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
62913                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
62914                                 }
62915                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
62916                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
62917                                 }
62918                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
62919                             }
62920                             else {
62921                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
62922                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
62923                                     ? "new "
62924                                     : "";
62925                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
62926                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
62927                                     ? ""
62928                                     : "...";
62929                                 path = "".concat(prefix).concat(path, "(").concat(params, ")");
62930                             }
62931                             break;
62932                         }
62933                         case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: {
62934                             secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]);
62935                             break;
62936                         }
62937                         case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: {
62938                             secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]);
62939                             break;
62940                         }
62941                         default:
62942                             return ts.Debug.fail("Unhandled Diagnostic: ".concat(msg.code));
62943                     }
62944                 }
62945                 if (path) {
62946                     reportError(path[path.length - 1] === ")"
62947                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
62948                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
62949                 }
62950                 else {
62951                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
62952                     secondaryRootErrors.shift();
62953                 }
62954                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
62955                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
62956                     var originalValue = msg.elidedInCompatabilityPyramid;
62957                     msg.elidedInCompatabilityPyramid = false; // Temporarily override elision to ensure error is reported
62958                     reportError.apply(void 0, __spreadArray([msg], args, false));
62959                     msg.elidedInCompatabilityPyramid = originalValue;
62960                 }
62961                 if (info) {
62962                     // Actually do the last relation error
62963                     reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info, false));
62964                 }
62965             }
62966             function reportError(message, arg0, arg1, arg2, arg3) {
62967                 ts.Debug.assert(!!errorNode);
62968                 if (incompatibleStack.length)
62969                     reportIncompatibleStack();
62970                 if (message.elidedInCompatabilityPyramid)
62971                     return;
62972                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
62973             }
62974             function associateRelatedInfo(info) {
62975                 ts.Debug.assert(!!errorInfo);
62976                 if (!relatedInfo) {
62977                     relatedInfo = [info];
62978                 }
62979                 else {
62980                     relatedInfo.push(info);
62981                 }
62982             }
62983             function reportRelationError(message, source, target) {
62984                 if (incompatibleStack.length)
62985                     reportIncompatibleStack();
62986                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
62987                 var generalizedSource = source;
62988                 var generalizedSourceType = sourceType;
62989                 if (isLiteralType(source) && !typeCouldHaveTopLevelSingletonTypes(target)) {
62990                     generalizedSource = getBaseTypeOfLiteralType(source);
62991                     ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable");
62992                     generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
62993                 }
62994                 if (target.flags & 262144 /* TypeParameter */) {
62995                     var constraint = getBaseConstraintOfType(target);
62996                     var needsOriginalSource = void 0;
62997                     if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) {
62998                         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));
62999                     }
63000                     else {
63001                         errorInfo = undefined;
63002                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType);
63003                     }
63004                 }
63005                 if (!message) {
63006                     if (relation === comparableRelation) {
63007                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
63008                     }
63009                     else if (sourceType === targetType) {
63010                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
63011                     }
63012                     else if (exactOptionalPropertyTypes && getExactOptionalUnassignableProperties(source, target).length) {
63013                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties;
63014                     }
63015                     else {
63016                         if (source.flags & 128 /* StringLiteral */ && target.flags & 1048576 /* Union */) {
63017                             var suggestedType = getSuggestedTypeForNonexistentStringLiteralType(source, target);
63018                             if (suggestedType) {
63019                                 reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Did_you_mean_2, generalizedSourceType, targetType, typeToString(suggestedType));
63020                                 return;
63021                             }
63022                         }
63023                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
63024                     }
63025                 }
63026                 else if (message === ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1
63027                     && exactOptionalPropertyTypes
63028                     && getExactOptionalUnassignableProperties(source, target).length) {
63029                     message = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties;
63030                 }
63031                 reportError(message, generalizedSourceType, targetType);
63032             }
63033             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
63034                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
63035                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
63036                 if ((globalStringType === source && stringType === target) ||
63037                     (globalNumberType === source && numberType === target) ||
63038                     (globalBooleanType === source && booleanType === target) ||
63039                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
63040                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
63041                 }
63042             }
63043             /**
63044              * Try and elaborate array and tuple errors. Returns false
63045              * if we have found an elaboration, or we should ignore
63046              * any other elaborations when relating the `source` and
63047              * `target` types.
63048              */
63049             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
63050                 /**
63051                  * The spec for elaboration is:
63052                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
63053                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
63054                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
63055                  * - If the source an array then skip property elaborations if the target is a tuple.
63056                  */
63057                 if (isTupleType(source)) {
63058                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
63059                         if (reportErrors) {
63060                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
63061                         }
63062                         return false;
63063                     }
63064                     return isTupleType(target) || isArrayType(target);
63065                 }
63066                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
63067                     if (reportErrors) {
63068                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
63069                     }
63070                     return false;
63071                 }
63072                 if (isTupleType(target)) {
63073                     return isArrayType(source);
63074                 }
63075                 return true;
63076             }
63077             function isRelatedToWorker(source, target, reportErrors) {
63078                 return isRelatedTo(source, target, 3 /* Both */, reportErrors);
63079             }
63080             /**
63081              * Compare two types and return
63082              * * Ternary.True if they are related with no assumptions,
63083              * * Ternary.Maybe if they are related with assumptions of other relationships, or
63084              * * Ternary.False if they are not related.
63085              */
63086             function isRelatedTo(originalSource, originalTarget, recursionFlags, reportErrors, headMessage, intersectionState) {
63087                 if (recursionFlags === void 0) { recursionFlags = 3 /* Both */; }
63088                 if (reportErrors === void 0) { reportErrors = false; }
63089                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
63090                 // Before normalization: if `source` is type an object type, and `target` is primitive,
63091                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
63092                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
63093                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
63094                         return -1 /* True */;
63095                     }
63096                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */));
63097                     return 0 /* False */;
63098                 }
63099                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
63100                 // turn deferred type references into regular type references, simplify indexed access and
63101                 // conditional types, and resolve substitution types to either the substitution (on the source
63102                 // side) or the type variable (on the target side).
63103                 var source = getNormalizedType(originalSource, /*writing*/ false);
63104                 var target = getNormalizedType(originalTarget, /*writing*/ true);
63105                 if (source === target)
63106                     return -1 /* True */;
63107                 if (relation === identityRelation) {
63108                     return isIdenticalTo(source, target, recursionFlags);
63109                 }
63110                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
63111                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
63112                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
63113                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
63114                 // the target is exactly the constraint.
63115                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
63116                     return -1 /* True */;
63117                 }
63118                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
63119                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
63120                 // First, see if we're even relating an object type to a union.
63121                 // Then see if the target is stripped down to a single non-union type.
63122                 // Note
63123                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
63124                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
63125                 //    when dealing with generics.
63126                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
63127                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
63128                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
63129                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
63130                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
63131                         target = getNormalizedType(nullStrippedTarget, /*writing*/ true);
63132                     }
63133                     if (source === nullStrippedTarget)
63134                         return -1 /* True */;
63135                 }
63136                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
63137                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
63138                     return -1 /* True */;
63139                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */);
63140                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */);
63141                 if (isPerformingExcessPropertyChecks) {
63142                     if (hasExcessProperties(source, target, reportErrors)) {
63143                         if (reportErrors) {
63144                             reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target);
63145                         }
63146                         return 0 /* False */;
63147                     }
63148                 }
63149                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
63150                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
63151                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
63152                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
63153                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
63154                     if (reportErrors) {
63155                         var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source);
63156                         var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target);
63157                         var calls = getSignaturesOfType(source, 0 /* Call */);
63158                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
63159                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) ||
63160                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) {
63161                             reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
63162                         }
63163                         else {
63164                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
63165                         }
63166                     }
63167                     return 0 /* False */;
63168                 }
63169                 traceUnionsOrIntersectionsTooLarge(source, target);
63170                 var result = 0 /* False */;
63171                 var saveErrorInfo = captureErrorCalculationState();
63172                 if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) {
63173                     // We skip caching when source or target is a union with no more than three constituents.
63174                     result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */);
63175                 }
63176                 else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) {
63177                     result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags);
63178                 }
63179                 if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) {
63180                     if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) {
63181                         resetErrorInfo(saveErrorInfo);
63182                     }
63183                 }
63184                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
63185                     // The combined constraint of an intersection type is the intersection of the constraints of
63186                     // the constituents. When an intersection type contains instantiable types with union type
63187                     // constraints, there are situations where we need to examine the combined constraint. One is
63188                     // when the target is a union type. Another is when the intersection contains types belonging
63189                     // to one of the disjoint domains. For example, given type variables T and U, each with the
63190                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
63191                     // we need to check this constraint against a union on the target side. Also, given a type
63192                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
63193                     // 'string & number | number & number' which reduces to just 'number'.
63194                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
63195                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
63196                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
63197                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
63198                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
63199                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
63200                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
63201                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
63202                             if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
63203                                 resetErrorInfo(saveErrorInfo);
63204                             }
63205                         }
63206                     }
63207                 }
63208                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
63209                 // an extra property check where the intersection is viewed as a single object. The following are motivating
63210                 // examples that all should be errors, but aren't without this extra property check:
63211                 //
63212                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
63213                 //
63214                 //   declare let wrong: { a: { y: string } };
63215                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
63216                 //
63217                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
63218                 //     x = y;  // Mismatched property in source intersection
63219                 //   }
63220                 //
63221                 // We suppress recursive intersection property checks because they can generate lots of work when relating
63222                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
63223                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
63224                     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) & 524288 /* NonInferrableType */); }))) {
63225                     inPropertyCheck = true;
63226                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags);
63227                     inPropertyCheck = false;
63228                 }
63229                 reportErrorResults(source, target, result, isComparingJsxAttributes);
63230                 return result;
63231                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
63232                     if (!result && reportErrors) {
63233                         var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource);
63234                         var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget);
63235                         source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source;
63236                         target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target;
63237                         var maybeSuppress = overrideNextErrorInfo > 0;
63238                         if (maybeSuppress) {
63239                             overrideNextErrorInfo--;
63240                         }
63241                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
63242                             var currentError = errorInfo;
63243                             tryElaborateArrayLikeErrors(source, target, reportErrors);
63244                             if (errorInfo !== currentError) {
63245                                 maybeSuppress = !!errorInfo;
63246                             }
63247                         }
63248                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
63249                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
63250                         }
63251                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
63252                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
63253                         }
63254                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
63255                             var targetTypes = target.types;
63256                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
63257                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
63258                             if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) &&
63259                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
63260                                 // do not report top error
63261                                 return result;
63262                             }
63263                         }
63264                         else {
63265                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
63266                         }
63267                         if (!headMessage && maybeSuppress) {
63268                             lastSkippedInfo = [source, target];
63269                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
63270                             return result;
63271                         }
63272                         reportRelationError(headMessage, source, target);
63273                     }
63274                 }
63275             }
63276             function traceUnionsOrIntersectionsTooLarge(source, target) {
63277                 if (!ts.tracing) {
63278                     return;
63279                 }
63280                 if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) {
63281                     var sourceUnionOrIntersection = source;
63282                     var targetUnionOrIntersection = target;
63283                     if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) {
63284                         // There's a fast path for comparing primitive unions
63285                         return;
63286                     }
63287                     var sourceSize = sourceUnionOrIntersection.types.length;
63288                     var targetSize = targetUnionOrIntersection.types.length;
63289                     if (sourceSize * targetSize > 1E6) {
63290                         ts.tracing.instant("checkTypes" /* CheckTypes */, "traceUnionsOrIntersectionsTooLarge_DepthLimit", {
63291                             sourceId: source.id,
63292                             sourceSize: sourceSize,
63293                             targetId: target.id,
63294                             targetSize: targetSize,
63295                             pos: errorNode === null || errorNode === void 0 ? void 0 : errorNode.pos,
63296                             end: errorNode === null || errorNode === void 0 ? void 0 : errorNode.end
63297                         });
63298                     }
63299                 }
63300             }
63301             function isIdenticalTo(source, target, recursionFlags) {
63302                 if (source.flags !== target.flags)
63303                     return 0 /* False */;
63304                 if (source.flags & 67358815 /* Singleton */)
63305                     return -1 /* True */;
63306                 traceUnionsOrIntersectionsTooLarge(source, target);
63307                 if (source.flags & 3145728 /* UnionOrIntersection */) {
63308                     var result_7 = eachTypeRelatedToSomeType(source, target);
63309                     if (result_7) {
63310                         result_7 &= eachTypeRelatedToSomeType(target, source);
63311                     }
63312                     return result_7;
63313                 }
63314                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags);
63315             }
63316             function getTypeOfPropertyInTypes(types, name) {
63317                 var appendPropType = function (propTypes, type) {
63318                     var _a;
63319                     type = getApparentType(type);
63320                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
63321                     var propType = prop && getTypeOfSymbol(prop) || ((_a = getApplicableIndexInfoForName(type, name)) === null || _a === void 0 ? void 0 : _a.type) || undefinedType;
63322                     return ts.append(propTypes, propType);
63323                 };
63324                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
63325             }
63326             function hasExcessProperties(source, target, reportErrors) {
63327                 var _a;
63328                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) {
63329                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
63330                 }
63331                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */);
63332                 if ((relation === assignableRelation || relation === comparableRelation) &&
63333                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
63334                     return false;
63335                 }
63336                 var reducedTarget = target;
63337                 var checkTypes;
63338                 if (target.flags & 1048576 /* Union */) {
63339                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
63340                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
63341                 }
63342                 var _loop_18 = function (prop) {
63343                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
63344                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
63345                             if (reportErrors) {
63346                                 // Report error in terms of object types in the target as those are the only ones
63347                                 // we check in isKnownProperty.
63348                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
63349                                 // We know *exactly* where things went wrong when comparing the types.
63350                                 // Use this property as the error node as this will be more helpful in
63351                                 // reasoning about what went wrong.
63352                                 if (!errorNode)
63353                                     return { value: ts.Debug.fail() };
63354                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
63355                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
63356                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
63357                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
63358                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
63359                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
63360                                         errorNode = prop.valueDeclaration.name;
63361                                     }
63362                                     var propName = symbolToString(prop);
63363                                     var suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
63364                                     var suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : undefined;
63365                                     if (suggestion) {
63366                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
63367                                     }
63368                                     else {
63369                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
63370                                     }
63371                                 }
63372                                 else {
63373                                     // use the property's value declaration if the property is assigned inside the literal itself
63374                                     var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations);
63375                                     var suggestion = void 0;
63376                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
63377                                         var propDeclaration = prop.valueDeclaration;
63378                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
63379                                         errorNode = propDeclaration;
63380                                         var name = propDeclaration.name;
63381                                         if (ts.isIdentifier(name)) {
63382                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
63383                                         }
63384                                     }
63385                                     if (suggestion !== undefined) {
63386                                         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);
63387                                     }
63388                                     else {
63389                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
63390                                     }
63391                                 }
63392                             }
63393                             return { value: true };
63394                         }
63395                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), 3 /* Both */, reportErrors)) {
63396                             if (reportErrors) {
63397                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
63398                             }
63399                             return { value: true };
63400                         }
63401                     }
63402                 };
63403                 for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) {
63404                     var prop = _b[_i];
63405                     var state_5 = _loop_18(prop);
63406                     if (typeof state_5 === "object")
63407                         return state_5.value;
63408                 }
63409                 return false;
63410             }
63411             function shouldCheckAsExcessProperty(prop, container) {
63412                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
63413             }
63414             function eachTypeRelatedToSomeType(source, target) {
63415                 var result = -1 /* True */;
63416                 var sourceTypes = source.types;
63417                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
63418                     var sourceType = sourceTypes_1[_i];
63419                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
63420                     if (!related) {
63421                         return 0 /* False */;
63422                     }
63423                     result &= related;
63424                 }
63425                 return result;
63426             }
63427             function typeRelatedToSomeType(source, target, reportErrors) {
63428                 var targetTypes = target.types;
63429                 if (target.flags & 1048576 /* Union */) {
63430                     if (containsType(targetTypes, source)) {
63431                         return -1 /* True */;
63432                     }
63433                     var match = getMatchingUnionConstituentForType(target, source);
63434                     if (match) {
63435                         var related = isRelatedTo(source, match, 2 /* Target */, /*reportErrors*/ false);
63436                         if (related) {
63437                             return related;
63438                         }
63439                     }
63440                 }
63441                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
63442                     var type = targetTypes_1[_i];
63443                     var related = isRelatedTo(source, type, 2 /* Target */, /*reportErrors*/ false);
63444                     if (related) {
63445                         return related;
63446                     }
63447                 }
63448                 if (reportErrors) {
63449                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
63450                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], 2 /* Target */, /*reportErrors*/ true);
63451                 }
63452                 return 0 /* False */;
63453             }
63454             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
63455                 var result = -1 /* True */;
63456                 var targetTypes = target.types;
63457                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
63458                     var targetType = targetTypes_2[_i];
63459                     var related = isRelatedTo(source, targetType, 2 /* Target */, reportErrors, /*headMessage*/ undefined, intersectionState);
63460                     if (!related) {
63461                         return 0 /* False */;
63462                     }
63463                     result &= related;
63464                 }
63465                 return result;
63466             }
63467             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
63468                 var sourceTypes = source.types;
63469                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
63470                     return -1 /* True */;
63471                 }
63472                 var len = sourceTypes.length;
63473                 for (var i = 0; i < len; i++) {
63474                     var related = isRelatedTo(sourceTypes[i], target, 1 /* Source */, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
63475                     if (related) {
63476                         return related;
63477                     }
63478                 }
63479                 return 0 /* False */;
63480             }
63481             function getUndefinedStrippedTargetIfNeeded(source, target) {
63482                 // As a builtin type, `undefined` is a very low type ID - making it almsot always first, making this a very fast check to see
63483                 // if we need to strip `undefined` from the target
63484                 if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ &&
63485                     !(source.types[0].flags & 32768 /* Undefined */) && target.types[0].flags & 32768 /* Undefined */) {
63486                     return extractTypesOfKind(target, ~32768 /* Undefined */);
63487                 }
63488                 return target;
63489             }
63490             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
63491                 var result = -1 /* True */;
63492                 var sourceTypes = source.types;
63493                 // We strip `undefined` from the target if the `source` trivially doesn't contain it for our correspondence-checking fastpath
63494                 // since `undefined` is frequently added by optionality and would otherwise spoil a potentially useful correspondence
63495                 var undefinedStrippedTarget = getUndefinedStrippedTargetIfNeeded(source, target);
63496                 for (var i = 0; i < sourceTypes.length; i++) {
63497                     var sourceType = sourceTypes[i];
63498                     if (undefinedStrippedTarget.flags & 1048576 /* Union */ && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) {
63499                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
63500                         // such unions will have identical lengths, and their corresponding elements will match up. Another common scenario is where a large
63501                         // union has a union of objects intersected with it. In such cases, if the input was, eg `("a" | "b" | "c") & (string | boolean | {} | {whatever})`,
63502                         // the result will have the structure `"a" | "b" | "c" | "a" & {} | "b" & {} | "c" & {} | "a" & {whatever} | "b" & {whatever} | "c" & {whatever}`
63503                         // - the resulting union has a length which is a multiple of the original union, and the elements correspond modulo the length of the original union
63504                         var related_1 = isRelatedTo(sourceType, undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], 3 /* Both */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
63505                         if (related_1) {
63506                             result &= related_1;
63507                             continue;
63508                         }
63509                     }
63510                     var related = isRelatedTo(sourceType, target, 1 /* Source */, reportErrors, /*headMessage*/ undefined, intersectionState);
63511                     if (!related) {
63512                         return 0 /* False */;
63513                     }
63514                     result &= related;
63515                 }
63516                 return result;
63517             }
63518             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
63519                 if (sources === void 0) { sources = ts.emptyArray; }
63520                 if (targets === void 0) { targets = ts.emptyArray; }
63521                 if (variances === void 0) { variances = ts.emptyArray; }
63522                 if (sources.length !== targets.length && relation === identityRelation) {
63523                     return 0 /* False */;
63524                 }
63525                 var length = sources.length <= targets.length ? sources.length : targets.length;
63526                 var result = -1 /* True */;
63527                 for (var i = 0; i < length; i++) {
63528                     // When variance information isn't available we default to covariance. This happens
63529                     // in the process of computing variance information for recursive types and when
63530                     // comparing 'this' type arguments.
63531                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
63532                     var variance = varianceFlags & 7 /* VarianceMask */;
63533                     // We ignore arguments for independent type parameters (because they're never witnessed).
63534                     if (variance !== 4 /* Independent */) {
63535                         var s = sources[i];
63536                         var t = targets[i];
63537                         var related = -1 /* True */;
63538                         if (varianceFlags & 8 /* Unmeasurable */) {
63539                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
63540                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
63541                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
63542                             related = relation === identityRelation ? isRelatedTo(s, t, 3 /* Both */, /*reportErrors*/ false) : compareTypesIdentical(s, t);
63543                         }
63544                         else if (variance === 1 /* Covariant */) {
63545                             related = isRelatedTo(s, t, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
63546                         }
63547                         else if (variance === 2 /* Contravariant */) {
63548                             related = isRelatedTo(t, s, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
63549                         }
63550                         else if (variance === 3 /* Bivariant */) {
63551                             // In the bivariant case we first compare contravariantly without reporting
63552                             // errors. Then, if that doesn't succeed, we compare covariantly with error
63553                             // reporting. Thus, error elaboration will be based on the the covariant check,
63554                             // which is generally easier to reason about.
63555                             related = isRelatedTo(t, s, 3 /* Both */, /*reportErrors*/ false);
63556                             if (!related) {
63557                                 related = isRelatedTo(s, t, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
63558                             }
63559                         }
63560                         else {
63561                             // In the invariant case we first compare covariantly, and only when that
63562                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
63563                             // will typically be based on the covariant check.
63564                             related = isRelatedTo(s, t, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
63565                             if (related) {
63566                                 related &= isRelatedTo(t, s, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
63567                             }
63568                         }
63569                         if (!related) {
63570                             return 0 /* False */;
63571                         }
63572                         result &= related;
63573                     }
63574                 }
63575                 return result;
63576             }
63577             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
63578             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
63579             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
63580             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
63581             // and issue an error. Otherwise, actually compare the structure of the two types.
63582             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags) {
63583                 if (overflow) {
63584                     return 0 /* False */;
63585                 }
63586                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0), relation);
63587                 var entry = relation.get(id);
63588                 if (entry !== undefined) {
63589                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
63590                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
63591                         // as a failure, and should be updated as a reported failure by the bottom of this function.
63592                     }
63593                     else {
63594                         if (outofbandVarianceMarkerHandler) {
63595                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
63596                             var saved = entry & 24 /* ReportsMask */;
63597                             if (saved & 8 /* ReportsUnmeasurable */) {
63598                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
63599                             }
63600                             if (saved & 16 /* ReportsUnreliable */) {
63601                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
63602                             }
63603                         }
63604                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
63605                     }
63606                 }
63607                 if (!maybeKeys) {
63608                     maybeKeys = [];
63609                     sourceStack = [];
63610                     targetStack = [];
63611                 }
63612                 else {
63613                     // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids
63614                     // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus
63615                     // prevent finding matches- but it should hit up the common cases
63616                     var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) {
63617                         var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined);
63618                         return "=".concat(index);
63619                     }); }).join(",");
63620                     for (var i = 0; i < maybeCount; i++) {
63621                         // If source and target are already being compared, consider them related with assumptions
63622                         if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) {
63623                             return 3 /* Maybe */;
63624                         }
63625                     }
63626                     if (sourceDepth === 100 || targetDepth === 100) {
63627                         overflow = true;
63628                         return 0 /* False */;
63629                     }
63630                 }
63631                 var maybeStart = maybeCount;
63632                 maybeKeys[maybeCount] = id;
63633                 maybeCount++;
63634                 var saveExpandingFlags = expandingFlags;
63635                 if (recursionFlags & 1 /* Source */) {
63636                     sourceStack[sourceDepth] = source;
63637                     sourceDepth++;
63638                     if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth))
63639                         expandingFlags |= 1 /* Source */;
63640                 }
63641                 if (recursionFlags & 2 /* Target */) {
63642                     targetStack[targetDepth] = target;
63643                     targetDepth++;
63644                     if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth))
63645                         expandingFlags |= 2 /* Target */;
63646                 }
63647                 var originalHandler;
63648                 var propagatingVarianceFlags = 0;
63649                 if (outofbandVarianceMarkerHandler) {
63650                     originalHandler = outofbandVarianceMarkerHandler;
63651                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
63652                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
63653                         return originalHandler(onlyUnreliable);
63654                     };
63655                 }
63656                 if (expandingFlags === 3 /* Both */) {
63657                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", {
63658                         sourceId: source.id,
63659                         sourceIdStack: sourceStack.map(function (t) { return t.id; }),
63660                         targetId: target.id,
63661                         targetIdStack: targetStack.map(function (t) { return t.id; }),
63662                         depth: sourceDepth,
63663                         targetDepth: targetDepth
63664                     });
63665                 }
63666                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */;
63667                 if (outofbandVarianceMarkerHandler) {
63668                     outofbandVarianceMarkerHandler = originalHandler;
63669                 }
63670                 if (recursionFlags & 1 /* Source */) {
63671                     sourceDepth--;
63672                 }
63673                 if (recursionFlags & 2 /* Target */) {
63674                     targetDepth--;
63675                 }
63676                 expandingFlags = saveExpandingFlags;
63677                 if (result) {
63678                     if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) {
63679                         if (result === -1 /* True */ || result === 3 /* Maybe */) {
63680                             // If result is definitely true, record all maybe keys as having succeeded. Also, record Ternary.Maybe
63681                             // results as having succeeded once we reach depth 0, but never record Ternary.Unknown results.
63682                             for (var i = maybeStart; i < maybeCount; i++) {
63683                                 relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
63684                             }
63685                         }
63686                         maybeCount = maybeStart;
63687                     }
63688                 }
63689                 else {
63690                     // A false result goes straight into global cache (when something is false under
63691                     // assumptions it will also be false without assumptions)
63692                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
63693                     maybeCount = maybeStart;
63694                 }
63695                 return result;
63696             }
63697             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
63698                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
63699                 var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
63700                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
63701                 return result;
63702             }
63703             function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
63704                 if (intersectionState & 4 /* PropertyCheck */) {
63705                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
63706                 }
63707                 if (intersectionState & 8 /* UnionIntersectionCheck */) {
63708                     // Note that these checks are specifically ordered to produce correct results. In particular,
63709                     // we need to deconstruct unions before intersections (because unions are always at the top),
63710                     // and we need to handle "each" relations before "some" relations for the same kind of type.
63711                     if (source.flags & 1048576 /* Union */) {
63712                         return relation === comparableRelation ?
63713                             someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) :
63714                             eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */);
63715                     }
63716                     if (target.flags & 1048576 /* Union */) {
63717                         return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
63718                     }
63719                     if (target.flags & 2097152 /* Intersection */) {
63720                         return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
63721                     }
63722                     // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the
63723                     // constraints of all non-primitive types in the source into a new intersection. We do this because the
63724                     // intersection may further constrain the constraints of the non-primitive types. For example, given a type
63725                     // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't
63726                     // appear to be comparable to '2'.
63727                     if (relation === comparableRelation && target.flags & 131068 /* Primitive */) {
63728                         var constraints = ts.sameMap(source.types, getBaseConstraintOrType);
63729                         if (constraints !== source.types) {
63730                             source = getIntersectionType(constraints);
63731                             if (!(source.flags & 2097152 /* Intersection */)) {
63732                                 return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false);
63733                             }
63734                         }
63735                     }
63736                     // Check to see if any constituents of the intersection are immediately related to the target.
63737                     //
63738                     // Don't report errors though. Checking whether a constituent is related to the source is not actually
63739                     // useful and leads to some confusing error messages. Instead it is better to let the below checks
63740                     // take care of this, or to not elaborate at all. For instance,
63741                     //
63742                     //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
63743                     //
63744                     //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
63745                     //          than to report that 'D' is not assignable to 'A' or 'B'.
63746                     //
63747                     //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
63748                     //          breaking the intersection apart.
63749                     return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
63750                 }
63751                 var flags = source.flags & target.flags;
63752                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
63753                     if (flags & 4194304 /* Index */) {
63754                         return isRelatedTo(source.type, target.type, 3 /* Both */, /*reportErrors*/ false);
63755                     }
63756                     var result_8 = 0 /* False */;
63757                     if (flags & 8388608 /* IndexedAccess */) {
63758                         if (result_8 = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) {
63759                             if (result_8 &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) {
63760                                 return result_8;
63761                             }
63762                         }
63763                     }
63764                     if (flags & 16777216 /* Conditional */) {
63765                         if (source.root.isDistributive === target.root.isDistributive) {
63766                             if (result_8 = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) {
63767                                 if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) {
63768                                     if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
63769                                         if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
63770                                             return result_8;
63771                                         }
63772                                     }
63773                                 }
63774                             }
63775                         }
63776                     }
63777                     if (flags & 33554432 /* Substitution */) {
63778                         return isRelatedTo(source.substitute, target.substitute, 3 /* Both */, /*reportErrors*/ false);
63779                     }
63780                     return 0 /* False */;
63781                 }
63782                 var result;
63783                 var originalErrorInfo;
63784                 var varianceCheckFailed = false;
63785                 var saveErrorInfo = captureErrorCalculationState();
63786                 // We limit alias variance probing to only object and conditional types since their alias behavior
63787                 // is more predictable than other, interned types, which may or may not have an alias depending on
63788                 // the order in which things were checked.
63789                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
63790                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
63791                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
63792                     var variances = getAliasVariances(source.aliasSymbol);
63793                     if (variances === ts.emptyArray) {
63794                         return 1 /* Unknown */;
63795                     }
63796                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
63797                     if (varianceResult !== undefined) {
63798                         return varianceResult;
63799                     }
63800                 }
63801                 // 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],
63802                 // and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
63803                 if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target, 1 /* Source */)) ||
63804                     isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], 2 /* Target */))) {
63805                     return result;
63806                 }
63807                 if (target.flags & 262144 /* TypeParameter */) {
63808                     // 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].
63809                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source), 3 /* Both */)) {
63810                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
63811                             var templateType = getTemplateTypeFromMappedType(source);
63812                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
63813                             if (result = isRelatedTo(templateType, indexedAccessType, 3 /* Both */, reportErrors)) {
63814                                 return result;
63815                             }
63816                         }
63817                     }
63818                 }
63819                 else if (target.flags & 4194304 /* Index */) {
63820                     var targetType_1 = target.type;
63821                     // A keyof S is related to a keyof T if T is related to S.
63822                     if (source.flags & 4194304 /* Index */) {
63823                         if (result = isRelatedTo(targetType_1, source.type, 3 /* Both */, /*reportErrors*/ false)) {
63824                             return result;
63825                         }
63826                     }
63827                     if (isTupleType(targetType_1)) {
63828                         // An index type can have a tuple type target when the tuple type contains variadic elements.
63829                         // Check if the source is related to the known keys of the tuple type.
63830                         if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType_1), 2 /* Target */, reportErrors)) {
63831                             return result;
63832                         }
63833                     }
63834                     else {
63835                         // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
63836                         // simplified form of T or, if T doesn't simplify, the constraint of T.
63837                         var constraint = getSimplifiedTypeOrConstraint(targetType_1);
63838                         if (constraint) {
63839                             // We require Ternary.True here such that circular constraints don't cause
63840                             // false positives. For example, given 'T extends { [K in keyof T]: string }',
63841                             // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
63842                             // related to other types.
63843                             if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), 2 /* Target */, reportErrors) === -1 /* True */) {
63844                                 return -1 /* True */;
63845                             }
63846                         }
63847                         else if (isGenericMappedType(targetType_1)) {
63848                             // generic mapped types that don't simplify or have a constraint still have a very simple set of keys we can compare against
63849                             // - their nameType or constraintType.
63850                             // In many ways, this comparison is a deferred version of what `getIndexTypeForMappedType` does to actually resolve the keys for _non_-generic types
63851                             var nameType_1 = getNameTypeFromMappedType(targetType_1);
63852                             var constraintType = getConstraintTypeFromMappedType(targetType_1);
63853                             var targetKeys = void 0;
63854                             if (nameType_1 && isMappedTypeWithKeyofConstraintDeclaration(targetType_1)) {
63855                                 // we need to get the apparent mappings and union them with the generic mappings, since some properties may be
63856                                 // missing from the `constraintType` which will otherwise be mapped in the object
63857                                 var modifiersType = getApparentType(getModifiersTypeFromMappedType(targetType_1));
63858                                 var mappedKeys_1 = [];
63859                                 forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */, 
63860                                 /*stringsOnly*/ false, function (t) { return void mappedKeys_1.push(instantiateType(nameType_1, appendTypeMapping(targetType_1.mapper, getTypeParameterFromMappedType(targetType_1), t))); });
63861                                 // We still need to include the non-apparent (and thus still generic) keys in the target side of the comparison (in case they're in the source side)
63862                                 targetKeys = getUnionType(__spreadArray(__spreadArray([], mappedKeys_1, true), [nameType_1], false));
63863                             }
63864                             else {
63865                                 targetKeys = nameType_1 || constraintType;
63866                             }
63867                             if (isRelatedTo(source, targetKeys, 2 /* Target */, reportErrors) === -1 /* True */) {
63868                                 return -1 /* True */;
63869                             }
63870                         }
63871                     }
63872                 }
63873                 else if (target.flags & 8388608 /* IndexedAccess */) {
63874                     if (source.flags & 8388608 /* IndexedAccess */) {
63875                         // Relate components directly before falling back to constraint relationships
63876                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
63877                         if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, reportErrors)) {
63878                             result &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, reportErrors);
63879                         }
63880                         if (result) {
63881                             resetErrorInfo(saveErrorInfo);
63882                             return result;
63883                         }
63884                         if (reportErrors) {
63885                             originalErrorInfo = errorInfo;
63886                         }
63887                     }
63888                     // A type S is related to a type T[K] if S is related to C, where C is the base
63889                     // constraint of T[K] for writing.
63890                     if (relation === assignableRelation || relation === comparableRelation) {
63891                         var objectType = target.objectType;
63892                         var indexType = target.indexType;
63893                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
63894                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
63895                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
63896                             var accessFlags = 4 /* Writing */ | (baseObjectType !== objectType ? 2 /* NoIndexSignatures */ : 0);
63897                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags);
63898                             if (constraint) {
63899                                 if (reportErrors && originalErrorInfo) {
63900                                     // create a new chain for the constraint error
63901                                     resetErrorInfo(saveErrorInfo);
63902                                 }
63903                                 if (result = isRelatedTo(source, constraint, 2 /* Target */, reportErrors)) {
63904                                     return result;
63905                                 }
63906                                 // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain
63907                                 if (reportErrors && originalErrorInfo && errorInfo) {
63908                                     errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo;
63909                                 }
63910                             }
63911                         }
63912                     }
63913                     if (reportErrors) {
63914                         originalErrorInfo = undefined;
63915                     }
63916                 }
63917                 else if (isGenericMappedType(target) && relation !== identityRelation) {
63918                     // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`.
63919                     var keysRemapped = !!target.declaration.nameType;
63920                     var templateType = getTemplateTypeFromMappedType(target);
63921                     var modifiers = getMappedTypeModifiers(target);
63922                     if (!(modifiers & 8 /* ExcludeOptional */)) {
63923                         // If the mapped type has shape `{ [P in Q]: T[P] }`,
63924                         // source `S` is related to target if `T` = `S`, i.e. `S` is related to `{ [P in Q]: S[P] }`.
63925                         if (!keysRemapped && templateType.flags & 8388608 /* IndexedAccess */ && templateType.objectType === source &&
63926                             templateType.indexType === getTypeParameterFromMappedType(target)) {
63927                             return -1 /* True */;
63928                         }
63929                         if (!isGenericMappedType(source)) {
63930                             // If target has shape `{ [P in Q as R]: T}`, then its keys have type `R`.
63931                             // If target has shape `{ [P in Q]: T }`, then its keys have type `Q`.
63932                             var targetKeys = keysRemapped ? getNameTypeFromMappedType(target) : getConstraintTypeFromMappedType(target);
63933                             // Type of the keys of source type `S`, i.e. `keyof S`.
63934                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
63935                             var includeOptional = modifiers & 4 /* IncludeOptional */;
63936                             var filteredByApplicability = includeOptional ? intersectTypes(targetKeys, sourceKeys) : undefined;
63937                             // A source type `S` is related to a target type `{ [P in Q]: T }` if `Q` is related to `keyof S` and `S[Q]` is related to `T`.
63938                             // A source type `S` is related to a target type `{ [P in Q as R]: T }` if `R` is related to `keyof S` and `S[R]` is related to `T.
63939                             // A source type `S` is related to a target type `{ [P in Q]?: T }` if some constituent `Q'` of `Q` is related to `keyof S` and `S[Q']` is related to `T`.
63940                             // A source type `S` is related to a target type `{ [P in Q as R]?: T }` if some constituent `R'` of `R` is related to `keyof S` and `S[R']` is related to `T`.
63941                             if (includeOptional
63942                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
63943                                 : isRelatedTo(targetKeys, sourceKeys, 3 /* Both */)) {
63944                                 var templateType_1 = getTemplateTypeFromMappedType(target);
63945                                 var typeParameter = getTypeParameterFromMappedType(target);
63946                                 // Fastpath: When the template type has the form `Obj[P]` where `P` is the mapped type parameter, directly compare source `S` with `Obj`
63947                                 // to avoid creating the (potentially very large) number of new intermediate types made by manufacturing `S[P]`.
63948                                 var nonNullComponent = extractTypesOfKind(templateType_1, ~98304 /* Nullable */);
63949                                 if (!keysRemapped && nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
63950                                     if (result = isRelatedTo(source, nonNullComponent.objectType, 2 /* Target */, reportErrors)) {
63951                                         return result;
63952                                     }
63953                                 }
63954                                 else {
63955                                     // We need to compare the type of a property on the source type `S` to the type of the same property on the target type,
63956                                     // so we need to construct an indexing type representing a property, and then use indexing type to index the source type for comparison.
63957                                     // If the target type has shape `{ [P in Q]: T }`, then a property of the target has type `P`.
63958                                     // If the target type has shape `{ [P in Q]?: T }`, then a property of the target has type `P`,
63959                                     // but the property is optional, so we only want to compare properties `P` that are common between `keyof S` and `Q`.
63960                                     // If the target type has shape `{ [P in Q as R]: T }`, then a property of the target has type `R`.
63961                                     // If the target type has shape `{ [P in Q as R]?: T }`, then a property of the target has type `R`,
63962                                     // but the property is optional, so we only want to compare properties `R` that are common between `keyof S` and `R`.
63963                                     var indexingType = keysRemapped
63964                                         ? (filteredByApplicability || targetKeys)
63965                                         : filteredByApplicability
63966                                             ? getIntersectionType([filteredByApplicability, typeParameter])
63967                                             : typeParameter;
63968                                     var indexedAccessType = getIndexedAccessType(source, indexingType);
63969                                     // Compare `S[indexingType]` to `T`, where `T` is the type of a property of the target type.
63970                                     if (result = isRelatedTo(indexedAccessType, templateType_1, 3 /* Both */, reportErrors)) {
63971                                         return result;
63972                                     }
63973                                 }
63974                             }
63975                             originalErrorInfo = errorInfo;
63976                             resetErrorInfo(saveErrorInfo);
63977                         }
63978                     }
63979                 }
63980                 else if (target.flags & 16777216 /* Conditional */) {
63981                     // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
63982                     // conditional type and bail out with a Ternary.Maybe result.
63983                     if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) {
63984                         resetErrorInfo(saveErrorInfo);
63985                         return 3 /* Maybe */;
63986                     }
63987                     var c = target;
63988                     // We check for a relationship to a conditional type target only when the conditional type has no
63989                     // 'infer' positions and is not distributive or is distributive but doesn't reference the check type
63990                     // parameter in either of the result types.
63991                     if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) {
63992                         // Check if the conditional is always true or always false but still deferred for distribution purposes.
63993                         var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType));
63994                         var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType));
63995                         // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't)
63996                         if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) {
63997                             result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false);
63998                             if (result) {
63999                                 resetErrorInfo(saveErrorInfo);
64000                                 return result;
64001                             }
64002                         }
64003                     }
64004                 }
64005                 else if (target.flags & 134217728 /* TemplateLiteral */) {
64006                     if (source.flags & 134217728 /* TemplateLiteral */) {
64007                         if (relation === comparableRelation) {
64008                             return templateLiteralTypesDefinitelyUnrelated(source, target) ? 0 /* False */ : -1 /* True */;
64009                         }
64010                         // Report unreliable variance for type variables referenced in template literal type placeholders.
64011                         // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string.
64012                         instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
64013                     }
64014                     if (isTypeMatchedByTemplateLiteralType(source, target)) {
64015                         return -1 /* True */;
64016                     }
64017                 }
64018                 if (source.flags & 8650752 /* TypeVariable */) {
64019                     // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch
64020                     if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) {
64021                         var constraint = getConstraintOfType(source);
64022                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
64023                             // A type variable with no constraint is not related to the non-primitive object type.
64024                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */), 3 /* Both */)) {
64025                                 resetErrorInfo(saveErrorInfo);
64026                                 return result;
64027                             }
64028                         }
64029                         // 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
64030                         else if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
64031                             resetErrorInfo(saveErrorInfo);
64032                             return result;
64033                         }
64034                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
64035                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) {
64036                             resetErrorInfo(saveErrorInfo);
64037                             return result;
64038                         }
64039                     }
64040                 }
64041                 else if (source.flags & 4194304 /* Index */) {
64042                     if (result = isRelatedTo(keyofConstraintType, target, 1 /* Source */, reportErrors)) {
64043                         resetErrorInfo(saveErrorInfo);
64044                         return result;
64045                     }
64046                 }
64047                 else if (source.flags & 134217728 /* TemplateLiteral */ && !(target.flags & 524288 /* Object */)) {
64048                     if (!(target.flags & 134217728 /* TemplateLiteral */)) {
64049                         var constraint = getBaseConstraintOfType(source);
64050                         if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* Source */, reportErrors))) {
64051                             resetErrorInfo(saveErrorInfo);
64052                             return result;
64053                         }
64054                     }
64055                 }
64056                 else if (source.flags & 268435456 /* StringMapping */) {
64057                     if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
64058                         if (result = isRelatedTo(source.type, target.type, 3 /* Both */, reportErrors)) {
64059                             resetErrorInfo(saveErrorInfo);
64060                             return result;
64061                         }
64062                     }
64063                     else {
64064                         var constraint = getBaseConstraintOfType(source);
64065                         if (constraint && (result = isRelatedTo(constraint, target, 1 /* Source */, reportErrors))) {
64066                             resetErrorInfo(saveErrorInfo);
64067                             return result;
64068                         }
64069                     }
64070                 }
64071                 else if (source.flags & 16777216 /* Conditional */) {
64072                     // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
64073                     // conditional type and bail out with a Ternary.Maybe result.
64074                     if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) {
64075                         resetErrorInfo(saveErrorInfo);
64076                         return 3 /* Maybe */;
64077                     }
64078                     if (target.flags & 16777216 /* Conditional */) {
64079                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
64080                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
64081                         // and Y1 is related to Y2.
64082                         var sourceParams = source.root.inferTypeParameters;
64083                         var sourceExtends = source.extendsType;
64084                         var mapper = void 0;
64085                         if (sourceParams) {
64086                             // If the source has infer type parameters, we instantiate them in the context of the target
64087                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker);
64088                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */);
64089                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
64090                             mapper = ctx.mapper;
64091                         }
64092                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
64093                             (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) {
64094                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) {
64095                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors);
64096                             }
64097                             if (result) {
64098                                 resetErrorInfo(saveErrorInfo);
64099                                 return result;
64100                             }
64101                         }
64102                     }
64103                     else {
64104                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
64105                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
64106                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
64107                         if (distributiveConstraint) {
64108                             if (result = isRelatedTo(distributiveConstraint, target, 1 /* Source */, reportErrors)) {
64109                                 resetErrorInfo(saveErrorInfo);
64110                                 return result;
64111                             }
64112                         }
64113                     }
64114                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
64115                     // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!).
64116                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
64117                     if (defaultConstraint) {
64118                         if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) {
64119                             resetErrorInfo(saveErrorInfo);
64120                             return result;
64121                         }
64122                     }
64123                 }
64124                 else {
64125                     // An empty object type is related to any mapped type that includes a '?' modifier.
64126                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
64127                         return -1 /* True */;
64128                     }
64129                     if (isGenericMappedType(target)) {
64130                         if (isGenericMappedType(source)) {
64131                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
64132                                 resetErrorInfo(saveErrorInfo);
64133                                 return result;
64134                             }
64135                         }
64136                         return 0 /* False */;
64137                     }
64138                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
64139                     if (relation !== identityRelation) {
64140                         source = getApparentType(source);
64141                     }
64142                     else if (isGenericMappedType(source)) {
64143                         return 0 /* False */;
64144                     }
64145                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
64146                         !isTupleType(source) && !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) {
64147                         // We have type references to the same generic type, and the type references are not marker
64148                         // type references (which are intended by be compared structurally). Obtain the variance
64149                         // information for the type parameters and relate the type arguments accordingly.
64150                         var variances = getVariances(source.target);
64151                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
64152                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
64153                         // recursive instantiations of the generic type.
64154                         if (variances === ts.emptyArray) {
64155                             return 1 /* Unknown */;
64156                         }
64157                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
64158                         if (varianceResult !== undefined) {
64159                             return varianceResult;
64160                         }
64161                     }
64162                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
64163                         if (relation !== identityRelation) {
64164                             return isRelatedTo(getIndexTypeOfType(source, numberType) || anyType, getIndexTypeOfType(target, numberType) || anyType, 3 /* Both */, reportErrors);
64165                         }
64166                         else {
64167                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
64168                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
64169                             return 0 /* False */;
64170                         }
64171                     }
64172                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
64173                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
64174                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) {
64175                         return 0 /* False */;
64176                     }
64177                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
64178                     // it may hold in a structural comparison.
64179                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
64180                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
64181                     // relates to X. Thus, we include intersection types on the source side here.
64182                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
64183                         // Report structural errors only if we haven't reported any errors yet
64184                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
64185                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
64186                         if (result) {
64187                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
64188                             if (result) {
64189                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
64190                                 if (result) {
64191                                     result &= indexSignaturesRelatedTo(source, target, sourceIsPrimitive, reportStructuralErrors, intersectionState);
64192                                 }
64193                             }
64194                         }
64195                         if (varianceCheckFailed && result) {
64196                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
64197                         }
64198                         else if (result) {
64199                             return result;
64200                         }
64201                     }
64202                     // If S is an object type and T is a discriminated union, S may be related to T if
64203                     // there exists a constituent of T for every combination of the discriminants of S
64204                     // with respect to T. We do not report errors here, as we will use the existing
64205                     // error result from checking each constituent of the union.
64206                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
64207                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
64208                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
64209                             var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
64210                             if (result_9) {
64211                                 return result_9;
64212                             }
64213                         }
64214                     }
64215                 }
64216                 return 0 /* False */;
64217                 function countMessageChainBreadth(info) {
64218                     if (!info)
64219                         return 0;
64220                     return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0);
64221                 }
64222                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
64223                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
64224                         return result;
64225                     }
64226                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
64227                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
64228                         // have to allow a structural fallback check
64229                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
64230                         // be assuming identity of the type parameter.
64231                         originalErrorInfo = undefined;
64232                         resetErrorInfo(saveErrorInfo);
64233                         return undefined;
64234                     }
64235                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
64236                     varianceCheckFailed = !allowStructuralFallback;
64237                     // The type arguments did not relate appropriately, but it may be because we have no variance
64238                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
64239                     // arguments). It might also be the case that the target type has a 'void' type argument for
64240                     // a covariant type parameter that is only used in return positions within the generic type
64241                     // (in which case any type argument is permitted on the source side). In those cases we proceed
64242                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
64243                     // related and we can return here.
64244                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
64245                         // In some cases generic types that are covariant in regular type checking mode become
64246                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
64247                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
64248                         // types are invariant, if any of the type parameters are invariant we reset the reported
64249                         // errors and instead force a structural comparison (which will include elaborations that
64250                         // reveal the reason).
64251                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
64252                         // we can return `False` early here to skip calculating the structural error message we don't need.
64253                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
64254                             return 0 /* False */;
64255                         }
64256                         // We remember the original error information so we can restore it in case the structural
64257                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
64258                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
64259                         originalErrorInfo = errorInfo;
64260                         resetErrorInfo(saveErrorInfo);
64261                     }
64262                 }
64263             }
64264             function reportUnmeasurableMarkers(p) {
64265                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
64266                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
64267                 }
64268                 return p;
64269             }
64270             function reportUnreliableMarkers(p) {
64271                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
64272                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
64273                 }
64274                 return p;
64275             }
64276             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
64277             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
64278             // that S and T are contra-variant whereas X and Y are co-variant.
64279             function mappedTypeRelatedTo(source, target, reportErrors) {
64280                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
64281                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
64282                 if (modifiersRelated) {
64283                     var result_10;
64284                     var targetConstraint = getConstraintTypeFromMappedType(target);
64285                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
64286                     if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) {
64287                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
64288                         if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) {
64289                             return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors);
64290                         }
64291                     }
64292                 }
64293                 return 0 /* False */;
64294             }
64295             function typeRelatedToDiscriminatedType(source, target) {
64296                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
64297                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
64298                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
64299                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
64300                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
64301                 //    'target' are related to a property in 'source'.
64302                 //
64303                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
64304                 //       for examples.
64305                 var sourceProperties = getPropertiesOfType(source);
64306                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
64307                 if (!sourcePropertiesFiltered)
64308                     return 0 /* False */;
64309                 // Though we could compute the number of combinations as we generate
64310                 // the matrix, this would incur additional memory overhead due to
64311                 // array allocations. To reduce this overhead, we first compute
64312                 // the number of combinations to ensure we will not surpass our
64313                 // fixed limit before incurring the cost of any allocations:
64314                 var numCombinations = 1;
64315                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
64316                     var sourceProperty = sourcePropertiesFiltered_1[_i];
64317                     numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty));
64318                     if (numCombinations > 25) {
64319                         // We've reached the complexity limit.
64320                         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
64321                         return 0 /* False */;
64322                     }
64323                 }
64324                 // Compute the set of types for each discriminant property.
64325                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
64326                 var excludedProperties = new ts.Set();
64327                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
64328                     var sourceProperty = sourcePropertiesFiltered[i];
64329                     var sourcePropertyType = getNonMissingTypeOfSymbol(sourceProperty);
64330                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
64331                         ? sourcePropertyType.types
64332                         : [sourcePropertyType];
64333                     excludedProperties.add(sourceProperty.escapedName);
64334                 }
64335                 // Match each combination of the cartesian product of discriminant properties to one or more
64336                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
64337                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
64338                 var matchingTypes = [];
64339                 var _loop_19 = function (combination) {
64340                     var hasMatch = false;
64341                     outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) {
64342                         var type = _d[_c];
64343                         var _loop_20 = function (i) {
64344                             var sourceProperty = sourcePropertiesFiltered[i];
64345                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
64346                             if (!targetProperty)
64347                                 return "continue-outer";
64348                             if (sourceProperty === targetProperty)
64349                                 return "continue";
64350                             // We compare the source property to the target in the context of a single discriminant type.
64351                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
64352                             // If the target property could not be found, or if the properties were not related,
64353                             // then this constituent is not a match.
64354                             if (!related) {
64355                                 return "continue-outer";
64356                             }
64357                         };
64358                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
64359                             var state_7 = _loop_20(i);
64360                             switch (state_7) {
64361                                 case "continue-outer": continue outer;
64362                             }
64363                         }
64364                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
64365                         hasMatch = true;
64366                     }
64367                     if (!hasMatch) {
64368                         return { value: 0 /* False */ };
64369                     }
64370                 };
64371                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
64372                     var combination = discriminantCombinations_1[_a];
64373                     var state_6 = _loop_19(combination);
64374                     if (typeof state_6 === "object")
64375                         return state_6.value;
64376                 }
64377                 // Compare the remaining non-discriminant properties of each match.
64378                 var result = -1 /* True */;
64379                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
64380                     var type = matchingTypes_1[_b];
64381                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
64382                     if (result) {
64383                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
64384                         if (result) {
64385                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
64386                             if (result && !(isTupleType(source) && isTupleType(type))) {
64387                                 // Comparing numeric index types when both `source` and `type` are tuples is unnecessary as the
64388                                 // element types should be sufficiently covered by `propertiesRelatedTo`. It also causes problems
64389                                 // with index type assignability as the types for the excluded discriminants are still included
64390                                 // in the index type.
64391                                 result &= indexSignaturesRelatedTo(source, type, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
64392                             }
64393                         }
64394                     }
64395                     if (!result) {
64396                         return result;
64397                     }
64398                 }
64399                 return result;
64400             }
64401             function excludeProperties(properties, excludedProperties) {
64402                 if (!excludedProperties || properties.length === 0)
64403                     return properties;
64404                 var result;
64405                 for (var i = 0; i < properties.length; i++) {
64406                     if (!excludedProperties.has(properties[i].escapedName)) {
64407                         if (result) {
64408                             result.push(properties[i]);
64409                         }
64410                     }
64411                     else if (!result) {
64412                         result = properties.slice(0, i);
64413                     }
64414                 }
64415                 return result || properties;
64416             }
64417             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
64418                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
64419                 var effectiveTarget = addOptionality(getNonMissingTypeOfSymbol(targetProp), /*isProperty*/ false, targetIsOptional);
64420                 var effectiveSource = getTypeOfSourceProperty(sourceProp);
64421                 return isRelatedTo(effectiveSource, effectiveTarget, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
64422             }
64423             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
64424                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
64425                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
64426                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
64427                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
64428                         if (reportErrors) {
64429                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
64430                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
64431                             }
64432                             else {
64433                                 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));
64434                             }
64435                         }
64436                         return 0 /* False */;
64437                     }
64438                 }
64439                 else if (targetPropFlags & 16 /* Protected */) {
64440                     if (!isValidOverrideOf(sourceProp, targetProp)) {
64441                         if (reportErrors) {
64442                             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));
64443                         }
64444                         return 0 /* False */;
64445                     }
64446                 }
64447                 else if (sourcePropFlags & 16 /* Protected */) {
64448                     if (reportErrors) {
64449                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
64450                     }
64451                     return 0 /* False */;
64452                 }
64453                 // If the target comes from a partial union prop, allow `undefined` in the target type
64454                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
64455                 if (!related) {
64456                     if (reportErrors) {
64457                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
64458                     }
64459                     return 0 /* False */;
64460                 }
64461                 // When checking for comparability, be more lenient with optional properties.
64462                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
64463                     // TypeScript 1.0 spec (April 2014): 3.8.3
64464                     // S is a subtype of a type T, and T is a supertype of S if ...
64465                     // S' and T are object types and, for each member M in T..
64466                     // M is a property and S' contains a property N where
64467                     // if M is a required property, N is also a required property
64468                     // (M - property in T)
64469                     // (N - property in S)
64470                     if (reportErrors) {
64471                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
64472                     }
64473                     return 0 /* False */;
64474                 }
64475                 return related;
64476             }
64477             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
64478                 var shouldSkipElaboration = false;
64479                 // give specific error in case where private names have the same description
64480                 if (unmatchedProperty.valueDeclaration
64481                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
64482                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
64483                     && source.symbol
64484                     && source.symbol.flags & 32 /* Class */) {
64485                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
64486                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
64487                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
64488                         var sourceName = ts.factory.getDeclarationName(source.symbol.valueDeclaration);
64489                         var targetName = ts.factory.getDeclarationName(target.symbol.valueDeclaration);
64490                         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));
64491                         return;
64492                     }
64493                 }
64494                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
64495                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
64496                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
64497                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
64498                 }
64499                 if (props.length === 1) {
64500                     var propName = symbolToString(unmatchedProperty);
64501                     reportError.apply(void 0, __spreadArray([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target), false));
64502                     if (ts.length(unmatchedProperty.declarations)) {
64503                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
64504                     }
64505                     if (shouldSkipElaboration && errorInfo) {
64506                         overrideNextErrorInfo++;
64507                     }
64508                 }
64509                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
64510                     if (props.length > 5) { // arbitrary cutoff for too-long list form
64511                         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);
64512                     }
64513                     else {
64514                         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(", "));
64515                     }
64516                     if (shouldSkipElaboration && errorInfo) {
64517                         overrideNextErrorInfo++;
64518                     }
64519                 }
64520                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
64521             }
64522             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
64523                 if (relation === identityRelation) {
64524                     return propertiesIdenticalTo(source, target, excludedProperties);
64525                 }
64526                 var result = -1 /* True */;
64527                 if (isTupleType(target)) {
64528                     if (isArrayType(source) || isTupleType(source)) {
64529                         if (!target.target.readonly && (isReadonlyArrayType(source) || isTupleType(source) && source.target.readonly)) {
64530                             return 0 /* False */;
64531                         }
64532                         var sourceArity = getTypeReferenceArity(source);
64533                         var targetArity = getTypeReferenceArity(target);
64534                         var sourceRestFlag = isTupleType(source) ? source.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
64535                         var targetRestFlag = target.target.combinedFlags & 4 /* Rest */;
64536                         var sourceMinLength = isTupleType(source) ? source.target.minLength : 0;
64537                         var targetMinLength = target.target.minLength;
64538                         if (!sourceRestFlag && sourceArity < targetMinLength) {
64539                             if (reportErrors) {
64540                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
64541                             }
64542                             return 0 /* False */;
64543                         }
64544                         if (!targetRestFlag && targetArity < sourceMinLength) {
64545                             if (reportErrors) {
64546                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
64547                             }
64548                             return 0 /* False */;
64549                         }
64550                         if (!targetRestFlag && (sourceRestFlag || targetArity < sourceArity)) {
64551                             if (reportErrors) {
64552                                 if (sourceMinLength < targetMinLength) {
64553                                     reportError(ts.Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
64554                                 }
64555                                 else {
64556                                     reportError(ts.Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
64557                                 }
64558                             }
64559                             return 0 /* False */;
64560                         }
64561                         var sourceTypeArguments = getTypeArguments(source);
64562                         var targetTypeArguments = getTypeArguments(target);
64563                         var startCount = Math.min(isTupleType(source) ? getStartElementCount(source.target, 11 /* NonRest */) : 0, getStartElementCount(target.target, 11 /* NonRest */));
64564                         var endCount = Math.min(isTupleType(source) ? getEndElementCount(source.target, 11 /* NonRest */) : 0, targetRestFlag ? getEndElementCount(target.target, 11 /* NonRest */) : 0);
64565                         var canExcludeDiscriminants = !!excludedProperties;
64566                         for (var i = 0; i < targetArity; i++) {
64567                             var sourceIndex = i < targetArity - endCount ? i : i + sourceArity - targetArity;
64568                             var sourceFlags = isTupleType(source) && (i < startCount || i >= targetArity - endCount) ? source.target.elementFlags[sourceIndex] : 4 /* Rest */;
64569                             var targetFlags = target.target.elementFlags[i];
64570                             if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */)) {
64571                                 if (reportErrors) {
64572                                     reportError(ts.Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, i);
64573                                 }
64574                                 return 0 /* False */;
64575                             }
64576                             if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) {
64577                                 if (reportErrors) {
64578                                     reportError(ts.Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourceIndex, i);
64579                                 }
64580                                 return 0 /* False */;
64581                             }
64582                             if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) {
64583                                 if (reportErrors) {
64584                                     reportError(ts.Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, i);
64585                                 }
64586                                 return 0 /* False */;
64587                             }
64588                             // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
64589                             if (canExcludeDiscriminants) {
64590                                 if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
64591                                     canExcludeDiscriminants = false;
64592                                 }
64593                                 if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
64594                                     continue;
64595                                 }
64596                             }
64597                             var sourceType = !isTupleType(source) ? sourceTypeArguments[0] :
64598                                 i < startCount || i >= targetArity - endCount ? removeMissingType(sourceTypeArguments[sourceIndex], !!(sourceFlags & targetFlags & 2 /* Optional */)) :
64599                                     getElementTypeOfSliceOfTupleType(source, startCount, endCount) || neverType;
64600                             var targetType = targetTypeArguments[i];
64601                             var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) :
64602                                 removeMissingType(targetType, !!(targetFlags & 2 /* Optional */));
64603                             var related = isRelatedTo(sourceType, targetCheckType, 3 /* Both */, reportErrors, /*headMessage*/ undefined, intersectionState);
64604                             if (!related) {
64605                                 if (reportErrors && (targetArity > 1 || sourceArity > 1)) {
64606                                     if (i < startCount || i >= targetArity - endCount || sourceArity - startCount - endCount === 1) {
64607                                         reportIncompatibleError(ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, sourceIndex, i);
64608                                     }
64609                                     else {
64610                                         reportIncompatibleError(ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, startCount, sourceArity - endCount - 1, i);
64611                                     }
64612                                 }
64613                                 return 0 /* False */;
64614                             }
64615                             result &= related;
64616                         }
64617                         return result;
64618                     }
64619                     if (target.target.combinedFlags & 12 /* Variable */) {
64620                         return 0 /* False */;
64621                     }
64622                 }
64623                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
64624                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
64625                 if (unmatchedProperty) {
64626                     if (reportErrors) {
64627                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
64628                     }
64629                     return 0 /* False */;
64630                 }
64631                 if (isObjectLiteralType(target)) {
64632                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
64633                         var sourceProp = _a[_i];
64634                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
64635                             var sourceType = getTypeOfSymbol(sourceProp);
64636                             if (!(sourceType.flags & 32768 /* Undefined */)) {
64637                                 if (reportErrors) {
64638                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
64639                                 }
64640                                 return 0 /* False */;
64641                             }
64642                         }
64643                     }
64644                 }
64645                 // 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_
64646                 // from the target union, across all members
64647                 var properties = getPropertiesOfType(target);
64648                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
64649                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
64650                     var targetProp = _c[_b];
64651                     var name = targetProp.escapedName;
64652                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
64653                         var sourceProp = getPropertyOfType(source, name);
64654                         if (sourceProp && sourceProp !== targetProp) {
64655                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
64656                             if (!related) {
64657                                 return 0 /* False */;
64658                             }
64659                             result &= related;
64660                         }
64661                     }
64662                 }
64663                 return result;
64664             }
64665             function propertiesIdenticalTo(source, target, excludedProperties) {
64666                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
64667                     return 0 /* False */;
64668                 }
64669                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
64670                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
64671                 if (sourceProperties.length !== targetProperties.length) {
64672                     return 0 /* False */;
64673                 }
64674                 var result = -1 /* True */;
64675                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
64676                     var sourceProp = sourceProperties_1[_i];
64677                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
64678                     if (!targetProp) {
64679                         return 0 /* False */;
64680                     }
64681                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
64682                     if (!related) {
64683                         return 0 /* False */;
64684                     }
64685                     result &= related;
64686                 }
64687                 return result;
64688             }
64689             function signaturesRelatedTo(source, target, kind, reportErrors) {
64690                 var _a, _b;
64691                 if (relation === identityRelation) {
64692                     return signaturesIdenticalTo(source, target, kind);
64693                 }
64694                 if (target === anyFunctionType || source === anyFunctionType) {
64695                     return -1 /* True */;
64696                 }
64697                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
64698                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
64699                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
64700                     0 /* Call */ : kind);
64701                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
64702                     0 /* Call */ : kind);
64703                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
64704                     var sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */);
64705                     var targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */);
64706                     if (sourceIsAbstract && !targetIsAbstract) {
64707                         // An abstract constructor type is not assignable to a non-abstract constructor type
64708                         // as it would otherwise be possible to new an abstract class. Note that the assignability
64709                         // check we perform for an extends clause excludes construct signatures from the target,
64710                         // so this check never proceeds.
64711                         if (reportErrors) {
64712                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
64713                         }
64714                         return 0 /* False */;
64715                     }
64716                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
64717                         return 0 /* False */;
64718                     }
64719                 }
64720                 var result = -1 /* True */;
64721                 var saveErrorInfo = captureErrorCalculationState();
64722                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
64723                 var sourceObjectFlags = ts.getObjectFlags(source);
64724                 var targetObjectFlags = ts.getObjectFlags(target);
64725                 if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) {
64726                     // We have instantiations of the same anonymous type (which typically will be the type of a
64727                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
64728                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
64729                     // as they are known to always be the same.
64730                     for (var i = 0; i < targetSignatures.length; i++) {
64731                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
64732                         if (!related) {
64733                             return 0 /* False */;
64734                         }
64735                         result &= related;
64736                     }
64737                 }
64738                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
64739                     // For simple functions (functions with a single signature) we only erase type parameters for
64740                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
64741                     // in the context of the target signature before checking the relationship. Ideally we'd do
64742                     // this regardless of the number of signatures, but the potential costs are prohibitive due
64743                     // to the quadratic nature of the logic below.
64744                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
64745                     var sourceSignature = ts.first(sourceSignatures);
64746                     var targetSignature = ts.first(targetSignatures);
64747                     result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature));
64748                     if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) &&
64749                         (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 170 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 170 /* Constructor */)) {
64750                         var constructSignatureToString = function (signature) {
64751                             return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind);
64752                         };
64753                         reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature));
64754                         reportError(ts.Diagnostics.Types_of_construct_signatures_are_incompatible);
64755                         return result;
64756                     }
64757                 }
64758                 else {
64759                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
64760                         var t = targetSignatures_1[_i];
64761                         // Only elaborate errors from the first failure
64762                         var shouldElaborateErrors = reportErrors;
64763                         for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) {
64764                             var s = sourceSignatures_1[_c];
64765                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
64766                             if (related) {
64767                                 result &= related;
64768                                 resetErrorInfo(saveErrorInfo);
64769                                 continue outer;
64770                             }
64771                             shouldElaborateErrors = false;
64772                         }
64773                         if (shouldElaborateErrors) {
64774                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
64775                         }
64776                         return 0 /* False */;
64777                     }
64778                 }
64779                 return result;
64780             }
64781             function reportIncompatibleCallSignatureReturn(siga, sigb) {
64782                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
64783                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
64784                 }
64785                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
64786             }
64787             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
64788                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
64789                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
64790                 }
64791                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
64792             }
64793             /**
64794              * See signatureAssignableTo, compareSignaturesIdentical
64795              */
64796             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
64797                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers));
64798             }
64799             function signaturesIdenticalTo(source, target, kind) {
64800                 var sourceSignatures = getSignaturesOfType(source, kind);
64801                 var targetSignatures = getSignaturesOfType(target, kind);
64802                 if (sourceSignatures.length !== targetSignatures.length) {
64803                     return 0 /* False */;
64804                 }
64805                 var result = -1 /* True */;
64806                 for (var i = 0; i < sourceSignatures.length; i++) {
64807                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
64808                     if (!related) {
64809                         return 0 /* False */;
64810                     }
64811                     result &= related;
64812                 }
64813                 return result;
64814             }
64815             function membersRelatedToIndexInfo(source, targetInfo, reportErrors) {
64816                 var result = -1 /* True */;
64817                 var keyType = targetInfo.keyType;
64818                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
64819                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
64820                     var prop = props_2[_i];
64821                     // Skip over ignored JSX and symbol-named members
64822                     if (isIgnoredJsxProperty(source, prop)) {
64823                         continue;
64824                     }
64825                     if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), keyType)) {
64826                         var propType = getNonMissingTypeOfSymbol(prop);
64827                         var type = exactOptionalPropertyTypes || propType.flags & 32768 /* Undefined */ || keyType === numberType || !(prop.flags & 16777216 /* Optional */)
64828                             ? propType
64829                             : getTypeWithFacts(propType, 524288 /* NEUndefined */);
64830                         var related = isRelatedTo(type, targetInfo.type, 3 /* Both */, reportErrors);
64831                         if (!related) {
64832                             if (reportErrors) {
64833                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
64834                             }
64835                             return 0 /* False */;
64836                         }
64837                         result &= related;
64838                     }
64839                 }
64840                 for (var _a = 0, _b = getIndexInfosOfType(source); _a < _b.length; _a++) {
64841                     var info = _b[_a];
64842                     if (isApplicableIndexType(info.keyType, keyType)) {
64843                         var related = indexInfoRelatedTo(info, targetInfo, reportErrors);
64844                         if (!related) {
64845                             return 0 /* False */;
64846                         }
64847                         result &= related;
64848                     }
64849                 }
64850                 return result;
64851             }
64852             function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) {
64853                 var related = isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */, reportErrors);
64854                 if (!related && reportErrors) {
64855                     if (sourceInfo.keyType === targetInfo.keyType) {
64856                         reportError(ts.Diagnostics._0_index_signatures_are_incompatible, typeToString(sourceInfo.keyType));
64857                     }
64858                     else {
64859                         reportError(ts.Diagnostics._0_and_1_index_signatures_are_incompatible, typeToString(sourceInfo.keyType), typeToString(targetInfo.keyType));
64860                     }
64861                 }
64862                 return related;
64863             }
64864             function indexSignaturesRelatedTo(source, target, sourceIsPrimitive, reportErrors, intersectionState) {
64865                 if (relation === identityRelation) {
64866                     return indexSignaturesIdenticalTo(source, target);
64867                 }
64868                 var indexInfos = getIndexInfosOfType(target);
64869                 var targetHasStringIndex = ts.some(indexInfos, function (info) { return info.keyType === stringType; });
64870                 var result = -1 /* True */;
64871                 for (var _i = 0, indexInfos_3 = indexInfos; _i < indexInfos_3.length; _i++) {
64872                     var targetInfo = indexInfos_3[_i];
64873                     var related = !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & 1 /* Any */ ? -1 /* True */ :
64874                         isGenericMappedType(source) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, 3 /* Both */, reportErrors) :
64875                             typeRelatedToIndexInfo(source, targetInfo, reportErrors, intersectionState);
64876                     if (!related) {
64877                         return 0 /* False */;
64878                     }
64879                     result &= related;
64880                 }
64881                 return result;
64882             }
64883             function typeRelatedToIndexInfo(source, targetInfo, reportErrors, intersectionState) {
64884                 var sourceInfo = getApplicableIndexInfo(source, targetInfo.keyType);
64885                 if (sourceInfo) {
64886                     return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors);
64887                 }
64888                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
64889                     // Intersection constituents are never considered to have an inferred index signature
64890                     return membersRelatedToIndexInfo(source, targetInfo, reportErrors);
64891                 }
64892                 if (reportErrors) {
64893                     reportError(ts.Diagnostics.Index_signature_for_type_0_is_missing_in_type_1, typeToString(targetInfo.keyType), typeToString(source));
64894                 }
64895                 return 0 /* False */;
64896             }
64897             function indexSignaturesIdenticalTo(source, target) {
64898                 var sourceInfos = getIndexInfosOfType(source);
64899                 var targetInfos = getIndexInfosOfType(target);
64900                 if (sourceInfos.length !== targetInfos.length) {
64901                     return 0 /* False */;
64902                 }
64903                 for (var _i = 0, targetInfos_1 = targetInfos; _i < targetInfos_1.length; _i++) {
64904                     var targetInfo = targetInfos_1[_i];
64905                     var sourceInfo = getIndexInfoOfType(source, targetInfo.keyType);
64906                     if (!(sourceInfo && isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */) && sourceInfo.isReadonly === targetInfo.isReadonly)) {
64907                         return 0 /* False */;
64908                     }
64909                 }
64910                 return -1 /* True */;
64911             }
64912             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
64913                 if (!sourceSignature.declaration || !targetSignature.declaration) {
64914                     return true;
64915                 }
64916                 var sourceAccessibility = ts.getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
64917                 var targetAccessibility = ts.getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
64918                 // A public, protected and private signature is assignable to a private signature.
64919                 if (targetAccessibility === 8 /* Private */) {
64920                     return true;
64921                 }
64922                 // A public and protected signature is assignable to a protected signature.
64923                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
64924                     return true;
64925                 }
64926                 // Only a public signature is assignable to public signature.
64927                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
64928                     return true;
64929                 }
64930                 if (reportErrors) {
64931                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
64932                 }
64933                 return false;
64934             }
64935         }
64936         function typeCouldHaveTopLevelSingletonTypes(type) {
64937             // Okay, yes, 'boolean' is a union of 'true | false', but that's not useful
64938             // in error reporting scenarios. If you need to use this function but that detail matters,
64939             // feel free to add a flag.
64940             if (type.flags & 16 /* Boolean */) {
64941                 return false;
64942             }
64943             if (type.flags & 3145728 /* UnionOrIntersection */) {
64944                 return !!ts.forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
64945             }
64946             if (type.flags & 465829888 /* Instantiable */) {
64947                 var constraint = getConstraintOfType(type);
64948                 if (constraint && constraint !== type) {
64949                     return typeCouldHaveTopLevelSingletonTypes(constraint);
64950                 }
64951             }
64952             return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */);
64953         }
64954         function getExactOptionalUnassignableProperties(source, target) {
64955             if (isTupleType(source) && isTupleType(target))
64956                 return ts.emptyArray;
64957             return getPropertiesOfType(target)
64958                 .filter(function (targetProp) { return isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp)); });
64959         }
64960         function isExactOptionalPropertyMismatch(source, target) {
64961             return !!source && !!target && maybeTypeOfKind(source, 32768 /* Undefined */) && !!containsMissingType(target);
64962         }
64963         function getExactOptionalProperties(type) {
64964             return getPropertiesOfType(type).filter(function (targetProp) { return containsMissingType(getTypeOfSymbol(targetProp)); });
64965         }
64966         function getBestMatchingType(source, target, isRelatedTo) {
64967             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
64968             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
64969                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
64970                 findBestTypeForObjectLiteral(source, target) ||
64971                 findBestTypeForInvokable(source, target) ||
64972                 findMostOverlappyType(source, target);
64973         }
64974         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
64975             // undefined=unknown, true=discriminated, false=not discriminated
64976             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
64977             var discriminable = target.types.map(function (_) { return undefined; });
64978             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
64979                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
64980                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
64981                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
64982                     continue;
64983                 }
64984                 var i = 0;
64985                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
64986                     var type = _c[_b];
64987                     var targetType = getTypeOfPropertyOfType(type, propertyName);
64988                     if (targetType && related(getDiscriminatingType(), targetType)) {
64989                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
64990                     }
64991                     else {
64992                         discriminable[i] = false;
64993                     }
64994                     i++;
64995                 }
64996             }
64997             var match = discriminable.indexOf(/*searchElement*/ true);
64998             if (match === -1) {
64999                 return defaultValue;
65000             }
65001             // make sure exactly 1 matches before returning it
65002             var nextMatch = discriminable.indexOf(/*searchElement*/ true, match + 1);
65003             while (nextMatch !== -1) {
65004                 if (!isTypeIdenticalTo(target.types[match], target.types[nextMatch])) {
65005                     return defaultValue;
65006                 }
65007                 nextMatch = discriminable.indexOf(/*searchElement*/ true, nextMatch + 1);
65008             }
65009             return target.types[match];
65010         }
65011         /**
65012          * A type is 'weak' if it is an object type with at least one optional property
65013          * and no required properties, call/construct signatures or index signatures
65014          */
65015         function isWeakType(type) {
65016             if (type.flags & 524288 /* Object */) {
65017                 var resolved = resolveStructuredTypeMembers(type);
65018                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 &&
65019                     resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
65020             }
65021             if (type.flags & 2097152 /* Intersection */) {
65022                 return ts.every(type.types, isWeakType);
65023             }
65024             return false;
65025         }
65026         function hasCommonProperties(source, target, isComparingJsxAttributes) {
65027             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
65028                 var prop = _a[_i];
65029                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
65030                     return true;
65031                 }
65032             }
65033             return false;
65034         }
65035         // Return a type reference where the source type parameter is replaced with the target marker
65036         // type, and flag the result as a marker type reference.
65037         function getMarkerTypeReference(type, source, target) {
65038             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
65039             result.objectFlags |= 4096 /* MarkerType */;
65040             return result;
65041         }
65042         function getAliasVariances(symbol) {
65043             var links = getSymbolLinks(symbol);
65044             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
65045                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
65046                 type.aliasTypeArgumentsContainsMarker = true;
65047                 return type;
65048             });
65049         }
65050         // Return an array containing the variance of each type parameter. The variance is effectively
65051         // a digest of the type comparisons that occur for each type argument when instantiations of the
65052         // generic type are structurally compared. We infer the variance information by comparing
65053         // instantiations of the generic type for type arguments with known relations. The function
65054         // returns the emptyArray singleton when invoked recursively for the given generic type.
65055         function getVariancesWorker(typeParameters, cache, createMarkerType) {
65056             var _a, _b, _c;
65057             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
65058             var variances = cache.variances;
65059             if (!variances) {
65060                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "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 });
65061                 // The emptyArray singleton is used to signal a recursive invocation.
65062                 cache.variances = ts.emptyArray;
65063                 variances = [];
65064                 var _loop_21 = function (tp) {
65065                     var unmeasurable = false;
65066                     var unreliable = false;
65067                     var oldHandler = outofbandVarianceMarkerHandler;
65068                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
65069                     // We first compare instantiations where the type parameter is replaced with
65070                     // marker types that have a known subtype relationship. From this we can infer
65071                     // invariance, covariance, contravariance or bivariance.
65072                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
65073                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
65074                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
65075                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
65076                     // If the instantiations appear to be related bivariantly it may be because the
65077                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
65078                     // type). To determine this we compare instantiations where the type parameter is
65079                     // replaced with marker types that are known to be unrelated.
65080                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
65081                         variance = 4 /* Independent */;
65082                     }
65083                     outofbandVarianceMarkerHandler = oldHandler;
65084                     if (unmeasurable || unreliable) {
65085                         if (unmeasurable) {
65086                             variance |= 8 /* Unmeasurable */;
65087                         }
65088                         if (unreliable) {
65089                             variance |= 16 /* Unreliable */;
65090                         }
65091                     }
65092                     variances.push(variance);
65093                 };
65094                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
65095                     var tp = typeParameters_1[_i];
65096                     _loop_21(tp);
65097                 }
65098                 cache.variances = variances;
65099                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
65100             }
65101             return variances;
65102         }
65103         function getVariances(type) {
65104             // Arrays and tuples are known to be covariant, no need to spend time computing this.
65105             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
65106                 return arrayVariances;
65107             }
65108             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
65109         }
65110         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
65111         // See comment at call in recursiveTypeRelatedTo for when this case matters.
65112         function hasCovariantVoidArgument(typeArguments, variances) {
65113             for (var i = 0; i < variances.length; i++) {
65114                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
65115                     return true;
65116                 }
65117             }
65118             return false;
65119         }
65120         function isUnconstrainedTypeParameter(type) {
65121             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
65122         }
65123         function isNonDeferredTypeReference(type) {
65124             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
65125         }
65126         function isTypeReferenceWithGenericArguments(type) {
65127             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); });
65128         }
65129         /**
65130          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
65131          *   where A.id=111 and number.id=12
65132          */
65133         function getTypeReferenceId(type, typeParameters, depth) {
65134             if (depth === void 0) { depth = 0; }
65135             var result = "" + type.target.id;
65136             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
65137                 var t = _a[_i];
65138                 if (isUnconstrainedTypeParameter(t)) {
65139                     var index = typeParameters.indexOf(t);
65140                     if (index < 0) {
65141                         index = typeParameters.length;
65142                         typeParameters.push(t);
65143                     }
65144                     result += "=" + index;
65145                 }
65146                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
65147                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
65148                 }
65149                 else {
65150                     result += "-" + t.id;
65151                 }
65152             }
65153             return result;
65154         }
65155         /**
65156          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
65157          * For other cases, the types ids are used.
65158          */
65159         function getRelationKey(source, target, intersectionState, relation) {
65160             if (relation === identityRelation && source.id > target.id) {
65161                 var temp = source;
65162                 source = target;
65163                 target = temp;
65164             }
65165             var postFix = intersectionState ? ":" + intersectionState : "";
65166             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
65167                 var typeParameters = [];
65168                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
65169             }
65170             return source.id + "," + target.id + postFix;
65171         }
65172         // Invoke the callback for each underlying property symbol of the given symbol and return the first
65173         // value that isn't undefined.
65174         function forEachProperty(prop, callback) {
65175             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
65176                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
65177                     var t = _a[_i];
65178                     var p = getPropertyOfType(t, prop.escapedName);
65179                     var result = p && forEachProperty(p, callback);
65180                     if (result) {
65181                         return result;
65182                     }
65183                 }
65184                 return undefined;
65185             }
65186             return callback(prop);
65187         }
65188         // Return the declaring class type of a property or undefined if property not declared in class
65189         function getDeclaringClass(prop) {
65190             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
65191         }
65192         // Return the inherited type of the given property or undefined if property doesn't exist in a base class.
65193         function getTypeOfPropertyInBaseClass(property) {
65194             var classType = getDeclaringClass(property);
65195             var baseClassType = classType && getBaseTypes(classType)[0];
65196             return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
65197         }
65198         // Return true if some underlying source property is declared in a class that derives
65199         // from the given base class.
65200         function isPropertyInClassDerivedFrom(prop, baseClass) {
65201             return forEachProperty(prop, function (sp) {
65202                 var sourceClass = getDeclaringClass(sp);
65203                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
65204             });
65205         }
65206         // Return true if source property is a valid override of protected parts of target property.
65207         function isValidOverrideOf(sourceProp, targetProp) {
65208             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
65209                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
65210         }
65211         // Return true if the given class derives from each of the declaring classes of the protected
65212         // constituents of the given property.
65213         function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) {
65214             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ?
65215                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
65216         }
65217         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
65218         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
65219         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
65220         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
65221         // levels, but unequal at some level beyond that.
65222         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
65223         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
65224         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
65225         // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of
65226         // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]`
65227         // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`
65228         // in such cases we need to terminate the expansion, and we do so here.
65229         function isDeeplyNestedType(type, stack, depth, maxDepth) {
65230             if (maxDepth === void 0) { maxDepth = 5; }
65231             if (depth >= maxDepth) {
65232                 var identity_1 = getRecursionIdentity(type);
65233                 var count = 0;
65234                 for (var i = 0; i < depth; i++) {
65235                     if (getRecursionIdentity(stack[i]) === identity_1) {
65236                         count++;
65237                         if (count >= maxDepth) {
65238                             return true;
65239                         }
65240                     }
65241                 }
65242             }
65243             return false;
65244         }
65245         // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type.
65246         // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with
65247         // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all
65248         // instantiations of that type have the same recursion identity. The default recursion identity is the object
65249         // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly
65250         // reference the type have a recursion identity that differs from the object identity.
65251         function getRecursionIdentity(type) {
65252             // Object and array literals are known not to contain recursive references and don't need a recursion identity.
65253             if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
65254                 if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) {
65255                     // Deferred type references are tracked through their associated AST node. This gives us finer
65256                     // granularity than using their associated target because each manifest type reference has a
65257                     // unique AST node.
65258                     return type.node;
65259                 }
65260                 if (type.symbol && !(ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
65261                     // We track all object types that have an associated symbol (representing the origin of the type), but
65262                     // exclude the static side of classes from this check since it shares its symbol with the instance side.
65263                     return type.symbol;
65264                 }
65265                 if (isTupleType(type)) {
65266                     // Tuple types are tracked through their target type
65267                     return type.target;
65268                 }
65269             }
65270             if (type.flags & 262144 /* TypeParameter */) {
65271                 return type.symbol;
65272             }
65273             if (type.flags & 8388608 /* IndexedAccess */) {
65274                 // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A
65275                 do {
65276                     type = type.objectType;
65277                 } while (type.flags & 8388608 /* IndexedAccess */);
65278                 return type;
65279             }
65280             if (type.flags & 16777216 /* Conditional */) {
65281                 // The root object represents the origin of the conditional type
65282                 return type.root;
65283             }
65284             return type;
65285         }
65286         function isPropertyIdenticalTo(sourceProp, targetProp) {
65287             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
65288         }
65289         function compareProperties(sourceProp, targetProp, compareTypes) {
65290             // Two members are considered identical when
65291             // - they are public properties with identical names, optionality, and types,
65292             // - they are private or protected properties originating in the same declaration and having identical types
65293             if (sourceProp === targetProp) {
65294                 return -1 /* True */;
65295             }
65296             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
65297             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
65298             if (sourcePropAccessibility !== targetPropAccessibility) {
65299                 return 0 /* False */;
65300             }
65301             if (sourcePropAccessibility) {
65302                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
65303                     return 0 /* False */;
65304                 }
65305             }
65306             else {
65307                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
65308                     return 0 /* False */;
65309                 }
65310             }
65311             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
65312                 return 0 /* False */;
65313             }
65314             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
65315         }
65316         function isMatchingSignature(source, target, partialMatch) {
65317             var sourceParameterCount = getParameterCount(source);
65318             var targetParameterCount = getParameterCount(target);
65319             var sourceMinArgumentCount = getMinArgumentCount(source);
65320             var targetMinArgumentCount = getMinArgumentCount(target);
65321             var sourceHasRestParameter = hasEffectiveRestParameter(source);
65322             var targetHasRestParameter = hasEffectiveRestParameter(target);
65323             // A source signature matches a target signature if the two signatures have the same number of required,
65324             // optional, and rest parameters.
65325             if (sourceParameterCount === targetParameterCount &&
65326                 sourceMinArgumentCount === targetMinArgumentCount &&
65327                 sourceHasRestParameter === targetHasRestParameter) {
65328                 return true;
65329             }
65330             // A source signature partially matches a target signature if the target signature has no fewer required
65331             // parameters
65332             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
65333                 return true;
65334             }
65335             return false;
65336         }
65337         /**
65338          * See signatureRelatedTo, compareSignaturesIdentical
65339          */
65340         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
65341             // TODO (drosen): De-duplicate code between related functions.
65342             if (source === target) {
65343                 return -1 /* True */;
65344             }
65345             if (!(isMatchingSignature(source, target, partialMatch))) {
65346                 return 0 /* False */;
65347             }
65348             // Check that the two signatures have the same number of type parameters.
65349             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
65350                 return 0 /* False */;
65351             }
65352             // Check that type parameter constraints and defaults match. If they do, instantiate the source
65353             // signature with the type parameters of the target signature and continue the comparison.
65354             if (target.typeParameters) {
65355                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
65356                 for (var i = 0; i < target.typeParameters.length; i++) {
65357                     var s = source.typeParameters[i];
65358                     var t = target.typeParameters[i];
65359                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
65360                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
65361                         return 0 /* False */;
65362                     }
65363                 }
65364                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
65365             }
65366             var result = -1 /* True */;
65367             if (!ignoreThisTypes) {
65368                 var sourceThisType = getThisTypeOfSignature(source);
65369                 if (sourceThisType) {
65370                     var targetThisType = getThisTypeOfSignature(target);
65371                     if (targetThisType) {
65372                         var related = compareTypes(sourceThisType, targetThisType);
65373                         if (!related) {
65374                             return 0 /* False */;
65375                         }
65376                         result &= related;
65377                     }
65378                 }
65379             }
65380             var targetLen = getParameterCount(target);
65381             for (var i = 0; i < targetLen; i++) {
65382                 var s = getTypeAtPosition(source, i);
65383                 var t = getTypeAtPosition(target, i);
65384                 var related = compareTypes(t, s);
65385                 if (!related) {
65386                     return 0 /* False */;
65387                 }
65388                 result &= related;
65389             }
65390             if (!ignoreReturnTypes) {
65391                 var sourceTypePredicate = getTypePredicateOfSignature(source);
65392                 var targetTypePredicate = getTypePredicateOfSignature(target);
65393                 result &= sourceTypePredicate || targetTypePredicate ?
65394                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
65395                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
65396             }
65397             return result;
65398         }
65399         function compareTypePredicatesIdentical(source, target, compareTypes) {
65400             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
65401                 source.type === target.type ? -1 /* True */ :
65402                     source.type && target.type ? compareTypes(source.type, target.type) :
65403                         0 /* False */;
65404         }
65405         function literalTypesWithSameBaseType(types) {
65406             var commonBaseType;
65407             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
65408                 var t = types_13[_i];
65409                 var baseType = getBaseTypeOfLiteralType(t);
65410                 if (!commonBaseType) {
65411                     commonBaseType = baseType;
65412                 }
65413                 if (baseType === t || baseType !== commonBaseType) {
65414                     return false;
65415                 }
65416             }
65417             return true;
65418         }
65419         // When the candidate types are all literal types with the same base type, return a union
65420         // of those literal types. Otherwise, return the leftmost type for which no type to the
65421         // right is a supertype.
65422         function getSupertypeOrUnion(types) {
65423             if (types.length === 1) {
65424                 return types[0];
65425             }
65426             return literalTypesWithSameBaseType(types) ?
65427                 getUnionType(types) :
65428                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
65429         }
65430         function getCommonSupertype(types) {
65431             if (!strictNullChecks) {
65432                 return getSupertypeOrUnion(types);
65433             }
65434             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
65435             return primaryTypes.length ?
65436                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
65437                 getUnionType(types, 2 /* Subtype */);
65438         }
65439         // Return the leftmost type for which no type to the right is a subtype.
65440         function getCommonSubtype(types) {
65441             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
65442         }
65443         function isArrayType(type) {
65444             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
65445         }
65446         function isReadonlyArrayType(type) {
65447             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
65448         }
65449         function isMutableArrayOrTuple(type) {
65450             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
65451         }
65452         function getElementTypeOfArrayType(type) {
65453             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
65454         }
65455         function isArrayLikeType(type) {
65456             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
65457             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
65458             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
65459         }
65460         function getSingleBaseForNonAugmentingSubtype(type) {
65461             if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) {
65462                 return undefined;
65463             }
65464             if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) {
65465                 return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined;
65466             }
65467             type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */;
65468             var target = type.target;
65469             if (ts.getObjectFlags(target) & 1 /* Class */) {
65470                 var baseTypeNode = getBaseTypeNodeOfClass(target);
65471                 // A base type expression may circularly reference the class itself (e.g. as an argument to function call), so we only
65472                 // check for base types specified as simple qualified names.
65473                 if (baseTypeNode && baseTypeNode.expression.kind !== 79 /* Identifier */ && baseTypeNode.expression.kind !== 205 /* PropertyAccessExpression */) {
65474                     return undefined;
65475                 }
65476             }
65477             var bases = getBaseTypes(target);
65478             if (bases.length !== 1) {
65479                 return undefined;
65480             }
65481             if (getMembersOfSymbol(type.symbol).size) {
65482                 return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison
65483             }
65484             var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length)));
65485             if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) {
65486                 instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type)));
65487             }
65488             type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */;
65489             return type.cachedEquivalentBaseType = instantiatedBase;
65490         }
65491         function isEmptyLiteralType(type) {
65492             return strictNullChecks ? type === implicitNeverType : type === undefinedWideningType;
65493         }
65494         function isEmptyArrayLiteralType(type) {
65495             var elementType = getElementTypeOfArrayType(type);
65496             return !!elementType && isEmptyLiteralType(elementType);
65497         }
65498         function isTupleLikeType(type) {
65499             return isTupleType(type) || !!getPropertyOfType(type, "0");
65500         }
65501         function isArrayOrTupleLikeType(type) {
65502             return isArrayLikeType(type) || isTupleLikeType(type);
65503         }
65504         function getTupleElementType(type, index) {
65505             var propType = getTypeOfPropertyOfType(type, "" + index);
65506             if (propType) {
65507                 return propType;
65508             }
65509             if (everyType(type, isTupleType)) {
65510                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
65511             }
65512             return undefined;
65513         }
65514         function isNeitherUnitTypeNorNever(type) {
65515             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
65516         }
65517         function isUnitType(type) {
65518             return !!(type.flags & 109440 /* Unit */);
65519         }
65520         function isUnitLikeType(type) {
65521             return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) :
65522                 !!(type.flags & 109440 /* Unit */);
65523         }
65524         function extractUnitType(type) {
65525             return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type;
65526         }
65527         function isLiteralType(type) {
65528             return type.flags & 16 /* Boolean */ ? true :
65529                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
65530                     isUnitType(type);
65531         }
65532         function getBaseTypeOfLiteralType(type) {
65533             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
65534                 type.flags & 128 /* StringLiteral */ ? stringType :
65535                     type.flags & 256 /* NumberLiteral */ ? numberType :
65536                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
65537                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
65538                                 type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralType) :
65539                                     type;
65540         }
65541         function getWidenedLiteralType(type) {
65542             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
65543                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
65544                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
65545                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
65546                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
65547                                 type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) :
65548                                     type;
65549         }
65550         function getWidenedUniqueESSymbolType(type) {
65551             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
65552                 type.flags & 1048576 /* Union */ ? mapType(type, getWidenedUniqueESSymbolType) :
65553                     type;
65554         }
65555         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
65556             if (!isLiteralOfContextualType(type, contextualType)) {
65557                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
65558             }
65559             return type;
65560         }
65561         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
65562             if (type && isUnitType(type)) {
65563                 var contextualType = !contextualSignatureReturnType ? undefined :
65564                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
65565                         contextualSignatureReturnType;
65566                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
65567             }
65568             return type;
65569         }
65570         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
65571             if (type && isUnitType(type)) {
65572                 var contextualType = !contextualSignatureReturnType ? undefined :
65573                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
65574                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
65575             }
65576             return type;
65577         }
65578         /**
65579          * Check if a Type was written as a tuple type literal.
65580          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
65581          */
65582         function isTupleType(type) {
65583             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
65584         }
65585         function isGenericTupleType(type) {
65586             return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
65587         }
65588         function isSingleElementGenericTupleType(type) {
65589             return isGenericTupleType(type) && type.target.elementFlags.length === 1;
65590         }
65591         function getRestTypeOfTupleType(type) {
65592             return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
65593         }
65594         function getRestArrayTypeOfTupleType(type) {
65595             var restType = getRestTypeOfTupleType(type);
65596             return restType && createArrayType(restType);
65597         }
65598         function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
65599             if (endSkipCount === void 0) { endSkipCount = 0; }
65600             if (writing === void 0) { writing = false; }
65601             var length = getTypeReferenceArity(type) - endSkipCount;
65602             if (index < length) {
65603                 var typeArguments = getTypeArguments(type);
65604                 var elementTypes = [];
65605                 for (var i = index; i < length; i++) {
65606                     var t = typeArguments[i];
65607                     elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
65608                 }
65609                 return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes);
65610             }
65611             return undefined;
65612         }
65613         function isTupleTypeStructureMatching(t1, t2) {
65614             return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) &&
65615                 ts.every(t1.target.elementFlags, function (f, i) { return (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */); });
65616         }
65617         function isZeroBigInt(_a) {
65618             var value = _a.value;
65619             return value.base10Value === "0";
65620         }
65621         function getFalsyFlagsOfTypes(types) {
65622             var result = 0;
65623             for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
65624                 var t = types_14[_i];
65625                 result |= getFalsyFlags(t);
65626             }
65627             return result;
65628         }
65629         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
65630         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
65631         // no flags for all other types (including non-falsy literal types).
65632         function getFalsyFlags(type) {
65633             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
65634                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
65635                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
65636                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
65637                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
65638                                 type.flags & 117724 /* PossiblyFalsy */;
65639         }
65640         function removeDefinitelyFalsyTypes(type) {
65641             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
65642                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
65643                 type;
65644         }
65645         function extractDefinitelyFalsyTypes(type) {
65646             return mapType(type, getDefinitelyFalsyPartOfType);
65647         }
65648         function getDefinitelyFalsyPartOfType(type) {
65649             return type.flags & 4 /* String */ ? emptyStringType :
65650                 type.flags & 8 /* Number */ ? zeroType :
65651                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
65652                         type === regularFalseType ||
65653                             type === falseType ||
65654                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) ||
65655                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
65656                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
65657                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
65658                             neverType;
65659         }
65660         /**
65661          * Add undefined or null or both to a type if they are missing.
65662          * @param type - type to add undefined and/or null to if not present
65663          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
65664          */
65665         function getNullableType(type, flags) {
65666             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
65667             return missing === 0 ? type :
65668                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
65669                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
65670                         getUnionType([type, undefinedType, nullType]);
65671         }
65672         function getOptionalType(type, isProperty) {
65673             if (isProperty === void 0) { isProperty = false; }
65674             ts.Debug.assert(strictNullChecks);
65675             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]);
65676         }
65677         function getGlobalNonNullableTypeInstantiation(type) {
65678             // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates
65679             // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null'
65680             // that isn't eliminated by a NonNullable<T> instantiation.
65681             var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
65682             if (!deferredGlobalNonNullableTypeAlias) {
65683                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
65684             }
65685             // If the NonNullable<T> type is available, return an instantiation. Otherwise just return the reduced type.
65686             return deferredGlobalNonNullableTypeAlias !== unknownSymbol ?
65687                 getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) :
65688                 reducedType;
65689         }
65690         function getNonNullableType(type) {
65691             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
65692         }
65693         function addOptionalTypeMarker(type) {
65694             return strictNullChecks ? getUnionType([type, optionalType]) : type;
65695         }
65696         function removeOptionalTypeMarker(type) {
65697             return strictNullChecks ? removeType(type, optionalType) : type;
65698         }
65699         function propagateOptionalTypeMarker(type, node, wasOptional) {
65700             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
65701         }
65702         function getOptionalExpressionType(exprType, expression) {
65703             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
65704                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
65705                     exprType;
65706         }
65707         function removeMissingType(type, isOptional) {
65708             return exactOptionalPropertyTypes && isOptional ? removeType(type, missingType) : type;
65709         }
65710         function containsMissingType(type) {
65711             return exactOptionalPropertyTypes && (type === missingType || type.flags & 1048576 /* Union */ && containsType(type.types, missingType));
65712         }
65713         function removeMissingOrUndefinedType(type) {
65714             return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */);
65715         }
65716         /**
65717          * Is source potentially coercible to target type under `==`.
65718          * Assumes that `source` is a constituent of a union, hence
65719          * the boolean literal flag on the LHS, but not on the RHS.
65720          *
65721          * This does not fully replicate the semantics of `==`. The
65722          * intention is to catch cases that are clearly not right.
65723          *
65724          * Comparing (string | number) to number should not remove the
65725          * string element.
65726          *
65727          * Comparing (string | number) to 1 will remove the string
65728          * element, though this is not sound. This is a pragmatic
65729          * choice.
65730          *
65731          * @see narrowTypeByEquality
65732          *
65733          * @param source
65734          * @param target
65735          */
65736         function isCoercibleUnderDoubleEquals(source, target) {
65737             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
65738                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
65739         }
65740         /**
65741          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
65742          * with no call or construct signatures.
65743          */
65744         function isObjectTypeWithInferableIndex(type) {
65745             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
65746                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
65747                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
65748         }
65749         function createSymbolWithType(source, type) {
65750             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
65751             symbol.declarations = source.declarations;
65752             symbol.parent = source.parent;
65753             symbol.type = type;
65754             symbol.target = source;
65755             if (source.valueDeclaration) {
65756                 symbol.valueDeclaration = source.valueDeclaration;
65757             }
65758             var nameType = getSymbolLinks(source).nameType;
65759             if (nameType) {
65760                 symbol.nameType = nameType;
65761             }
65762             return symbol;
65763         }
65764         function transformTypeOfMembers(type, f) {
65765             var members = ts.createSymbolTable();
65766             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
65767                 var property = _a[_i];
65768                 var original = getTypeOfSymbol(property);
65769                 var updated = f(original);
65770                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
65771             }
65772             return members;
65773         }
65774         /**
65775          * If the the provided object literal is subject to the excess properties check,
65776          * create a new that is exempt. Recursively mark object literal members as exempt.
65777          * Leave signatures alone since they are not subject to the check.
65778          */
65779         function getRegularTypeOfObjectLiteral(type) {
65780             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) {
65781                 return type;
65782             }
65783             var regularType = type.regularType;
65784             if (regularType) {
65785                 return regularType;
65786             }
65787             var resolved = type;
65788             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
65789             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.indexInfos);
65790             regularNew.flags = resolved.flags;
65791             regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */;
65792             type.regularType = regularNew;
65793             return regularNew;
65794         }
65795         function createWideningContext(parent, propertyName, siblings) {
65796             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
65797         }
65798         function getSiblingsOfContext(context) {
65799             if (!context.siblings) {
65800                 var siblings_1 = [];
65801                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
65802                     var type = _a[_i];
65803                     if (isObjectLiteralType(type)) {
65804                         var prop = getPropertyOfObjectType(type, context.propertyName);
65805                         if (prop) {
65806                             forEachType(getTypeOfSymbol(prop), function (t) {
65807                                 siblings_1.push(t);
65808                             });
65809                         }
65810                     }
65811                 }
65812                 context.siblings = siblings_1;
65813             }
65814             return context.siblings;
65815         }
65816         function getPropertiesOfContext(context) {
65817             if (!context.resolvedProperties) {
65818                 var names = new ts.Map();
65819                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
65820                     var t = _a[_i];
65821                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) {
65822                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
65823                             var prop = _c[_b];
65824                             names.set(prop.escapedName, prop);
65825                         }
65826                     }
65827                 }
65828                 context.resolvedProperties = ts.arrayFrom(names.values());
65829             }
65830             return context.resolvedProperties;
65831         }
65832         function getWidenedProperty(prop, context) {
65833             if (!(prop.flags & 4 /* Property */)) {
65834                 // Since get accessors already widen their return value there is no need to
65835                 // widen accessor based properties here.
65836                 return prop;
65837             }
65838             var original = getTypeOfSymbol(prop);
65839             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
65840             var widened = getWidenedTypeWithContext(original, propContext);
65841             return widened === original ? prop : createSymbolWithType(prop, widened);
65842         }
65843         function getUndefinedProperty(prop) {
65844             var cached = undefinedProperties.get(prop.escapedName);
65845             if (cached) {
65846                 return cached;
65847             }
65848             var result = createSymbolWithType(prop, missingType);
65849             result.flags |= 16777216 /* Optional */;
65850             undefinedProperties.set(prop.escapedName, result);
65851             return result;
65852         }
65853         function getWidenedTypeOfObjectLiteral(type, context) {
65854             var members = ts.createSymbolTable();
65855             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
65856                 var prop = _a[_i];
65857                 members.set(prop.escapedName, getWidenedProperty(prop, context));
65858             }
65859             if (context) {
65860                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
65861                     var prop = _c[_b];
65862                     if (!members.has(prop.escapedName)) {
65863                         members.set(prop.escapedName, getUndefinedProperty(prop));
65864                     }
65865                 }
65866             }
65867             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, ts.sameMap(getIndexInfosOfType(type), function (info) { return createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly); }));
65868             result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
65869             return result;
65870         }
65871         function getWidenedType(type) {
65872             return getWidenedTypeWithContext(type, /*context*/ undefined);
65873         }
65874         function getWidenedTypeWithContext(type, context) {
65875             if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
65876                 if (context === undefined && type.widened) {
65877                     return type.widened;
65878                 }
65879                 var result = void 0;
65880                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
65881                     result = anyType;
65882                 }
65883                 else if (isObjectLiteralType(type)) {
65884                     result = getWidenedTypeOfObjectLiteral(type, context);
65885                 }
65886                 else if (type.flags & 1048576 /* Union */) {
65887                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
65888                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
65889                     // Widening an empty object literal transitions from a highly restrictive type to
65890                     // a highly inclusive one. For that reason we perform subtype reduction here if the
65891                     // union includes empty object types (e.g. reducing {} | string to just {}).
65892                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
65893                 }
65894                 else if (type.flags & 2097152 /* Intersection */) {
65895                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
65896                 }
65897                 else if (isArrayType(type) || isTupleType(type)) {
65898                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
65899                 }
65900                 if (result && context === undefined) {
65901                     type.widened = result;
65902                 }
65903                 return result || type;
65904             }
65905             return type;
65906         }
65907         /**
65908          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
65909          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
65910          * getWidenedType. But in some cases getWidenedType is called without reporting errors
65911          * (type argument inference is an example).
65912          *
65913          * The return value indicates whether an error was in fact reported. The particular circumstances
65914          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
65915          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
65916          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
65917          */
65918         function reportWideningErrorsInType(type) {
65919             var errorReported = false;
65920             if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
65921                 if (type.flags & 1048576 /* Union */) {
65922                     if (ts.some(type.types, isEmptyObjectType)) {
65923                         errorReported = true;
65924                     }
65925                     else {
65926                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
65927                             var t = _a[_i];
65928                             if (reportWideningErrorsInType(t)) {
65929                                 errorReported = true;
65930                             }
65931                         }
65932                     }
65933                 }
65934                 if (isArrayType(type) || isTupleType(type)) {
65935                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
65936                         var t = _c[_b];
65937                         if (reportWideningErrorsInType(t)) {
65938                             errorReported = true;
65939                         }
65940                     }
65941                 }
65942                 if (isObjectLiteralType(type)) {
65943                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
65944                         var p = _e[_d];
65945                         var t = getTypeOfSymbol(p);
65946                         if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
65947                             if (!reportWideningErrorsInType(t)) {
65948                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
65949                             }
65950                             errorReported = true;
65951                         }
65952                     }
65953                 }
65954             }
65955             return errorReported;
65956         }
65957         function reportImplicitAny(declaration, type, wideningKind) {
65958             var typeAsString = typeToString(getWidenedType(type));
65959             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
65960                 // Only report implicit any errors/suggestions in TS and ts-check JS files
65961                 return;
65962             }
65963             var diagnostic;
65964             switch (declaration.kind) {
65965                 case 220 /* BinaryExpression */:
65966                 case 166 /* PropertyDeclaration */:
65967                 case 165 /* PropertySignature */:
65968                     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;
65969                     break;
65970                 case 163 /* Parameter */:
65971                     var param = declaration;
65972                     if (ts.isIdentifier(param.name) &&
65973                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
65974                         param.parent.parameters.indexOf(param) > -1 &&
65975                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
65976                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
65977                         var newName = "arg" + param.parent.parameters.indexOf(param);
65978                         var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : "");
65979                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName);
65980                         return;
65981                     }
65982                     diagnostic = declaration.dotDotDotToken ?
65983                         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 :
65984                         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;
65985                     break;
65986                 case 202 /* BindingElement */:
65987                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
65988                     if (!noImplicitAny) {
65989                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
65990                         return;
65991                     }
65992                     break;
65993                 case 315 /* JSDocFunctionType */:
65994                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
65995                     return;
65996                 case 255 /* FunctionDeclaration */:
65997                 case 168 /* MethodDeclaration */:
65998                 case 167 /* MethodSignature */:
65999                 case 171 /* GetAccessor */:
66000                 case 172 /* SetAccessor */:
66001                 case 212 /* FunctionExpression */:
66002                 case 213 /* ArrowFunction */:
66003                     if (noImplicitAny && !declaration.name) {
66004                         if (wideningKind === 3 /* GeneratorYield */) {
66005                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
66006                         }
66007                         else {
66008                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
66009                         }
66010                         return;
66011                     }
66012                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
66013                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
66014                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
66015                     break;
66016                 case 194 /* MappedType */:
66017                     if (noImplicitAny) {
66018                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
66019                     }
66020                     return;
66021                 default:
66022                     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;
66023             }
66024             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
66025         }
66026         function reportErrorsFromWidening(declaration, type, wideningKind) {
66027             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
66028                 // Report implicit any error within type if possible, otherwise report error on declaration
66029                 if (!reportWideningErrorsInType(type)) {
66030                     reportImplicitAny(declaration, type, wideningKind);
66031                 }
66032             }
66033         }
66034         function applyToParameterTypes(source, target, callback) {
66035             var sourceCount = getParameterCount(source);
66036             var targetCount = getParameterCount(target);
66037             var sourceRestType = getEffectiveRestType(source);
66038             var targetRestType = getEffectiveRestType(target);
66039             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
66040             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
66041             var sourceThisType = getThisTypeOfSignature(source);
66042             if (sourceThisType) {
66043                 var targetThisType = getThisTypeOfSignature(target);
66044                 if (targetThisType) {
66045                     callback(sourceThisType, targetThisType);
66046                 }
66047             }
66048             for (var i = 0; i < paramCount; i++) {
66049                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
66050             }
66051             if (targetRestType) {
66052                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
66053             }
66054         }
66055         function applyToReturnTypes(source, target, callback) {
66056             var sourceTypePredicate = getTypePredicateOfSignature(source);
66057             var targetTypePredicate = getTypePredicateOfSignature(target);
66058             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
66059                 callback(sourceTypePredicate.type, targetTypePredicate.type);
66060             }
66061             else {
66062                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
66063             }
66064         }
66065         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
66066             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
66067         }
66068         function cloneInferenceContext(context, extraFlags) {
66069             if (extraFlags === void 0) { extraFlags = 0; }
66070             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
66071         }
66072         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
66073             var context = {
66074                 inferences: inferences,
66075                 signature: signature,
66076                 flags: flags,
66077                 compareTypes: compareTypes,
66078                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
66079                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
66080             };
66081             return context;
66082         }
66083         function mapToInferredType(context, t, fix) {
66084             var inferences = context.inferences;
66085             for (var i = 0; i < inferences.length; i++) {
66086                 var inference = inferences[i];
66087                 if (t === inference.typeParameter) {
66088                     if (fix && !inference.isFixed) {
66089                         clearCachedInferences(inferences);
66090                         inference.isFixed = true;
66091                     }
66092                     return getInferredType(context, i);
66093                 }
66094             }
66095             return t;
66096         }
66097         function clearCachedInferences(inferences) {
66098             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
66099                 var inference = inferences_1[_i];
66100                 if (!inference.isFixed) {
66101                     inference.inferredType = undefined;
66102                 }
66103             }
66104         }
66105         function createInferenceInfo(typeParameter) {
66106             return {
66107                 typeParameter: typeParameter,
66108                 candidates: undefined,
66109                 contraCandidates: undefined,
66110                 inferredType: undefined,
66111                 priority: undefined,
66112                 topLevel: true,
66113                 isFixed: false,
66114                 impliedArity: undefined
66115             };
66116         }
66117         function cloneInferenceInfo(inference) {
66118             return {
66119                 typeParameter: inference.typeParameter,
66120                 candidates: inference.candidates && inference.candidates.slice(),
66121                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
66122                 inferredType: inference.inferredType,
66123                 priority: inference.priority,
66124                 topLevel: inference.topLevel,
66125                 isFixed: inference.isFixed,
66126                 impliedArity: inference.impliedArity
66127             };
66128         }
66129         function cloneInferredPartOfContext(context) {
66130             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
66131             return inferences.length ?
66132                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
66133                 undefined;
66134         }
66135         function getMapperFromContext(context) {
66136             return context && context.mapper;
66137         }
66138         // Return true if the given type could possibly reference a type parameter for which
66139         // we perform type inference (i.e. a type parameter of a generic function). We cache
66140         // results for union and intersection types for performance reasons.
66141         function couldContainTypeVariables(type) {
66142             var objectFlags = ts.getObjectFlags(type);
66143             if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) {
66144                 return !!(objectFlags & 2097152 /* CouldContainTypeVariables */);
66145             }
66146             var result = !!(type.flags & 465829888 /* Instantiable */ ||
66147                 type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
66148                     objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
66149                     objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) ||
66150                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables));
66151             if (type.flags & 3899393 /* ObjectFlagsType */) {
66152                 type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0);
66153             }
66154             return result;
66155         }
66156         function isNonGenericTopLevelType(type) {
66157             if (type.aliasSymbol && !type.aliasTypeArguments) {
66158                 var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 258 /* TypeAliasDeclaration */);
66159                 return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 303 /* SourceFile */ ? true : n.kind === 260 /* ModuleDeclaration */ ? false : "quit"; }));
66160             }
66161             return false;
66162         }
66163         function isTypeParameterAtTopLevel(type, typeParameter) {
66164             return !!(type === typeParameter ||
66165                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
66166                 type.flags & 16777216 /* Conditional */ && (getTrueTypeFromConditionalType(type) === typeParameter || getFalseTypeFromConditionalType(type) === typeParameter));
66167         }
66168         /** Create an object with properties named in the string literal type. Every property has type `any` */
66169         function createEmptyObjectTypeFromStringLiteral(type) {
66170             var members = ts.createSymbolTable();
66171             forEachType(type, function (t) {
66172                 if (!(t.flags & 128 /* StringLiteral */)) {
66173                     return;
66174                 }
66175                 var name = ts.escapeLeadingUnderscores(t.value);
66176                 var literalProp = createSymbol(4 /* Property */, name);
66177                 literalProp.type = anyType;
66178                 if (t.symbol) {
66179                     literalProp.declarations = t.symbol.declarations;
66180                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
66181                 }
66182                 members.set(name, literalProp);
66183             });
66184             var indexInfos = type.flags & 4 /* String */ ? [createIndexInfo(stringType, emptyObjectType, /*isReadonly*/ false)] : ts.emptyArray;
66185             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfos);
66186         }
66187         /**
66188          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
66189          * an object type with the same set of properties as the source type, where the type of each
66190          * property is computed by inferring from the source property type to X for the type
66191          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
66192          */
66193         function inferTypeForHomomorphicMappedType(source, target, constraint) {
66194             if (inInferTypeForHomomorphicMappedType) {
66195                 return undefined;
66196             }
66197             var key = source.id + "," + target.id + "," + constraint.id;
66198             if (reverseMappedCache.has(key)) {
66199                 return reverseMappedCache.get(key);
66200             }
66201             inInferTypeForHomomorphicMappedType = true;
66202             var type = createReverseMappedType(source, target, constraint);
66203             inInferTypeForHomomorphicMappedType = false;
66204             reverseMappedCache.set(key, type);
66205             return type;
66206         }
66207         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
66208         // an object literal type with at least one property of an inferable type. For example, an object
66209         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
66210         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
66211         function isPartiallyInferableType(type) {
66212             return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) ||
66213                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) ||
66214                 isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType);
66215         }
66216         function createReverseMappedType(source, target, constraint) {
66217             // We consider a source type reverse mappable if it has a string index signature or if
66218             // it has one or more properties and is of a partially inferable type.
66219             if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
66220                 return undefined;
66221             }
66222             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
66223             // applied to the element type(s).
66224             if (isArrayType(source)) {
66225                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
66226             }
66227             if (isTupleType(source)) {
66228                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
66229                 var elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
66230                     ts.sameMap(source.target.elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
66231                     source.target.elementFlags;
66232                 return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
66233             }
66234             // For all other object types we infer a new object type where the reverse mapping has been
66235             // applied to the type of each property.
66236             var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
66237             reversed.source = source;
66238             reversed.mappedType = target;
66239             reversed.constraintType = constraint;
66240             return reversed;
66241         }
66242         function getTypeOfReverseMappedSymbol(symbol) {
66243             var links = getSymbolLinks(symbol);
66244             if (!links.type) {
66245                 links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
66246             }
66247             return links.type;
66248         }
66249         function inferReverseMappedType(sourceType, target, constraint) {
66250             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
66251             var templateType = getTemplateTypeFromMappedType(target);
66252             var inference = createInferenceInfo(typeParameter);
66253             inferTypes([inference], sourceType, templateType);
66254             return getTypeFromInference(inference) || unknownType;
66255         }
66256         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
66257             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
66258             return __generator(this, function (_a) {
66259                 switch (_a.label) {
66260                     case 0:
66261                         properties = getPropertiesOfType(target);
66262                         _i = 0, properties_2 = properties;
66263                         _a.label = 1;
66264                     case 1:
66265                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
66266                         targetProp = properties_2[_i];
66267                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
66268                         if (isStaticPrivateIdentifierProperty(targetProp)) {
66269                             return [3 /*break*/, 5];
66270                         }
66271                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
66272                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
66273                         if (!!sourceProp) return [3 /*break*/, 3];
66274                         return [4 /*yield*/, targetProp];
66275                     case 2:
66276                         _a.sent();
66277                         return [3 /*break*/, 5];
66278                     case 3:
66279                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
66280                         targetType = getTypeOfSymbol(targetProp);
66281                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
66282                         sourceType = getTypeOfSymbol(sourceProp);
66283                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
66284                         return [4 /*yield*/, targetProp];
66285                     case 4:
66286                         _a.sent();
66287                         _a.label = 5;
66288                     case 5:
66289                         _i++;
66290                         return [3 /*break*/, 1];
66291                     case 6: return [2 /*return*/];
66292                 }
66293             });
66294         }
66295         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
66296             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
66297             if (!result.done)
66298                 return result.value;
66299         }
66300         function tupleTypesDefinitelyUnrelated(source, target) {
66301             return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength ||
66302                 !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength);
66303         }
66304         function typesDefinitelyUnrelated(source, target) {
66305             // Two tuple types with incompatible arities are definitely unrelated.
66306             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
66307             return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
66308                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
66309                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ false);
66310         }
66311         function getTypeFromInference(inference) {
66312             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
66313                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
66314                     undefined;
66315         }
66316         function hasSkipDirectInferenceFlag(node) {
66317             return !!getNodeLinks(node).skipDirectInference;
66318         }
66319         function isFromInferenceBlockedSource(type) {
66320             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
66321         }
66322         function templateLiteralTypesDefinitelyUnrelated(source, target) {
66323             // Two template literal types with diffences in their starting or ending text spans are definitely unrelated.
66324             var sourceStart = source.texts[0];
66325             var targetStart = target.texts[0];
66326             var sourceEnd = source.texts[source.texts.length - 1];
66327             var targetEnd = target.texts[target.texts.length - 1];
66328             var startLen = Math.min(sourceStart.length, targetStart.length);
66329             var endLen = Math.min(sourceEnd.length, targetEnd.length);
66330             return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) ||
66331                 sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen);
66332         }
66333         function isValidBigIntString(s) {
66334             var scanner = ts.createScanner(99 /* ESNext */, /*skipTrivia*/ false);
66335             var success = true;
66336             scanner.setOnError(function () { return success = false; });
66337             scanner.setText(s + "n");
66338             var result = scanner.scan();
66339             if (result === 40 /* MinusToken */) {
66340                 result = scanner.scan();
66341             }
66342             var flags = scanner.getTokenFlags();
66343             // validate that
66344             // * scanning proceeded without error
66345             // * a bigint can be scanned, and that when it is scanned, it is
66346             // * the full length of the input string (so the scanner is one character beyond the augmented input length)
66347             // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input)
66348             return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */);
66349         }
66350         function isValidTypeForTemplateLiteralPlaceholder(source, target) {
66351             if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) {
66352                 return true;
66353             }
66354             if (source.flags & 128 /* StringLiteral */) {
66355                 var value = source.value;
66356                 return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) ||
66357                     target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) ||
66358                     target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName);
66359             }
66360             if (source.flags & 134217728 /* TemplateLiteral */) {
66361                 var texts = source.texts;
66362                 return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target);
66363             }
66364             return isTypeAssignableTo(source, target);
66365         }
66366         function inferTypesFromTemplateLiteralType(source, target) {
66367             return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) :
66368                 source.flags & 134217728 /* TemplateLiteral */ ?
66369                     ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) :
66370                         inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) :
66371                     undefined;
66372         }
66373         function isTypeMatchedByTemplateLiteralType(source, target) {
66374             var inferences = inferTypesFromTemplateLiteralType(source, target);
66375             return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); });
66376         }
66377         function getStringLikeTypeForType(type) {
66378             return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]);
66379         }
66380         // This function infers from the text parts and type parts of a source literal to a target template literal. The number
66381         // of text parts is always one more than the number of type parts, and a source string literal is treated as a source
66382         // with one text part and zero type parts. The function returns an array of inferred string or template literal types
66383         // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target.
66384         //
66385         // We first check that the starting source text part matches the starting target text part, and that the ending source
66386         // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding
66387         // a match for each in the source and inferring string or template literal types created from the segments of the source
66388         // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts
66389         // array and pos holds the current character position in the current text part.
66390         //
66391         // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e.
66392         //   sourceTexts = ['<<', '>.<', '-', '>>']
66393         //   sourceTypes = [string, number, number]
66394         //   target.texts = ['<', '.', '>']
66395         // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in
66396         // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus
66397         // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second
66398         // inference, the template literal type `<${number}-${number}>`.
66399         function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) {
66400             var lastSourceIndex = sourceTexts.length - 1;
66401             var sourceStartText = sourceTexts[0];
66402             var sourceEndText = sourceTexts[lastSourceIndex];
66403             var targetTexts = target.texts;
66404             var lastTargetIndex = targetTexts.length - 1;
66405             var targetStartText = targetTexts[0];
66406             var targetEndText = targetTexts[lastTargetIndex];
66407             if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length ||
66408                 !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText))
66409                 return undefined;
66410             var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length);
66411             var matches = [];
66412             var seg = 0;
66413             var pos = targetStartText.length;
66414             for (var i = 1; i < lastTargetIndex; i++) {
66415                 var delim = targetTexts[i];
66416                 if (delim.length > 0) {
66417                     var s = seg;
66418                     var p = pos;
66419                     while (true) {
66420                         p = getSourceText(s).indexOf(delim, p);
66421                         if (p >= 0)
66422                             break;
66423                         s++;
66424                         if (s === sourceTexts.length)
66425                             return undefined;
66426                         p = 0;
66427                     }
66428                     addMatch(s, p);
66429                     pos += delim.length;
66430                 }
66431                 else if (pos < getSourceText(seg).length) {
66432                     addMatch(seg, pos + 1);
66433                 }
66434                 else if (seg < lastSourceIndex) {
66435                     addMatch(seg + 1, 0);
66436                 }
66437                 else {
66438                     return undefined;
66439                 }
66440             }
66441             addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length);
66442             return matches;
66443             function getSourceText(index) {
66444                 return index < lastSourceIndex ? sourceTexts[index] : remainingEndText;
66445             }
66446             function addMatch(s, p) {
66447                 var matchType = s === seg ?
66448                     getStringLiteralType(getSourceText(s).slice(pos, p)) :
66449                     getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s), true), [getSourceText(s).slice(0, p)], false), sourceTypes.slice(seg, s));
66450                 matches.push(matchType);
66451                 seg = s;
66452                 pos = p;
66453             }
66454         }
66455         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
66456             if (priority === void 0) { priority = 0; }
66457             if (contravariant === void 0) { contravariant = false; }
66458             var bivariant = false;
66459             var propagationType;
66460             var inferencePriority = 2048 /* MaxValue */;
66461             var allowComplexConstraintInference = true;
66462             var visited;
66463             var sourceStack;
66464             var targetStack;
66465             var expandingFlags = 0 /* None */;
66466             inferFromTypes(originalSource, originalTarget);
66467             function inferFromTypes(source, target) {
66468                 if (!couldContainTypeVariables(target)) {
66469                     return;
66470                 }
66471                 if (source === wildcardType) {
66472                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
66473                     // referenced in the target type, so we record it as the propagation type and infer from the
66474                     // target to itself. Then, as we find candidates we substitute the propagation type.
66475                     var savePropagationType = propagationType;
66476                     propagationType = source;
66477                     inferFromTypes(target, target);
66478                     propagationType = savePropagationType;
66479                     return;
66480                 }
66481                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
66482                     // Source and target are types originating in the same generic type alias declaration.
66483                     // Simply infer from source type arguments to target type arguments.
66484                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
66485                     return;
66486                 }
66487                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
66488                     // When source and target are the same union or intersection type, just relate each constituent
66489                     // type to itself.
66490                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
66491                         var t = _a[_i];
66492                         inferFromTypes(t, t);
66493                     }
66494                     return;
66495                 }
66496                 if (target.flags & 1048576 /* Union */) {
66497                     // First, infer between identically matching source and target constituents and remove the
66498                     // matching types.
66499                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
66500                     // Next, infer between closely matching source and target constituents and remove
66501                     // the matching types. Types closely match when they are instantiations of the same
66502                     // object type or instantiations of the same type alias.
66503                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
66504                     if (targets.length === 0) {
66505                         return;
66506                     }
66507                     target = getUnionType(targets);
66508                     if (sources.length === 0) {
66509                         // All source constituents have been matched and there is nothing further to infer from.
66510                         // However, simply making no inferences is undesirable because it could ultimately mean
66511                         // inferring a type parameter constraint. Instead, make a lower priority inference from
66512                         // the full source to whatever remains in the target. For example, when inferring from
66513                         // string to 'string | T', make a lower priority inference of string for T.
66514                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
66515                         return;
66516                     }
66517                     source = getUnionType(sources);
66518                 }
66519                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
66520                     // We reduce intersection types only when they contain naked type parameters. For example, when
66521                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
66522                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
66523                     // string[] on the source side and infer string for T.
66524                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
66525                     // in such scenarios.
66526                     if (!(source.flags & 1048576 /* Union */)) {
66527                         // Infer between identically matching source and target constituents and remove the matching types.
66528                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
66529                         if (sources.length === 0 || targets.length === 0) {
66530                             return;
66531                         }
66532                         source = getIntersectionType(sources);
66533                         target = getIntersectionType(targets);
66534                     }
66535                 }
66536                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
66537                     target = getActualTypeVariable(target);
66538                 }
66539                 if (target.flags & 8650752 /* TypeVariable */) {
66540                     // If target is a type parameter, make an inference, unless the source type contains
66541                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
66542                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
66543                     // it as an inference candidate. Hopefully, a better candidate will come along that does
66544                     // not contain anyFunctionType when we come back to this argument for its second round
66545                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
66546                     // when constructing types from type parameters that had no inference candidates).
66547                     if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
66548                         (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
66549                         return;
66550                     }
66551                     var inference = getInferenceInfoForType(target);
66552                     if (inference) {
66553                         if (!inference.isFixed) {
66554                             if (inference.priority === undefined || priority < inference.priority) {
66555                                 inference.candidates = undefined;
66556                                 inference.contraCandidates = undefined;
66557                                 inference.topLevel = true;
66558                                 inference.priority = priority;
66559                             }
66560                             if (priority === inference.priority) {
66561                                 var candidate = propagationType || source;
66562                                 // We make contravariant inferences only if we are in a pure contravariant position,
66563                                 // i.e. only if we have not descended into a bivariant position.
66564                                 if (contravariant && !bivariant) {
66565                                     if (!ts.contains(inference.contraCandidates, candidate)) {
66566                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
66567                                         clearCachedInferences(inferences);
66568                                     }
66569                                 }
66570                                 else if (!ts.contains(inference.candidates, candidate)) {
66571                                     inference.candidates = ts.append(inference.candidates, candidate);
66572                                     clearCachedInferences(inferences);
66573                                 }
66574                             }
66575                             if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
66576                                 inference.topLevel = false;
66577                                 clearCachedInferences(inferences);
66578                             }
66579                         }
66580                         inferencePriority = Math.min(inferencePriority, priority);
66581                         return;
66582                     }
66583                     else {
66584                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
66585                         var simplified = getSimplifiedType(target, /*writing*/ false);
66586                         if (simplified !== target) {
66587                             invokeOnce(source, simplified, inferFromTypes);
66588                         }
66589                         else if (target.flags & 8388608 /* IndexedAccess */) {
66590                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
66591                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
66592                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
66593                             if (indexType.flags & 465829888 /* Instantiable */) {
66594                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
66595                                 if (simplified_1 && simplified_1 !== target) {
66596                                     invokeOnce(source, simplified_1, inferFromTypes);
66597                                 }
66598                             }
66599                         }
66600                     }
66601                 }
66602                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
66603                     !(source.node && target.node)) {
66604                     // If source and target are references to the same generic type, infer from type arguments
66605                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
66606                 }
66607                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
66608                     contravariant = !contravariant;
66609                     inferFromTypes(source.type, target.type);
66610                     contravariant = !contravariant;
66611                 }
66612                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
66613                     var empty = createEmptyObjectTypeFromStringLiteral(source);
66614                     contravariant = !contravariant;
66615                     inferWithPriority(empty, target.type, 256 /* LiteralKeyof */);
66616                     contravariant = !contravariant;
66617                 }
66618                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
66619                     inferFromTypes(source.objectType, target.objectType);
66620                     inferFromTypes(source.indexType, target.indexType);
66621                 }
66622                 else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
66623                     if (source.symbol === target.symbol) {
66624                         inferFromTypes(source.type, target.type);
66625                     }
66626                 }
66627                 else if (source.flags & 33554432 /* Substitution */) {
66628                     inferFromTypes(source.baseType, target);
66629                     var oldPriority = priority;
66630                     priority |= 4 /* SubstituteSource */;
66631                     inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority
66632                     priority = oldPriority;
66633                 }
66634                 else if (target.flags & 16777216 /* Conditional */) {
66635                     invokeOnce(source, target, inferToConditionalType);
66636                 }
66637                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
66638                     inferToMultipleTypes(source, target.types, target.flags);
66639                 }
66640                 else if (source.flags & 1048576 /* Union */) {
66641                     // Source is a union or intersection type, infer from each constituent type
66642                     var sourceTypes = source.types;
66643                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
66644                         var sourceType = sourceTypes_2[_e];
66645                         inferFromTypes(sourceType, target);
66646                     }
66647                 }
66648                 else if (target.flags & 134217728 /* TemplateLiteral */) {
66649                     inferToTemplateLiteralType(source, target);
66650                 }
66651                 else {
66652                     source = getReducedType(source);
66653                     if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
66654                         var apparentSource = getApparentType(source);
66655                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
66656                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
66657                         // with the simplified source.
66658                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
66659                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
66660                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
66661                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
66662                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
66663                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
66664                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
66665                             // remove this `allowComplexConstraintInference` flag.
66666                             allowComplexConstraintInference = false;
66667                             return inferFromTypes(apparentSource, target);
66668                         }
66669                         source = apparentSource;
66670                     }
66671                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
66672                         invokeOnce(source, target, inferFromObjectTypes);
66673                     }
66674                 }
66675             }
66676             function inferWithPriority(source, target, newPriority) {
66677                 var savePriority = priority;
66678                 priority |= newPriority;
66679                 inferFromTypes(source, target);
66680                 priority = savePriority;
66681             }
66682             function invokeOnce(source, target, action) {
66683                 var key = source.id + "," + target.id;
66684                 var status = visited && visited.get(key);
66685                 if (status !== undefined) {
66686                     inferencePriority = Math.min(inferencePriority, status);
66687                     return;
66688                 }
66689                 (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */);
66690                 var saveInferencePriority = inferencePriority;
66691                 inferencePriority = 2048 /* MaxValue */;
66692                 // We stop inferring and report a circularity if we encounter duplicate recursion identities on both
66693                 // the source side and the target side.
66694                 var saveExpandingFlags = expandingFlags;
66695                 var sourceIdentity = getRecursionIdentity(source);
66696                 var targetIdentity = getRecursionIdentity(target);
66697                 if (ts.contains(sourceStack, sourceIdentity))
66698                     expandingFlags |= 1 /* Source */;
66699                 if (ts.contains(targetStack, targetIdentity))
66700                     expandingFlags |= 2 /* Target */;
66701                 if (expandingFlags !== 3 /* Both */) {
66702                     (sourceStack || (sourceStack = [])).push(sourceIdentity);
66703                     (targetStack || (targetStack = [])).push(targetIdentity);
66704                     action(source, target);
66705                     targetStack.pop();
66706                     sourceStack.pop();
66707                 }
66708                 else {
66709                     inferencePriority = -1 /* Circularity */;
66710                 }
66711                 expandingFlags = saveExpandingFlags;
66712                 visited.set(key, inferencePriority);
66713                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
66714             }
66715             function inferFromMatchingTypes(sources, targets, matches) {
66716                 var matchedSources;
66717                 var matchedTargets;
66718                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
66719                     var t = targets_1[_i];
66720                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
66721                         var s = sources_1[_a];
66722                         if (matches(s, t)) {
66723                             inferFromTypes(s, t);
66724                             matchedSources = ts.appendIfUnique(matchedSources, s);
66725                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
66726                         }
66727                     }
66728                 }
66729                 return [
66730                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
66731                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
66732                 ];
66733             }
66734             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
66735                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
66736                 for (var i = 0; i < count; i++) {
66737                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
66738                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
66739                     }
66740                     else {
66741                         inferFromTypes(sourceTypes[i], targetTypes[i]);
66742                     }
66743                 }
66744             }
66745             function inferFromContravariantTypes(source, target) {
66746                 if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) {
66747                     contravariant = !contravariant;
66748                     inferFromTypes(source, target);
66749                     contravariant = !contravariant;
66750                 }
66751                 else {
66752                     inferFromTypes(source, target);
66753                 }
66754             }
66755             function getInferenceInfoForType(type) {
66756                 if (type.flags & 8650752 /* TypeVariable */) {
66757                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
66758                         var inference = inferences_2[_i];
66759                         if (type === inference.typeParameter) {
66760                             return inference;
66761                         }
66762                     }
66763                 }
66764                 return undefined;
66765             }
66766             function getSingleTypeVariableFromIntersectionTypes(types) {
66767                 var typeVariable;
66768                 for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
66769                     var type = types_15[_i];
66770                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
66771                     if (!t || typeVariable && t !== typeVariable) {
66772                         return undefined;
66773                     }
66774                     typeVariable = t;
66775                 }
66776                 return typeVariable;
66777             }
66778             function inferToMultipleTypes(source, targets, targetFlags) {
66779                 var typeVariableCount = 0;
66780                 if (targetFlags & 1048576 /* Union */) {
66781                     var nakedTypeVariable = void 0;
66782                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
66783                     var matched_1 = new Array(sources.length);
66784                     var inferenceCircularity = false;
66785                     // First infer to types that are not naked type variables. For each source type we
66786                     // track whether inferences were made from that particular type to some target with
66787                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
66788                     // parameter.
66789                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
66790                         var t = targets_2[_i];
66791                         if (getInferenceInfoForType(t)) {
66792                             nakedTypeVariable = t;
66793                             typeVariableCount++;
66794                         }
66795                         else {
66796                             for (var i = 0; i < sources.length; i++) {
66797                                 var saveInferencePriority = inferencePriority;
66798                                 inferencePriority = 2048 /* MaxValue */;
66799                                 inferFromTypes(sources[i], t);
66800                                 if (inferencePriority === priority)
66801                                     matched_1[i] = true;
66802                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
66803                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
66804                             }
66805                         }
66806                     }
66807                     if (typeVariableCount === 0) {
66808                         // If every target is an intersection of types containing a single naked type variable,
66809                         // make a lower priority inference to that type variable. This handles inferring from
66810                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
66811                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
66812                         if (intersectionTypeVariable) {
66813                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
66814                         }
66815                         return;
66816                     }
66817                     // If the target has a single naked type variable and no inference circularities were
66818                     // encountered above (meaning we explored the types fully), create a union of the source
66819                     // types from which no inferences have been made so far and infer from that union to the
66820                     // naked type variable.
66821                     if (typeVariableCount === 1 && !inferenceCircularity) {
66822                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
66823                         if (unmatched.length) {
66824                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
66825                             return;
66826                         }
66827                     }
66828                 }
66829                 else {
66830                     // We infer from types that are not naked type variables first so that inferences we
66831                     // make from nested naked type variables and given slightly higher priority by virtue
66832                     // of being first in the candidates array.
66833                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
66834                         var t = targets_3[_a];
66835                         if (getInferenceInfoForType(t)) {
66836                             typeVariableCount++;
66837                         }
66838                         else {
66839                             inferFromTypes(source, t);
66840                         }
66841                     }
66842                 }
66843                 // Inferences directly to naked type variables are given lower priority as they are
66844                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
66845                 // we want to infer string for T, not Promise<string> | string. For intersection types
66846                 // we only infer to single naked type variables.
66847                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
66848                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
66849                         var t = targets_4[_b];
66850                         if (getInferenceInfoForType(t)) {
66851                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
66852                         }
66853                     }
66854                 }
66855             }
66856             function inferToMappedType(source, target, constraintType) {
66857                 if (constraintType.flags & 1048576 /* Union */) {
66858                     var result = false;
66859                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
66860                         var type = _a[_i];
66861                         result = inferToMappedType(source, target, type) || result;
66862                     }
66863                     return result;
66864                 }
66865                 if (constraintType.flags & 4194304 /* Index */) {
66866                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
66867                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
66868                     // type and then make a secondary inference from that type to T. We make a secondary inference
66869                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
66870                     var inference = getInferenceInfoForType(constraintType.type);
66871                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
66872                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
66873                         if (inferredType) {
66874                             // We assign a lower priority to inferences made from types containing non-inferrable
66875                             // types because we may only have a partial result (i.e. we may have failed to make
66876                             // reverse inferences for some properties).
66877                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ?
66878                                 16 /* PartialHomomorphicMappedType */ :
66879                                 8 /* HomomorphicMappedType */);
66880                         }
66881                     }
66882                     return true;
66883                 }
66884                 if (constraintType.flags & 262144 /* TypeParameter */) {
66885                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
66886                     // parameter. First infer from 'keyof S' to K.
66887                     inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */);
66888                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
66889                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
66890                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
66891                     // Pick<T, K>.
66892                     var extendedConstraint = getConstraintOfType(constraintType);
66893                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
66894                         return true;
66895                     }
66896                     // If no inferences can be made to K's constraint, infer from a union of the property types
66897                     // in the source to the template type X.
66898                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
66899                     var indexTypes = ts.map(getIndexInfosOfType(source), function (info) { return info !== enumNumberIndexInfo ? info.type : neverType; });
66900                     inferFromTypes(getUnionType(ts.concatenate(propTypes, indexTypes)), getTemplateTypeFromMappedType(target));
66901                     return true;
66902                 }
66903                 return false;
66904             }
66905             function inferToConditionalType(source, target) {
66906                 if (source.flags & 16777216 /* Conditional */) {
66907                     inferFromTypes(source.checkType, target.checkType);
66908                     inferFromTypes(source.extendsType, target.extendsType);
66909                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
66910                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
66911                 }
66912                 else {
66913                     var savePriority = priority;
66914                     priority |= contravariant ? 64 /* ContravariantConditional */ : 0;
66915                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
66916                     inferToMultipleTypes(source, targetTypes, target.flags);
66917                     priority = savePriority;
66918                 }
66919             }
66920             function inferToTemplateLiteralType(source, target) {
66921                 var matches = inferTypesFromTemplateLiteralType(source, target);
66922                 var types = target.types;
66923                 // When the target template literal contains only placeholders (meaning that inference is intended to extract
66924                 // single characters and remainder strings) and inference fails to produce matches, we want to infer 'never' for
66925                 // each placeholder such that instantiation with the inferred value(s) produces 'never', a type for which an
66926                 // assignment check will fail. If we make no inferences, we'll likely end up with the constraint 'string' which,
66927                 // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might
66928                 // succeed. That would be a pointless and confusing outcome.
66929                 if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) {
66930                     for (var i = 0; i < types.length; i++) {
66931                         inferFromTypes(matches ? matches[i] : neverType, types[i]);
66932                     }
66933                 }
66934             }
66935             function inferFromObjectTypes(source, target) {
66936                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
66937                     // If source and target are references to the same generic type, infer from type arguments
66938                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
66939                     return;
66940                 }
66941                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
66942                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
66943                     // from S to T and from X to Y.
66944                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
66945                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
66946                     var sourceNameType = getNameTypeFromMappedType(source);
66947                     var targetNameType = getNameTypeFromMappedType(target);
66948                     if (sourceNameType && targetNameType)
66949                         inferFromTypes(sourceNameType, targetNameType);
66950                 }
66951                 if (ts.getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) {
66952                     var constraintType = getConstraintTypeFromMappedType(target);
66953                     if (inferToMappedType(source, target, constraintType)) {
66954                         return;
66955                     }
66956                 }
66957                 // Infer from the members of source and target only if the two types are possibly related
66958                 if (!typesDefinitelyUnrelated(source, target)) {
66959                     if (isArrayType(source) || isTupleType(source)) {
66960                         if (isTupleType(target)) {
66961                             var sourceArity = getTypeReferenceArity(source);
66962                             var targetArity = getTypeReferenceArity(target);
66963                             var elementTypes = getTypeArguments(target);
66964                             var elementFlags = target.target.elementFlags;
66965                             // When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
66966                             // to the same kind in each position), simply infer between the element types.
66967                             if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
66968                                 for (var i = 0; i < targetArity; i++) {
66969                                     inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
66970                                 }
66971                                 return;
66972                             }
66973                             var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
66974                             var endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0);
66975                             // Infer between starting fixed elements.
66976                             for (var i = 0; i < startLength; i++) {
66977                                 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
66978                             }
66979                             if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & 4 /* Rest */) {
66980                                 // Single rest element remains in source, infer from that to every element in target
66981                                 var restType = getTypeArguments(source)[startLength];
66982                                 for (var i = startLength; i < targetArity - endLength; i++) {
66983                                     inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]);
66984                                 }
66985                             }
66986                             else {
66987                                 var middleLength = targetArity - startLength - endLength;
66988                                 if (middleLength === 2 && elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */ && isTupleType(source)) {
66989                                     // Middle of target is [...T, ...U] and source is tuple type
66990                                     var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
66991                                     if (targetInfo && targetInfo.impliedArity !== undefined) {
66992                                         // Infer slices from source based on implied arity of T.
66993                                         inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
66994                                         inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]);
66995                                     }
66996                                 }
66997                                 else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
66998                                     // Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
66999                                     // If target ends in optional element(s), make a lower priority a speculative inference.
67000                                     var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
67001                                     var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, endLength) : createArrayType(getTypeArguments(source)[0]);
67002                                     inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
67003                                 }
67004                                 else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
67005                                     // Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
67006                                     var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, endLength) : getTypeArguments(source)[0];
67007                                     if (restType) {
67008                                         inferFromTypes(restType, elementTypes[startLength]);
67009                                     }
67010                                 }
67011                             }
67012                             // Infer between ending fixed elements
67013                             for (var i = 0; i < endLength; i++) {
67014                                 inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
67015                             }
67016                             return;
67017                         }
67018                         if (isArrayType(target)) {
67019                             inferFromIndexTypes(source, target);
67020                             return;
67021                         }
67022                     }
67023                     inferFromProperties(source, target);
67024                     inferFromSignatures(source, target, 0 /* Call */);
67025                     inferFromSignatures(source, target, 1 /* Construct */);
67026                     inferFromIndexTypes(source, target);
67027                 }
67028             }
67029             function inferFromProperties(source, target) {
67030                 var properties = getPropertiesOfObjectType(target);
67031                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
67032                     var targetProp = properties_3[_i];
67033                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
67034                     if (sourceProp) {
67035                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
67036                     }
67037                 }
67038             }
67039             function inferFromSignatures(source, target, kind) {
67040                 var sourceSignatures = getSignaturesOfType(source, kind);
67041                 var targetSignatures = getSignaturesOfType(target, kind);
67042                 var sourceLen = sourceSignatures.length;
67043                 var targetLen = targetSignatures.length;
67044                 var len = sourceLen < targetLen ? sourceLen : targetLen;
67045                 var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
67046                 for (var i = 0; i < len; i++) {
67047                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
67048                 }
67049             }
67050             function inferFromSignature(source, target, skipParameters) {
67051                 if (!skipParameters) {
67052                     var saveBivariant = bivariant;
67053                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
67054                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
67055                     bivariant = bivariant || kind === 168 /* MethodDeclaration */ || kind === 167 /* MethodSignature */ || kind === 170 /* Constructor */;
67056                     applyToParameterTypes(source, target, inferFromContravariantTypes);
67057                     bivariant = saveBivariant;
67058                 }
67059                 applyToReturnTypes(source, target, inferFromTypes);
67060             }
67061             function inferFromIndexTypes(source, target) {
67062                 // Inferences across mapped type index signatures are pretty much the same a inferences to homomorphic variables
67063                 var priority = (ts.getObjectFlags(source) & ts.getObjectFlags(target) & 32 /* Mapped */) ? 8 /* HomomorphicMappedType */ : 0;
67064                 var indexInfos = getIndexInfosOfType(target);
67065                 if (isObjectTypeWithInferableIndex(source)) {
67066                     for (var _i = 0, indexInfos_4 = indexInfos; _i < indexInfos_4.length; _i++) {
67067                         var targetInfo = indexInfos_4[_i];
67068                         var propTypes = [];
67069                         for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) {
67070                             var prop = _b[_a];
67071                             if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), targetInfo.keyType)) {
67072                                 var propType = getTypeOfSymbol(prop);
67073                                 propTypes.push(prop.flags & 16777216 /* Optional */ ? removeMissingOrUndefinedType(propType) : propType);
67074                             }
67075                         }
67076                         for (var _c = 0, _d = getIndexInfosOfType(source); _c < _d.length; _c++) {
67077                             var info = _d[_c];
67078                             if (isApplicableIndexType(info.keyType, targetInfo.keyType)) {
67079                                 propTypes.push(info.type);
67080                             }
67081                         }
67082                         if (propTypes.length) {
67083                             inferWithPriority(getUnionType(propTypes), targetInfo.type, priority);
67084                         }
67085                     }
67086                 }
67087                 for (var _e = 0, indexInfos_5 = indexInfos; _e < indexInfos_5.length; _e++) {
67088                     var targetInfo = indexInfos_5[_e];
67089                     var sourceInfo = getApplicableIndexInfo(source, targetInfo.keyType);
67090                     if (sourceInfo) {
67091                         inferWithPriority(sourceInfo.type, targetInfo.type, priority);
67092                     }
67093                 }
67094             }
67095         }
67096         function isTypeOrBaseIdenticalTo(s, t) {
67097             return exactOptionalPropertyTypes && t === missingType ? s === t :
67098                 (isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */));
67099         }
67100         function isTypeCloselyMatchedBy(s, t) {
67101             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
67102                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
67103         }
67104         function hasPrimitiveConstraint(type) {
67105             var constraint = getConstraintOfTypeParameter(type);
67106             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
67107         }
67108         function isObjectLiteralType(type) {
67109             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
67110         }
67111         function isObjectOrArrayLiteralType(type) {
67112             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */));
67113         }
67114         function unionObjectAndArrayLiteralCandidates(candidates) {
67115             if (candidates.length > 1) {
67116                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
67117                 if (objectLiterals.length) {
67118                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
67119                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
67120                 }
67121             }
67122             return candidates;
67123         }
67124         function getContravariantInference(inference) {
67125             return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
67126         }
67127         function getCovariantInference(inference, signature) {
67128             // Extract all object and array literal types and replace them with a single widened and normalized type.
67129             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
67130             // We widen inferred literal types if
67131             // all inferences were made to top-level occurrences of the type parameter, and
67132             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
67133             // the type parameter was fixed during inference or does not occur at top-level in the return type.
67134             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
67135             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
67136                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
67137             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
67138                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
67139                     candidates;
67140             // If all inferences were made from a position that implies a combined result, infer a union type.
67141             // Otherwise, infer a common supertype.
67142             var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ?
67143                 getUnionType(baseCandidates, 2 /* Subtype */) :
67144                 getCommonSupertype(baseCandidates);
67145             return getWidenedType(unwidenedType);
67146         }
67147         function getInferredType(context, index) {
67148             var inference = context.inferences[index];
67149             if (!inference.inferredType) {
67150                 var inferredType = void 0;
67151                 var signature = context.signature;
67152                 if (signature) {
67153                     var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined;
67154                     if (inference.contraCandidates) {
67155                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
67156                         // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'.
67157                         inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) &&
67158                             ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ?
67159                             inferredCovariantType_1 : getContravariantInference(inference);
67160                     }
67161                     else if (inferredCovariantType_1) {
67162                         inferredType = inferredCovariantType_1;
67163                     }
67164                     else if (context.flags & 1 /* NoDefault */) {
67165                         // We use silentNeverType as the wildcard that signals no inferences.
67166                         inferredType = silentNeverType;
67167                     }
67168                     else {
67169                         // Infer either the default or the empty object type when no inferences were
67170                         // made. It is important to remember that in this case, inference still
67171                         // succeeds, meaning there is no error for not having inference candidates. An
67172                         // inference error only occurs when there are *conflicting* candidates, i.e.
67173                         // candidates with no common supertype.
67174                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
67175                         if (defaultType) {
67176                             // Instantiate the default type. Any forward reference to a type
67177                             // parameter should be instantiated to the empty object type.
67178                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
67179                         }
67180                     }
67181                 }
67182                 else {
67183                     inferredType = getTypeFromInference(inference);
67184                 }
67185                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
67186                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
67187                 if (constraint) {
67188                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
67189                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
67190                         inference.inferredType = inferredType = instantiatedConstraint;
67191                     }
67192                 }
67193             }
67194             return inference.inferredType;
67195         }
67196         function getDefaultTypeArgumentType(isInJavaScriptFile) {
67197             return isInJavaScriptFile ? anyType : unknownType;
67198         }
67199         function getInferredTypes(context) {
67200             var result = [];
67201             for (var i = 0; i < context.inferences.length; i++) {
67202                 result.push(getInferredType(context, i));
67203             }
67204             return result;
67205         }
67206         // EXPRESSION TYPE CHECKING
67207         function getCannotFindNameDiagnosticForName(node) {
67208             switch (node.escapedText) {
67209                 case "document":
67210                 case "console":
67211                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
67212                 case "$":
67213                     return compilerOptions.types
67214                         ? 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
67215                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
67216                 case "describe":
67217                 case "suite":
67218                 case "it":
67219                 case "test":
67220                     return compilerOptions.types
67221                         ? 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
67222                         : 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;
67223                 case "process":
67224                 case "require":
67225                 case "Buffer":
67226                 case "module":
67227                     return compilerOptions.types
67228                         ? 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
67229                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
67230                 case "Map":
67231                 case "Set":
67232                 case "Promise":
67233                 case "Symbol":
67234                 case "WeakMap":
67235                 case "WeakSet":
67236                 case "Iterator":
67237                 case "AsyncIterator":
67238                 case "SharedArrayBuffer":
67239                 case "Atomics":
67240                 case "AsyncIterable":
67241                 case "AsyncIterableIterator":
67242                 case "AsyncGenerator":
67243                 case "AsyncGeneratorFunction":
67244                 case "BigInt":
67245                 case "Reflect":
67246                 case "BigInt64Array":
67247                 case "BigUint64Array":
67248                     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;
67249                 default:
67250                     if (node.parent.kind === 295 /* ShorthandPropertyAssignment */) {
67251                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
67252                     }
67253                     else {
67254                         return ts.Diagnostics.Cannot_find_name_0;
67255                     }
67256             }
67257         }
67258         function getResolvedSymbol(node) {
67259             var links = getNodeLinks(node);
67260             if (!links.resolvedSymbol) {
67261                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
67262                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
67263                     /*excludeGlobals*/ false) || unknownSymbol;
67264             }
67265             return links.resolvedSymbol;
67266         }
67267         function isInTypeQuery(node) {
67268             // TypeScript 1.0 spec (April 2014): 3.6.3
67269             // A type query consists of the keyword typeof followed by an expression.
67270             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
67271             return !!ts.findAncestor(node, function (n) { return n.kind === 180 /* TypeQuery */ ? true : n.kind === 79 /* Identifier */ || n.kind === 160 /* QualifiedName */ ? false : "quit"; });
67272         }
67273         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
67274         // separated by dots). The key consists of the id of the symbol referenced by the
67275         // leftmost identifier followed by zero or more property names separated by dots.
67276         // The result is undefined if the reference isn't a dotted name.
67277         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
67278             switch (node.kind) {
67279                 case 79 /* Identifier */:
67280                     if (!ts.isThisInTypeQuery(node)) {
67281                         var symbol = getResolvedSymbol(node);
67282                         return symbol !== unknownSymbol ? "".concat(flowContainer ? getNodeId(flowContainer) : "-1", "|").concat(getTypeId(declaredType), "|").concat(getTypeId(initialType), "|").concat(getSymbolId(symbol)) : undefined;
67283                     }
67284                 // falls through
67285                 case 108 /* ThisKeyword */:
67286                     return "0|".concat(flowContainer ? getNodeId(flowContainer) : "-1", "|").concat(getTypeId(declaredType), "|").concat(getTypeId(initialType));
67287                 case 229 /* NonNullExpression */:
67288                 case 211 /* ParenthesizedExpression */:
67289                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
67290                 case 160 /* QualifiedName */:
67291                     var left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer);
67292                     return left && left + "." + node.right.escapedText;
67293                 case 205 /* PropertyAccessExpression */:
67294                 case 206 /* ElementAccessExpression */:
67295                     var propName = getAccessedPropertyName(node);
67296                     if (propName !== undefined) {
67297                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
67298                         return key && key + "." + propName;
67299                     }
67300             }
67301             return undefined;
67302         }
67303         function isMatchingReference(source, target) {
67304             switch (target.kind) {
67305                 case 211 /* ParenthesizedExpression */:
67306                 case 229 /* NonNullExpression */:
67307                     return isMatchingReference(source, target.expression);
67308                 case 220 /* BinaryExpression */:
67309                     return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) ||
67310                         (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right));
67311             }
67312             switch (source.kind) {
67313                 case 230 /* MetaProperty */:
67314                     return target.kind === 230 /* MetaProperty */
67315                         && source.keywordToken === target.keywordToken
67316                         && source.name.escapedText === target.name.escapedText;
67317                 case 79 /* Identifier */:
67318                 case 80 /* PrivateIdentifier */:
67319                     return ts.isThisInTypeQuery(source) ?
67320                         target.kind === 108 /* ThisKeyword */ :
67321                         target.kind === 79 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
67322                             (target.kind === 253 /* VariableDeclaration */ || target.kind === 202 /* BindingElement */) &&
67323                                 getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
67324                 case 108 /* ThisKeyword */:
67325                     return target.kind === 108 /* ThisKeyword */;
67326                 case 106 /* SuperKeyword */:
67327                     return target.kind === 106 /* SuperKeyword */;
67328                 case 229 /* NonNullExpression */:
67329                 case 211 /* ParenthesizedExpression */:
67330                     return isMatchingReference(source.expression, target);
67331                 case 205 /* PropertyAccessExpression */:
67332                 case 206 /* ElementAccessExpression */:
67333                     return ts.isAccessExpression(target) &&
67334                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
67335                         isMatchingReference(source.expression, target.expression);
67336                 case 160 /* QualifiedName */:
67337                     return ts.isAccessExpression(target) &&
67338                         source.right.escapedText === getAccessedPropertyName(target) &&
67339                         isMatchingReference(source.left, target.expression);
67340                 case 220 /* BinaryExpression */:
67341                     return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target));
67342             }
67343             return false;
67344         }
67345         function getPropertyAccess(expr) {
67346             if (ts.isAccessExpression(expr)) {
67347                 return expr;
67348             }
67349             if (ts.isIdentifier(expr)) {
67350                 var symbol = getResolvedSymbol(expr);
67351                 if (isConstVariable(symbol)) {
67352                     var declaration = symbol.valueDeclaration;
67353                     // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind'
67354                     if (ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && ts.isAccessExpression(declaration.initializer)) {
67355                         return declaration.initializer;
67356                     }
67357                     // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind'
67358                     if (ts.isBindingElement(declaration) && !declaration.initializer) {
67359                         var parent = declaration.parent.parent;
67360                         if (ts.isVariableDeclaration(parent) && !parent.type && parent.initializer && (ts.isIdentifier(parent.initializer) || ts.isAccessExpression(parent.initializer))) {
67361                             return declaration;
67362                         }
67363                     }
67364                 }
67365             }
67366             return undefined;
67367         }
67368         function getAccessedPropertyName(access) {
67369             var propertyName;
67370             return access.kind === 205 /* PropertyAccessExpression */ ? access.name.escapedText :
67371                 access.kind === 206 /* ElementAccessExpression */ && ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
67372                     access.kind === 202 /* BindingElement */ && (propertyName = getDestructuringPropertyName(access)) ? ts.escapeLeadingUnderscores(propertyName) :
67373                         undefined;
67374         }
67375         function containsMatchingReference(source, target) {
67376             while (ts.isAccessExpression(source)) {
67377                 source = source.expression;
67378                 if (isMatchingReference(source, target)) {
67379                     return true;
67380                 }
67381             }
67382             return false;
67383         }
67384         function optionalChainContainsReference(source, target) {
67385             while (ts.isOptionalChain(source)) {
67386                 source = source.expression;
67387                 if (isMatchingReference(source, target)) {
67388                     return true;
67389                 }
67390             }
67391             return false;
67392         }
67393         function isDiscriminantProperty(type, name) {
67394             if (type && type.flags & 1048576 /* Union */) {
67395                 var prop = getUnionOrIntersectionProperty(type, name);
67396                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
67397                     if (prop.isDiscriminantProperty === undefined) {
67398                         prop.isDiscriminantProperty =
67399                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
67400                                 !isGenericType(getTypeOfSymbol(prop));
67401                     }
67402                     return !!prop.isDiscriminantProperty;
67403                 }
67404             }
67405             return false;
67406         }
67407         function findDiscriminantProperties(sourceProperties, target) {
67408             var result;
67409             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
67410                 var sourceProperty = sourceProperties_2[_i];
67411                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
67412                     if (result) {
67413                         result.push(sourceProperty);
67414                         continue;
67415                     }
67416                     result = [sourceProperty];
67417                 }
67418             }
67419             return result;
67420         }
67421         // Given a set of constituent types and a property name, create and return a map keyed by the literal
67422         // types of the property by that name in each constituent type. No map is returned if some key property
67423         // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key.
67424         // Entries with duplicate keys have unknownType as the value.
67425         function mapTypesByKeyProperty(types, name) {
67426             var map = new ts.Map();
67427             var count = 0;
67428             var _loop_22 = function (type) {
67429                 if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) {
67430                     var discriminant = getTypeOfPropertyOfType(type, name);
67431                     if (discriminant) {
67432                         if (!isLiteralType(discriminant)) {
67433                             return { value: undefined };
67434                         }
67435                         var duplicate_1 = false;
67436                         forEachType(discriminant, function (t) {
67437                             var id = getTypeId(getRegularTypeOfLiteralType(t));
67438                             var existing = map.get(id);
67439                             if (!existing) {
67440                                 map.set(id, type);
67441                             }
67442                             else if (existing !== unknownType) {
67443                                 map.set(id, unknownType);
67444                                 duplicate_1 = true;
67445                             }
67446                         });
67447                         if (!duplicate_1)
67448                             count++;
67449                     }
67450                 }
67451             };
67452             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
67453                 var type = types_16[_i];
67454                 var state_8 = _loop_22(type);
67455                 if (typeof state_8 === "object")
67456                     return state_8.value;
67457             }
67458             return count >= 10 && count * 2 >= types.length ? map : undefined;
67459         }
67460         // Return the name of a discriminant property for which it was possible and feasible to construct a map of
67461         // constituent types keyed by the literal types of the property by that name in each constituent type.
67462         function getKeyPropertyName(unionType) {
67463             var types = unionType.types;
67464             // We only construct maps for unions with many non-primitive constituents.
67465             if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ ||
67466                 ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) {
67467                 return undefined;
67468             }
67469             if (unionType.keyPropertyName === undefined) {
67470                 // The candidate key property name is the name of the first property with a unit type in one of the
67471                 // constituent types.
67472                 var keyPropertyName = ts.forEach(types, function (t) {
67473                     return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ?
67474                         ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) :
67475                         undefined;
67476                 });
67477                 var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName);
67478                 unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : "";
67479                 unionType.constituentMap = mapByKeyProperty;
67480             }
67481             return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined;
67482         }
67483         // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent
67484         // that corresponds to the given key type for that property name.
67485         function getConstituentTypeForKeyType(unionType, keyType) {
67486             var _a;
67487             var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType)));
67488             return result !== unknownType ? result : undefined;
67489         }
67490         function getMatchingUnionConstituentForType(unionType, type) {
67491             var keyPropertyName = getKeyPropertyName(unionType);
67492             var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName);
67493             return propType && getConstituentTypeForKeyType(unionType, propType);
67494         }
67495         function getMatchingUnionConstituentForObjectLiteral(unionType, node) {
67496             var keyPropertyName = getKeyPropertyName(unionType);
67497             var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ &&
67498                 p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); });
67499             var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer);
67500             return propType && getConstituentTypeForKeyType(unionType, propType);
67501         }
67502         function isOrContainsMatchingReference(source, target) {
67503             return isMatchingReference(source, target) || containsMatchingReference(source, target);
67504         }
67505         function hasMatchingArgument(expression, reference) {
67506             if (expression.arguments) {
67507                 for (var _i = 0, _a = expression.arguments; _i < _a.length; _i++) {
67508                     var argument = _a[_i];
67509                     if (isOrContainsMatchingReference(reference, argument)) {
67510                         return true;
67511                     }
67512                 }
67513             }
67514             if (expression.expression.kind === 205 /* PropertyAccessExpression */ &&
67515                 isOrContainsMatchingReference(reference, expression.expression.expression)) {
67516                 return true;
67517             }
67518             return false;
67519         }
67520         function getFlowNodeId(flow) {
67521             if (!flow.id || flow.id < 0) {
67522                 flow.id = nextFlowId;
67523                 nextFlowId++;
67524             }
67525             return flow.id;
67526         }
67527         function typeMaybeAssignableTo(source, target) {
67528             if (!(source.flags & 1048576 /* Union */)) {
67529                 return isTypeAssignableTo(source, target);
67530             }
67531             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
67532                 var t = _a[_i];
67533                 if (isTypeAssignableTo(t, target)) {
67534                     return true;
67535                 }
67536             }
67537             return false;
67538         }
67539         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
67540         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
67541         // we remove type string.
67542         function getAssignmentReducedType(declaredType, assignedType) {
67543             if (declaredType !== assignedType) {
67544                 if (assignedType.flags & 131072 /* Never */) {
67545                     return assignedType;
67546                 }
67547                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
67548                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
67549                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
67550                 }
67551                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
67552                 // For now, when that happens, we give up and don't narrow at all.  (This also
67553                 // means we'll never narrow for erroneous assignments where the assigned type
67554                 // is not assignable to the declared type.)
67555                 if (isTypeAssignableTo(assignedType, reducedType)) {
67556                     return reducedType;
67557                 }
67558             }
67559             return declaredType;
67560         }
67561         function isFunctionObjectType(type) {
67562             // We do a quick check for a "bind" property before performing the more expensive subtype
67563             // check. This gives us a quicker out in the common case where an object type is not a function.
67564             var resolved = resolveStructuredTypeMembers(type);
67565             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
67566                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
67567         }
67568         function getTypeFacts(type, ignoreObjects) {
67569             if (ignoreObjects === void 0) { ignoreObjects = false; }
67570             var flags = type.flags;
67571             if (flags & 4 /* String */) {
67572                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
67573             }
67574             if (flags & 128 /* StringLiteral */) {
67575                 var isEmpty = type.value === "";
67576                 return strictNullChecks ?
67577                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
67578                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
67579             }
67580             if (flags & (8 /* Number */ | 32 /* Enum */)) {
67581                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
67582             }
67583             if (flags & 256 /* NumberLiteral */) {
67584                 var isZero = type.value === 0;
67585                 return strictNullChecks ?
67586                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
67587                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
67588             }
67589             if (flags & 64 /* BigInt */) {
67590                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
67591             }
67592             if (flags & 2048 /* BigIntLiteral */) {
67593                 var isZero = isZeroBigInt(type);
67594                 return strictNullChecks ?
67595                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
67596                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
67597             }
67598             if (flags & 16 /* Boolean */) {
67599                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
67600             }
67601             if (flags & 528 /* BooleanLike */) {
67602                 return strictNullChecks ?
67603                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
67604                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
67605             }
67606             if (flags & 524288 /* Object */ && !ignoreObjects) {
67607                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
67608                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
67609                     isFunctionObjectType(type) ?
67610                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
67611                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
67612             }
67613             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
67614                 return 9830144 /* UndefinedFacts */;
67615             }
67616             if (flags & 65536 /* Null */) {
67617                 return 9363232 /* NullFacts */;
67618             }
67619             if (flags & 12288 /* ESSymbolLike */) {
67620                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
67621             }
67622             if (flags & 67108864 /* NonPrimitive */) {
67623                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
67624             }
67625             if (flags & 131072 /* Never */) {
67626                 return 0 /* None */;
67627             }
67628             if (flags & 465829888 /* Instantiable */) {
67629                 return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) :
67630                     strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */;
67631             }
67632             if (flags & 1048576 /* Union */) {
67633                 return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */);
67634             }
67635             if (flags & 2097152 /* Intersection */) {
67636                 // When an intersection contains a primitive type we ignore object type constituents as they are
67637                 // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type.
67638                 ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */));
67639                 return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */);
67640             }
67641             return 16777215 /* All */;
67642         }
67643         function getTypeWithFacts(type, include) {
67644             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
67645         }
67646         function getTypeWithDefault(type, defaultExpression) {
67647             return defaultExpression ?
67648                 getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) :
67649                 type;
67650         }
67651         function getTypeOfDestructuredProperty(type, name) {
67652             var _a;
67653             var nameType = getLiteralTypeFromPropertyName(name);
67654             if (!isTypeUsableAsPropertyName(nameType))
67655                 return errorType;
67656             var text = getPropertyNameFromType(nameType);
67657             return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) === null || _a === void 0 ? void 0 : _a.type) || errorType;
67658         }
67659         function getTypeOfDestructuredArrayElement(type, index) {
67660             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
67661                 includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined)) ||
67662                 errorType;
67663         }
67664         function includeUndefinedInIndexSignature(type) {
67665             if (!type)
67666                 return type;
67667             return compilerOptions.noUncheckedIndexedAccess ?
67668                 getUnionType([type, undefinedType]) :
67669                 type;
67670         }
67671         function getTypeOfDestructuredSpreadExpression(type) {
67672             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
67673         }
67674         function getAssignedTypeOfBinaryExpression(node) {
67675             var isDestructuringDefaultAssignment = node.parent.kind === 203 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
67676                 node.parent.kind === 294 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
67677             return isDestructuringDefaultAssignment ?
67678                 getTypeWithDefault(getAssignedType(node), node.right) :
67679                 getTypeOfExpression(node.right);
67680         }
67681         function isDestructuringAssignmentTarget(parent) {
67682             return parent.parent.kind === 220 /* BinaryExpression */ && parent.parent.left === parent ||
67683                 parent.parent.kind === 243 /* ForOfStatement */ && parent.parent.initializer === parent;
67684         }
67685         function getAssignedTypeOfArrayLiteralElement(node, element) {
67686             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
67687         }
67688         function getAssignedTypeOfSpreadExpression(node) {
67689             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
67690         }
67691         function getAssignedTypeOfPropertyAssignment(node) {
67692             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
67693         }
67694         function getAssignedTypeOfShorthandPropertyAssignment(node) {
67695             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
67696         }
67697         function getAssignedType(node) {
67698             var parent = node.parent;
67699             switch (parent.kind) {
67700                 case 242 /* ForInStatement */:
67701                     return stringType;
67702                 case 243 /* ForOfStatement */:
67703                     return checkRightHandSideOfForOf(parent) || errorType;
67704                 case 220 /* BinaryExpression */:
67705                     return getAssignedTypeOfBinaryExpression(parent);
67706                 case 214 /* DeleteExpression */:
67707                     return undefinedType;
67708                 case 203 /* ArrayLiteralExpression */:
67709                     return getAssignedTypeOfArrayLiteralElement(parent, node);
67710                 case 224 /* SpreadElement */:
67711                     return getAssignedTypeOfSpreadExpression(parent);
67712                 case 294 /* PropertyAssignment */:
67713                     return getAssignedTypeOfPropertyAssignment(parent);
67714                 case 295 /* ShorthandPropertyAssignment */:
67715                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
67716             }
67717             return errorType;
67718         }
67719         function getInitialTypeOfBindingElement(node) {
67720             var pattern = node.parent;
67721             var parentType = getInitialType(pattern.parent);
67722             var type = pattern.kind === 200 /* ObjectBindingPattern */ ?
67723                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
67724                 !node.dotDotDotToken ?
67725                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
67726                     getTypeOfDestructuredSpreadExpression(parentType);
67727             return getTypeWithDefault(type, node.initializer);
67728         }
67729         function getTypeOfInitializer(node) {
67730             // Return the cached type if one is available. If the type of the variable was inferred
67731             // from its initializer, we'll already have cached the type. Otherwise we compute it now
67732             // without caching such that transient types are reflected.
67733             var links = getNodeLinks(node);
67734             return links.resolvedType || getTypeOfExpression(node);
67735         }
67736         function getInitialTypeOfVariableDeclaration(node) {
67737             if (node.initializer) {
67738                 return getTypeOfInitializer(node.initializer);
67739             }
67740             if (node.parent.parent.kind === 242 /* ForInStatement */) {
67741                 return stringType;
67742             }
67743             if (node.parent.parent.kind === 243 /* ForOfStatement */) {
67744                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
67745             }
67746             return errorType;
67747         }
67748         function getInitialType(node) {
67749             return node.kind === 253 /* VariableDeclaration */ ?
67750                 getInitialTypeOfVariableDeclaration(node) :
67751                 getInitialTypeOfBindingElement(node);
67752         }
67753         function isEmptyArrayAssignment(node) {
67754             return node.kind === 253 /* VariableDeclaration */ && node.initializer &&
67755                 isEmptyArrayLiteral(node.initializer) ||
67756                 node.kind !== 202 /* BindingElement */ && node.parent.kind === 220 /* BinaryExpression */ &&
67757                     isEmptyArrayLiteral(node.parent.right);
67758         }
67759         function getReferenceCandidate(node) {
67760             switch (node.kind) {
67761                 case 211 /* ParenthesizedExpression */:
67762                     return getReferenceCandidate(node.expression);
67763                 case 220 /* BinaryExpression */:
67764                     switch (node.operatorToken.kind) {
67765                         case 63 /* EqualsToken */:
67766                         case 75 /* BarBarEqualsToken */:
67767                         case 76 /* AmpersandAmpersandEqualsToken */:
67768                         case 77 /* QuestionQuestionEqualsToken */:
67769                             return getReferenceCandidate(node.left);
67770                         case 27 /* CommaToken */:
67771                             return getReferenceCandidate(node.right);
67772                     }
67773             }
67774             return node;
67775         }
67776         function getReferenceRoot(node) {
67777             var parent = node.parent;
67778             return parent.kind === 211 /* ParenthesizedExpression */ ||
67779                 parent.kind === 220 /* BinaryExpression */ && parent.operatorToken.kind === 63 /* EqualsToken */ && parent.left === node ||
67780                 parent.kind === 220 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
67781                 getReferenceRoot(parent) : node;
67782         }
67783         function getTypeOfSwitchClause(clause) {
67784             if (clause.kind === 288 /* CaseClause */) {
67785                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
67786             }
67787             return neverType;
67788         }
67789         function getSwitchClauseTypes(switchStatement) {
67790             var links = getNodeLinks(switchStatement);
67791             if (!links.switchTypes) {
67792                 links.switchTypes = [];
67793                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
67794                     var clause = _a[_i];
67795                     links.switchTypes.push(getTypeOfSwitchClause(clause));
67796                 }
67797             }
67798             return links.switchTypes;
67799         }
67800         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
67801             var witnesses = [];
67802             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
67803                 var clause = _a[_i];
67804                 if (clause.kind === 288 /* CaseClause */) {
67805                     if (ts.isStringLiteralLike(clause.expression)) {
67806                         witnesses.push(clause.expression.text);
67807                         continue;
67808                     }
67809                     return ts.emptyArray;
67810                 }
67811                 if (retainDefault)
67812                     witnesses.push(/*explicitDefaultStatement*/ undefined);
67813             }
67814             return witnesses;
67815         }
67816         function eachTypeContainedIn(source, types) {
67817             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
67818         }
67819         function isTypeSubsetOf(source, target) {
67820             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
67821         }
67822         function isTypeSubsetOfUnion(source, target) {
67823             if (source.flags & 1048576 /* Union */) {
67824                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
67825                     var t = _a[_i];
67826                     if (!containsType(target.types, t)) {
67827                         return false;
67828                     }
67829                 }
67830                 return true;
67831             }
67832             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
67833                 return true;
67834             }
67835             return containsType(target.types, source);
67836         }
67837         function forEachType(type, f) {
67838             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
67839         }
67840         function someType(type, f) {
67841             return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type);
67842         }
67843         function everyType(type, f) {
67844             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
67845         }
67846         function everyContainedType(type, f) {
67847             return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type);
67848         }
67849         function filterType(type, f) {
67850             if (type.flags & 1048576 /* Union */) {
67851                 var types = type.types;
67852                 var filtered = ts.filter(types, f);
67853                 if (filtered === types) {
67854                     return type;
67855                 }
67856                 var origin = type.origin;
67857                 var newOrigin = void 0;
67858                 if (origin && origin.flags & 1048576 /* Union */) {
67859                     // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends
67860                     // up removing a smaller number of types than in the normalized constituent set (meaning some of the
67861                     // filtered types are within nested unions in the origin), then we can't construct a new origin type.
67862                     // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type.
67863                     // Otherwise, construct a new filtered origin type.
67864                     var originTypes = origin.types;
67865                     var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); });
67866                     if (originTypes.length - originFiltered.length === types.length - filtered.length) {
67867                         if (originFiltered.length === 1) {
67868                             return originFiltered[0];
67869                         }
67870                         newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered);
67871                     }
67872                 }
67873                 return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin);
67874             }
67875             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
67876         }
67877         function removeType(type, targetType) {
67878             return filterType(type, function (t) { return t !== targetType; });
67879         }
67880         function countTypes(type) {
67881             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
67882         }
67883         function mapType(type, mapper, noReductions) {
67884             if (type.flags & 131072 /* Never */) {
67885                 return type;
67886             }
67887             if (!(type.flags & 1048576 /* Union */)) {
67888                 return mapper(type);
67889             }
67890             var origin = type.origin;
67891             var types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types;
67892             var mappedTypes;
67893             var changed = false;
67894             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
67895                 var t = types_17[_i];
67896                 var mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t);
67897                 changed || (changed = t !== mapped);
67898                 if (mapped) {
67899                     if (!mappedTypes) {
67900                         mappedTypes = [mapped];
67901                     }
67902                     else {
67903                         mappedTypes.push(mapped);
67904                     }
67905                 }
67906             }
67907             return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type;
67908         }
67909         function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
67910             return type.flags & 1048576 /* Union */ && aliasSymbol ?
67911                 getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) :
67912                 mapType(type, mapper);
67913         }
67914         function getConstituentCount(type) {
67915             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
67916         }
67917         function extractTypesOfKind(type, kind) {
67918             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
67919         }
67920         // Return a new type in which occurrences of the string, number and bigint primitives and placeholder template
67921         // literal types in typeWithPrimitives have been replaced with occurrences of compatible and more specific types
67922         // from typeWithLiterals. This is essentially a limited form of intersection between the two types. We avoid a
67923         // true intersection because it is more costly and, when applied to union types, generates a large number of
67924         // types we don't actually care about.
67925         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
67926             if (maybeTypeOfKind(typeWithPrimitives, 4 /* String */ | 134217728 /* TemplateLiteral */ | 8 /* Number */ | 64 /* BigInt */) &&
67927                 maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)) {
67928                 return mapType(typeWithPrimitives, function (t) {
67929                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) :
67930                         isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) :
67931                             t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
67932                                 t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
67933                 });
67934             }
67935             return typeWithPrimitives;
67936         }
67937         function isIncomplete(flowType) {
67938             return flowType.flags === 0;
67939         }
67940         function getTypeFromFlowType(flowType) {
67941             return flowType.flags === 0 ? flowType.type : flowType;
67942         }
67943         function createFlowType(type, incomplete) {
67944             return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
67945         }
67946         // An evolving array type tracks the element types that have so far been seen in an
67947         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
67948         // array types are ultimately converted into manifest array types (using getFinalArrayType)
67949         // and never escape the getFlowTypeOfReference function.
67950         function createEvolvingArrayType(elementType) {
67951             var result = createObjectType(256 /* EvolvingArray */);
67952             result.elementType = elementType;
67953             return result;
67954         }
67955         function getEvolvingArrayType(elementType) {
67956             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
67957         }
67958         // When adding evolving array element types we do not perform subtype reduction. Instead,
67959         // we defer subtype reduction until the evolving array type is finalized into a manifest
67960         // array type.
67961         function addEvolvingArrayElementType(evolvingArrayType, node) {
67962             var elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
67963             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
67964         }
67965         function createFinalArrayType(elementType) {
67966             return elementType.flags & 131072 /* Never */ ?
67967                 autoArrayType :
67968                 createArrayType(elementType.flags & 1048576 /* Union */ ?
67969                     getUnionType(elementType.types, 2 /* Subtype */) :
67970                     elementType);
67971         }
67972         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
67973         function getFinalArrayType(evolvingArrayType) {
67974             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
67975         }
67976         function finalizeEvolvingArrayType(type) {
67977             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
67978         }
67979         function getElementTypeOfEvolvingArrayType(type) {
67980             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
67981         }
67982         function isEvolvingArrayTypeList(types) {
67983             var hasEvolvingArrayType = false;
67984             for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
67985                 var t = types_18[_i];
67986                 if (!(t.flags & 131072 /* Never */)) {
67987                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
67988                         return false;
67989                     }
67990                     hasEvolvingArrayType = true;
67991                 }
67992             }
67993             return hasEvolvingArrayType;
67994         }
67995         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
67996         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
67997         function isEvolvingArrayOperationTarget(node) {
67998             var root = getReferenceRoot(node);
67999             var parent = root.parent;
68000             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
68001                 parent.parent.kind === 207 /* CallExpression */
68002                     && ts.isIdentifier(parent.name)
68003                     && ts.isPushOrUnshiftIdentifier(parent.name));
68004             var isElementAssignment = parent.kind === 206 /* ElementAccessExpression */ &&
68005                 parent.expression === root &&
68006                 parent.parent.kind === 220 /* BinaryExpression */ &&
68007                 parent.parent.operatorToken.kind === 63 /* EqualsToken */ &&
68008                 parent.parent.left === parent &&
68009                 !ts.isAssignmentTarget(parent.parent) &&
68010                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
68011             return isLengthPushOrUnshift || isElementAssignment;
68012         }
68013         function isDeclarationWithExplicitTypeAnnotation(node) {
68014             return (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) &&
68015                 !!(ts.getEffectiveTypeAnnotationNode(node) ||
68016                     ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer));
68017         }
68018         function getExplicitTypeOfSymbol(symbol, diagnostic) {
68019             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
68020                 return getTypeOfSymbol(symbol);
68021             }
68022             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
68023                 if (ts.getCheckFlags(symbol) & 262144 /* Mapped */) {
68024                     var origin = symbol.syntheticOrigin;
68025                     if (origin && getExplicitTypeOfSymbol(origin)) {
68026                         return getTypeOfSymbol(symbol);
68027                     }
68028                 }
68029                 var declaration = symbol.valueDeclaration;
68030                 if (declaration) {
68031                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
68032                         return getTypeOfSymbol(symbol);
68033                     }
68034                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 243 /* ForOfStatement */) {
68035                         var statement = declaration.parent.parent;
68036                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
68037                         if (expressionType) {
68038                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
68039                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
68040                         }
68041                     }
68042                     if (diagnostic) {
68043                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
68044                     }
68045                 }
68046             }
68047         }
68048         // We require the dotted function name in an assertion expression to be comprised of identifiers
68049         // that reference function, method, class or value module symbols; or variable, property or
68050         // parameter symbols with declarations that have explicit type annotations. Such references are
68051         // resolvable with no possibility of triggering circularities in control flow analysis.
68052         function getTypeOfDottedName(node, diagnostic) {
68053             if (!(node.flags & 16777216 /* InWithStatement */)) {
68054                 switch (node.kind) {
68055                     case 79 /* Identifier */:
68056                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
68057                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
68058                     case 108 /* ThisKeyword */:
68059                         return getExplicitThisType(node);
68060                     case 106 /* SuperKeyword */:
68061                         return checkSuperExpression(node);
68062                     case 205 /* PropertyAccessExpression */: {
68063                         var type = getTypeOfDottedName(node.expression, diagnostic);
68064                         if (type) {
68065                             var name = node.name;
68066                             var prop = void 0;
68067                             if (ts.isPrivateIdentifier(name)) {
68068                                 if (!type.symbol) {
68069                                     return undefined;
68070                                 }
68071                                 prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText));
68072                             }
68073                             else {
68074                                 prop = getPropertyOfType(type, name.escapedText);
68075                             }
68076                             return prop && getExplicitTypeOfSymbol(prop, diagnostic);
68077                         }
68078                         return undefined;
68079                     }
68080                     case 211 /* ParenthesizedExpression */:
68081                         return getTypeOfDottedName(node.expression, diagnostic);
68082                 }
68083             }
68084         }
68085         function getEffectsSignature(node) {
68086             var links = getNodeLinks(node);
68087             var signature = links.effectsSignature;
68088             if (signature === undefined) {
68089                 // A call expression parented by an expression statement is a potential assertion. Other call
68090                 // expressions are potential type predicate function calls. In order to avoid triggering
68091                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
68092                 // target expression of an assertion.
68093                 var funcType = void 0;
68094                 if (node.parent.kind === 237 /* ExpressionStatement */) {
68095                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
68096                 }
68097                 else if (node.expression.kind !== 106 /* SuperKeyword */) {
68098                     if (ts.isOptionalChain(node)) {
68099                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
68100                     }
68101                     else {
68102                         funcType = checkNonNullExpression(node.expression);
68103                     }
68104                 }
68105                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
68106                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
68107                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
68108                         undefined;
68109                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
68110             }
68111             return signature === unknownSignature ? undefined : signature;
68112         }
68113         function hasTypePredicateOrNeverReturnType(signature) {
68114             return !!(getTypePredicateOfSignature(signature) ||
68115                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
68116         }
68117         function getTypePredicateArgument(predicate, callExpression) {
68118             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
68119                 return callExpression.arguments[predicate.parameterIndex];
68120             }
68121             var invokedExpression = ts.skipParentheses(callExpression.expression);
68122             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
68123         }
68124         function reportFlowControlError(node) {
68125             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
68126             var sourceFile = ts.getSourceFileOfNode(node);
68127             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
68128             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
68129         }
68130         function isReachableFlowNode(flow) {
68131             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
68132             lastFlowNode = flow;
68133             lastFlowNodeReachable = result;
68134             return result;
68135         }
68136         function isFalseExpression(expr) {
68137             var node = ts.skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true);
68138             return node.kind === 95 /* FalseKeyword */ || node.kind === 220 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
68139                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
68140         }
68141         function isReachableFlowNodeWorker(flow, noCacheCheck) {
68142             while (true) {
68143                 if (flow === lastFlowNode) {
68144                     return lastFlowNodeReachable;
68145                 }
68146                 var flags = flow.flags;
68147                 if (flags & 4096 /* Shared */) {
68148                     if (!noCacheCheck) {
68149                         var id = getFlowNodeId(flow);
68150                         var reachable = flowNodeReachable[id];
68151                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
68152                     }
68153                     noCacheCheck = false;
68154                 }
68155                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
68156                     flow = flow.antecedent;
68157                 }
68158                 else if (flags & 512 /* Call */) {
68159                     var signature = getEffectsSignature(flow.node);
68160                     if (signature) {
68161                         var predicate = getTypePredicateOfSignature(signature);
68162                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
68163                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
68164                             if (predicateArgument && isFalseExpression(predicateArgument)) {
68165                                 return false;
68166                             }
68167                         }
68168                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
68169                             return false;
68170                         }
68171                     }
68172                     flow = flow.antecedent;
68173                 }
68174                 else if (flags & 4 /* BranchLabel */) {
68175                     // A branching point is reachable if any branch is reachable.
68176                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
68177                 }
68178                 else if (flags & 8 /* LoopLabel */) {
68179                     var antecedents = flow.antecedents;
68180                     if (antecedents === undefined || antecedents.length === 0) {
68181                         return false;
68182                     }
68183                     // A loop is reachable if the control flow path that leads to the top is reachable.
68184                     flow = antecedents[0];
68185                 }
68186                 else if (flags & 128 /* SwitchClause */) {
68187                     // The control flow path representing an unmatched value in a switch statement with
68188                     // no default clause is unreachable if the switch statement is exhaustive.
68189                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
68190                         return false;
68191                     }
68192                     flow = flow.antecedent;
68193                 }
68194                 else if (flags & 1024 /* ReduceLabel */) {
68195                     // Cache is unreliable once we start adjusting labels
68196                     lastFlowNode = undefined;
68197                     var target = flow.target;
68198                     var saveAntecedents = target.antecedents;
68199                     target.antecedents = flow.antecedents;
68200                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
68201                     target.antecedents = saveAntecedents;
68202                     return result;
68203                 }
68204                 else {
68205                     return !(flags & 1 /* Unreachable */);
68206                 }
68207             }
68208         }
68209         // Return true if the given flow node is preceded by a 'super(...)' call in every possible code path
68210         // leading to the node.
68211         function isPostSuperFlowNode(flow, noCacheCheck) {
68212             while (true) {
68213                 var flags = flow.flags;
68214                 if (flags & 4096 /* Shared */) {
68215                     if (!noCacheCheck) {
68216                         var id = getFlowNodeId(flow);
68217                         var postSuper = flowNodePostSuper[id];
68218                         return postSuper !== undefined ? postSuper : (flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ true));
68219                     }
68220                     noCacheCheck = false;
68221                 }
68222                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
68223                     flow = flow.antecedent;
68224                 }
68225                 else if (flags & 512 /* Call */) {
68226                     if (flow.node.expression.kind === 106 /* SuperKeyword */) {
68227                         return true;
68228                     }
68229                     flow = flow.antecedent;
68230                 }
68231                 else if (flags & 4 /* BranchLabel */) {
68232                     // A branching point is post-super if every branch is post-super.
68233                     return ts.every(flow.antecedents, function (f) { return isPostSuperFlowNode(f, /*noCacheCheck*/ false); });
68234                 }
68235                 else if (flags & 8 /* LoopLabel */) {
68236                     // A loop is post-super if the control flow path that leads to the top is post-super.
68237                     flow = flow.antecedents[0];
68238                 }
68239                 else if (flags & 1024 /* ReduceLabel */) {
68240                     var target = flow.target;
68241                     var saveAntecedents = target.antecedents;
68242                     target.antecedents = flow.antecedents;
68243                     var result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ false);
68244                     target.antecedents = saveAntecedents;
68245                     return result;
68246                 }
68247                 else {
68248                     // Unreachable nodes are considered post-super to silence errors
68249                     return !!(flags & 1 /* Unreachable */);
68250                 }
68251             }
68252         }
68253         function isConstantReference(node) {
68254             switch (node.kind) {
68255                 case 79 /* Identifier */: {
68256                     var symbol = getResolvedSymbol(node);
68257                     return isConstVariable(symbol) || ts.isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol);
68258                 }
68259                 case 205 /* PropertyAccessExpression */:
68260                 case 206 /* ElementAccessExpression */:
68261                     // The resolvedSymbol property is initialized by checkPropertyAccess or checkElementAccess before we get here.
68262                     return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol);
68263             }
68264             return false;
68265         }
68266         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer) {
68267             if (initialType === void 0) { initialType = declaredType; }
68268             var key;
68269             var isKeySet = false;
68270             var flowDepth = 0;
68271             if (flowAnalysisDisabled) {
68272                 return errorType;
68273             }
68274             if (!reference.flowNode) {
68275                 return declaredType;
68276             }
68277             flowInvocationCount++;
68278             var sharedFlowStart = sharedFlowCount;
68279             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
68280             sharedFlowCount = sharedFlowStart;
68281             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
68282             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
68283             // on empty arrays are possible without implicit any errors and new element types can be inferred without
68284             // type mismatch errors.
68285             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
68286             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 229 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
68287                 return declaredType;
68288             }
68289             // The non-null unknown type should never escape control flow analysis.
68290             return resultType === nonNullUnknownType ? unknownType : resultType;
68291             function getOrSetCacheKey() {
68292                 if (isKeySet) {
68293                     return key;
68294                 }
68295                 isKeySet = true;
68296                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
68297             }
68298             function getTypeAtFlowNode(flow) {
68299                 if (flowDepth === 2000) {
68300                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
68301                     // and disable further control flow analysis in the containing function or module body.
68302                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
68303                     flowAnalysisDisabled = true;
68304                     reportFlowControlError(reference);
68305                     return errorType;
68306                 }
68307                 flowDepth++;
68308                 var sharedFlow;
68309                 while (true) {
68310                     var flags = flow.flags;
68311                     if (flags & 4096 /* Shared */) {
68312                         // We cache results of flow type resolution for shared nodes that were previously visited in
68313                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
68314                         // antecedent of more than one node.
68315                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
68316                             if (sharedFlowNodes[i] === flow) {
68317                                 flowDepth--;
68318                                 return sharedFlowTypes[i];
68319                             }
68320                         }
68321                         sharedFlow = flow;
68322                     }
68323                     var type = void 0;
68324                     if (flags & 16 /* Assignment */) {
68325                         type = getTypeAtFlowAssignment(flow);
68326                         if (!type) {
68327                             flow = flow.antecedent;
68328                             continue;
68329                         }
68330                     }
68331                     else if (flags & 512 /* Call */) {
68332                         type = getTypeAtFlowCall(flow);
68333                         if (!type) {
68334                             flow = flow.antecedent;
68335                             continue;
68336                         }
68337                     }
68338                     else if (flags & 96 /* Condition */) {
68339                         type = getTypeAtFlowCondition(flow);
68340                     }
68341                     else if (flags & 128 /* SwitchClause */) {
68342                         type = getTypeAtSwitchClause(flow);
68343                     }
68344                     else if (flags & 12 /* Label */) {
68345                         if (flow.antecedents.length === 1) {
68346                             flow = flow.antecedents[0];
68347                             continue;
68348                         }
68349                         type = flags & 4 /* BranchLabel */ ?
68350                             getTypeAtFlowBranchLabel(flow) :
68351                             getTypeAtFlowLoopLabel(flow);
68352                     }
68353                     else if (flags & 256 /* ArrayMutation */) {
68354                         type = getTypeAtFlowArrayMutation(flow);
68355                         if (!type) {
68356                             flow = flow.antecedent;
68357                             continue;
68358                         }
68359                     }
68360                     else if (flags & 1024 /* ReduceLabel */) {
68361                         var target = flow.target;
68362                         var saveAntecedents = target.antecedents;
68363                         target.antecedents = flow.antecedents;
68364                         type = getTypeAtFlowNode(flow.antecedent);
68365                         target.antecedents = saveAntecedents;
68366                     }
68367                     else if (flags & 2 /* Start */) {
68368                         // Check if we should continue with the control flow of the containing function.
68369                         var container = flow.node;
68370                         if (container && container !== flowContainer &&
68371                             reference.kind !== 205 /* PropertyAccessExpression */ &&
68372                             reference.kind !== 206 /* ElementAccessExpression */ &&
68373                             reference.kind !== 108 /* ThisKeyword */) {
68374                             flow = container.flowNode;
68375                             continue;
68376                         }
68377                         // At the top of the flow we have the initial type.
68378                         type = initialType;
68379                     }
68380                     else {
68381                         // Unreachable code errors are reported in the binding phase. Here we
68382                         // simply return the non-auto declared type to reduce follow-on errors.
68383                         type = convertAutoToAny(declaredType);
68384                     }
68385                     if (sharedFlow) {
68386                         // Record visited node and the associated type in the cache.
68387                         sharedFlowNodes[sharedFlowCount] = sharedFlow;
68388                         sharedFlowTypes[sharedFlowCount] = type;
68389                         sharedFlowCount++;
68390                     }
68391                     flowDepth--;
68392                     return type;
68393                 }
68394             }
68395             function getInitialOrAssignedType(flow) {
68396                 var node = flow.node;
68397                 return getNarrowableTypeForReference(node.kind === 253 /* VariableDeclaration */ || node.kind === 202 /* BindingElement */ ?
68398                     getInitialType(node) :
68399                     getAssignedType(node), reference);
68400             }
68401             function getTypeAtFlowAssignment(flow) {
68402                 var node = flow.node;
68403                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
68404                 // only need to evaluate the assigned type if the declared type is a union type.
68405                 if (isMatchingReference(reference, node)) {
68406                     if (!isReachableFlowNode(flow)) {
68407                         return unreachableNeverType;
68408                     }
68409                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
68410                         var flowType = getTypeAtFlowNode(flow.antecedent);
68411                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
68412                     }
68413                     if (declaredType === autoType || declaredType === autoArrayType) {
68414                         if (isEmptyArrayAssignment(node)) {
68415                             return getEvolvingArrayType(neverType);
68416                         }
68417                         var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
68418                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
68419                     }
68420                     if (declaredType.flags & 1048576 /* Union */) {
68421                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
68422                     }
68423                     return declaredType;
68424                 }
68425                 // We didn't have a direct match. However, if the reference is a dotted name, this
68426                 // may be an assignment to a left hand part of the reference. For example, for a
68427                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
68428                 // return the declared type.
68429                 if (containsMatchingReference(reference, node)) {
68430                     if (!isReachableFlowNode(flow)) {
68431                         return unreachableNeverType;
68432                     }
68433                     // A matching dotted name might also be an expando property on a function *expression*,
68434                     // in which case we continue control flow analysis back to the function's declaration
68435                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
68436                         var init = ts.getDeclaredExpandoInitializer(node);
68437                         if (init && (init.kind === 212 /* FunctionExpression */ || init.kind === 213 /* ArrowFunction */)) {
68438                             return getTypeAtFlowNode(flow.antecedent);
68439                         }
68440                     }
68441                     return declaredType;
68442                 }
68443                 // for (const _ in ref) acts as a nonnull on ref
68444                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 242 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
68445                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
68446                 }
68447                 // Assignment doesn't affect reference
68448                 return undefined;
68449             }
68450             function narrowTypeByAssertion(type, expr) {
68451                 var node = ts.skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true);
68452                 if (node.kind === 95 /* FalseKeyword */) {
68453                     return unreachableNeverType;
68454                 }
68455                 if (node.kind === 220 /* BinaryExpression */) {
68456                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
68457                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
68458                     }
68459                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
68460                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
68461                     }
68462                 }
68463                 return narrowType(type, node, /*assumeTrue*/ true);
68464             }
68465             function getTypeAtFlowCall(flow) {
68466                 var signature = getEffectsSignature(flow.node);
68467                 if (signature) {
68468                     var predicate = getTypePredicateOfSignature(signature);
68469                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
68470                         var flowType = getTypeAtFlowNode(flow.antecedent);
68471                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
68472                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
68473                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
68474                                 type;
68475                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
68476                     }
68477                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
68478                         return unreachableNeverType;
68479                     }
68480                 }
68481                 return undefined;
68482             }
68483             function getTypeAtFlowArrayMutation(flow) {
68484                 if (declaredType === autoType || declaredType === autoArrayType) {
68485                     var node = flow.node;
68486                     var expr = node.kind === 207 /* CallExpression */ ?
68487                         node.expression.expression :
68488                         node.left.expression;
68489                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
68490                         var flowType = getTypeAtFlowNode(flow.antecedent);
68491                         var type = getTypeFromFlowType(flowType);
68492                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
68493                             var evolvedType_1 = type;
68494                             if (node.kind === 207 /* CallExpression */) {
68495                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
68496                                     var arg = _a[_i];
68497                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
68498                                 }
68499                             }
68500                             else {
68501                                 // 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)
68502                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
68503                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
68504                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
68505                                 }
68506                             }
68507                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
68508                         }
68509                         return flowType;
68510                     }
68511                 }
68512                 return undefined;
68513             }
68514             function getTypeAtFlowCondition(flow) {
68515                 var flowType = getTypeAtFlowNode(flow.antecedent);
68516                 var type = getTypeFromFlowType(flowType);
68517                 if (type.flags & 131072 /* Never */) {
68518                     return flowType;
68519                 }
68520                 // If we have an antecedent type (meaning we're reachable in some way), we first
68521                 // attempt to narrow the antecedent type. If that produces the never type, and if
68522                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
68523                 // take the type guard as an indication that control *could* reach here once we
68524                 // have the complete type. We proceed by switching to the silent never type which
68525                 // doesn't report errors when operators are applied to it. Note that this is the
68526                 // *only* place a silent never type is ever generated.
68527                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
68528                 var nonEvolvingType = finalizeEvolvingArrayType(type);
68529                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
68530                 if (narrowedType === nonEvolvingType) {
68531                     return flowType;
68532                 }
68533                 return createFlowType(narrowedType, isIncomplete(flowType));
68534             }
68535             function getTypeAtSwitchClause(flow) {
68536                 var expr = flow.switchStatement.expression;
68537                 var flowType = getTypeAtFlowNode(flow.antecedent);
68538                 var type = getTypeFromFlowType(flowType);
68539                 if (isMatchingReference(reference, expr)) {
68540                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
68541                 }
68542                 else if (expr.kind === 215 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
68543                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
68544                 }
68545                 else {
68546                     if (strictNullChecks) {
68547                         if (optionalChainContainsReference(expr, reference)) {
68548                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
68549                         }
68550                         else if (expr.kind === 215 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
68551                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
68552                         }
68553                     }
68554                     var access = getDiscriminantPropertyAccess(expr, type);
68555                     if (access) {
68556                         type = narrowTypeBySwitchOnDiscriminantProperty(type, access, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
68557                     }
68558                 }
68559                 return createFlowType(type, isIncomplete(flowType));
68560             }
68561             function getTypeAtFlowBranchLabel(flow) {
68562                 var antecedentTypes = [];
68563                 var subtypeReduction = false;
68564                 var seenIncomplete = false;
68565                 var bypassFlow;
68566                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
68567                     var antecedent = _a[_i];
68568                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
68569                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
68570                         bypassFlow = antecedent;
68571                         continue;
68572                     }
68573                     var flowType = getTypeAtFlowNode(antecedent);
68574                     var type = getTypeFromFlowType(flowType);
68575                     // If the type at a particular antecedent path is the declared type and the
68576                     // reference is known to always be assigned (i.e. when declared and initial types
68577                     // are the same), there is no reason to process more antecedents since the only
68578                     // possible outcome is subtypes that will be removed in the final union type anyway.
68579                     if (type === declaredType && declaredType === initialType) {
68580                         return type;
68581                     }
68582                     ts.pushIfUnique(antecedentTypes, type);
68583                     // If an antecedent type is not a subset of the declared type, we need to perform
68584                     // subtype reduction. This happens when a "foreign" type is injected into the control
68585                     // flow using the instanceof operator or a user defined type predicate.
68586                     if (!isTypeSubsetOf(type, declaredType)) {
68587                         subtypeReduction = true;
68588                     }
68589                     if (isIncomplete(flowType)) {
68590                         seenIncomplete = true;
68591                     }
68592                 }
68593                 if (bypassFlow) {
68594                     var flowType = getTypeAtFlowNode(bypassFlow);
68595                     var type = getTypeFromFlowType(flowType);
68596                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
68597                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
68598                     // the risk of circularities, we only want to perform them when they make a difference.
68599                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
68600                         if (type === declaredType && declaredType === initialType) {
68601                             return type;
68602                         }
68603                         antecedentTypes.push(type);
68604                         if (!isTypeSubsetOf(type, declaredType)) {
68605                             subtypeReduction = true;
68606                         }
68607                         if (isIncomplete(flowType)) {
68608                             seenIncomplete = true;
68609                         }
68610                     }
68611                 }
68612                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
68613             }
68614             function getTypeAtFlowLoopLabel(flow) {
68615                 // If we have previously computed the control flow type for the reference at
68616                 // this flow loop junction, return the cached type.
68617                 var id = getFlowNodeId(flow);
68618                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = new ts.Map());
68619                 var key = getOrSetCacheKey();
68620                 if (!key) {
68621                     // No cache key is generated when binding patterns are in unnarrowable situations
68622                     return declaredType;
68623                 }
68624                 var cached = cache.get(key);
68625                 if (cached) {
68626                     return cached;
68627                 }
68628                 // If this flow loop junction and reference are already being processed, return
68629                 // the union of the types computed for each branch so far, marked as incomplete.
68630                 // It is possible to see an empty array in cases where loops are nested and the
68631                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
68632                 // In such cases we restart the analysis of the inner loop, which will then see
68633                 // a non-empty in-process array for the outer loop and eventually terminate because
68634                 // the first antecedent of a loop junction is always the non-looping control flow
68635                 // path that leads to the top.
68636                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
68637                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
68638                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
68639                     }
68640                 }
68641                 // Add the flow loop junction and reference to the in-process stack and analyze
68642                 // each antecedent code path.
68643                 var antecedentTypes = [];
68644                 var subtypeReduction = false;
68645                 var firstAntecedentType;
68646                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
68647                     var antecedent = _a[_i];
68648                     var flowType = void 0;
68649                     if (!firstAntecedentType) {
68650                         // The first antecedent of a loop junction is always the non-looping control
68651                         // flow path that leads to the top.
68652                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
68653                     }
68654                     else {
68655                         // All but the first antecedent are the looping control flow paths that lead
68656                         // back to the loop junction. We track these on the flow loop stack.
68657                         flowLoopNodes[flowLoopCount] = flow;
68658                         flowLoopKeys[flowLoopCount] = key;
68659                         flowLoopTypes[flowLoopCount] = antecedentTypes;
68660                         flowLoopCount++;
68661                         var saveFlowTypeCache = flowTypeCache;
68662                         flowTypeCache = undefined;
68663                         flowType = getTypeAtFlowNode(antecedent);
68664                         flowTypeCache = saveFlowTypeCache;
68665                         flowLoopCount--;
68666                         // If we see a value appear in the cache it is a sign that control flow analysis
68667                         // was restarted and completed by checkExpressionCached. We can simply pick up
68668                         // the resulting type and bail out.
68669                         var cached_1 = cache.get(key);
68670                         if (cached_1) {
68671                             return cached_1;
68672                         }
68673                     }
68674                     var type = getTypeFromFlowType(flowType);
68675                     ts.pushIfUnique(antecedentTypes, type);
68676                     // If an antecedent type is not a subset of the declared type, we need to perform
68677                     // subtype reduction. This happens when a "foreign" type is injected into the control
68678                     // flow using the instanceof operator or a user defined type predicate.
68679                     if (!isTypeSubsetOf(type, declaredType)) {
68680                         subtypeReduction = true;
68681                     }
68682                     // If the type at a particular antecedent path is the declared type there is no
68683                     // reason to process more antecedents since the only possible outcome is subtypes
68684                     // that will be removed in the final union type anyway.
68685                     if (type === declaredType) {
68686                         break;
68687                     }
68688                 }
68689                 // The result is incomplete if the first antecedent (the non-looping control flow path)
68690                 // is incomplete.
68691                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
68692                 if (isIncomplete(firstAntecedentType)) {
68693                     return createFlowType(result, /*incomplete*/ true);
68694                 }
68695                 cache.set(key, result);
68696                 return result;
68697             }
68698             // At flow control branch or loop junctions, if the type along every antecedent code path
68699             // is an evolving array type, we construct a combined evolving array type. Otherwise we
68700             // finalize all evolving array types.
68701             function getUnionOrEvolvingArrayType(types, subtypeReduction) {
68702                 if (isEvolvingArrayTypeList(types)) {
68703                     return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType)));
68704                 }
68705                 var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
68706                 if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && ts.arraysEqual(result.types, declaredType.types)) {
68707                     return declaredType;
68708                 }
68709                 return result;
68710             }
68711             function getDiscriminantPropertyAccess(expr, computedType) {
68712                 var access, name;
68713                 var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
68714                 return type.flags & 1048576 /* Union */ && (access = getPropertyAccess(expr)) && (name = getAccessedPropertyName(access)) &&
68715                     isMatchingReference(reference, ts.isAccessExpression(access) ? access.expression : access.parent.parent.initializer) &&
68716                     isDiscriminantProperty(type, name) ?
68717                     access : undefined;
68718             }
68719             function narrowTypeByDiscriminant(type, access, narrowType) {
68720                 var propName = getAccessedPropertyName(access);
68721                 if (propName === undefined) {
68722                     return type;
68723                 }
68724                 var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */);
68725                 var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName);
68726                 if (!propType) {
68727                     return type;
68728                 }
68729                 propType = removeNullable ? getOptionalType(propType) : propType;
68730                 var narrowedPropType = narrowType(propType);
68731                 return filterType(type, function (t) {
68732                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
68733                     return !(narrowedPropType.flags & 131072 /* Never */) && isTypeComparableTo(narrowedPropType, discriminantType);
68734                 });
68735             }
68736             function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) {
68737                 if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) {
68738                     var keyPropertyName = getKeyPropertyName(type);
68739                     if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) {
68740                         var candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value));
68741                         if (candidate) {
68742                             return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate :
68743                                 isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) :
68744                                     type;
68745                         }
68746                     }
68747                 }
68748                 return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); });
68749             }
68750             function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) {
68751                 if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) {
68752                     var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd);
68753                     var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; }));
68754                     if (candidate !== unknownType) {
68755                         return candidate;
68756                     }
68757                 }
68758                 return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); });
68759             }
68760             function narrowTypeByTruthiness(type, expr, assumeTrue) {
68761                 if (isMatchingReference(reference, expr)) {
68762                     return type.flags & 2 /* Unknown */ && assumeTrue ? nonNullUnknownType :
68763                         getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
68764                 }
68765                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
68766                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
68767                 }
68768                 var access = getDiscriminantPropertyAccess(expr, type);
68769                 if (access) {
68770                     return narrowTypeByDiscriminant(type, access, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
68771                 }
68772                 return type;
68773             }
68774             function isTypePresencePossible(type, propName, assumeTrue) {
68775                 var prop = getPropertyOfType(type, propName);
68776                 if (prop) {
68777                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
68778                 }
68779                 return getApplicableIndexInfoForName(type, propName) ? true : !assumeTrue;
68780             }
68781             function narrowByInKeyword(type, name, assumeTrue) {
68782                 if (type.flags & 1048576 /* Union */
68783                     || type.flags & 524288 /* Object */ && declaredType !== type
68784                     || isThisTypeParameter(type)
68785                     || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) {
68786                     return filterType(type, function (t) { return isTypePresencePossible(t, name, assumeTrue); });
68787                 }
68788                 return type;
68789             }
68790             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
68791                 switch (expr.operatorToken.kind) {
68792                     case 63 /* EqualsToken */:
68793                     case 75 /* BarBarEqualsToken */:
68794                     case 76 /* AmpersandAmpersandEqualsToken */:
68795                     case 77 /* QuestionQuestionEqualsToken */:
68796                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
68797                     case 34 /* EqualsEqualsToken */:
68798                     case 35 /* ExclamationEqualsToken */:
68799                     case 36 /* EqualsEqualsEqualsToken */:
68800                     case 37 /* ExclamationEqualsEqualsToken */:
68801                         var operator = expr.operatorToken.kind;
68802                         var left = getReferenceCandidate(expr.left);
68803                         var right = getReferenceCandidate(expr.right);
68804                         if (left.kind === 215 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) {
68805                             return narrowTypeByTypeof(type, left, operator, right, assumeTrue);
68806                         }
68807                         if (right.kind === 215 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) {
68808                             return narrowTypeByTypeof(type, right, operator, left, assumeTrue);
68809                         }
68810                         if (isMatchingReference(reference, left)) {
68811                             return narrowTypeByEquality(type, operator, right, assumeTrue);
68812                         }
68813                         if (isMatchingReference(reference, right)) {
68814                             return narrowTypeByEquality(type, operator, left, assumeTrue);
68815                         }
68816                         if (strictNullChecks) {
68817                             if (optionalChainContainsReference(left, reference)) {
68818                                 type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue);
68819                             }
68820                             else if (optionalChainContainsReference(right, reference)) {
68821                                 type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue);
68822                             }
68823                         }
68824                         var leftAccess = getDiscriminantPropertyAccess(left, type);
68825                         if (leftAccess) {
68826                             return narrowTypeByDiscriminantProperty(type, leftAccess, operator, right, assumeTrue);
68827                         }
68828                         var rightAccess = getDiscriminantPropertyAccess(right, type);
68829                         if (rightAccess) {
68830                             return narrowTypeByDiscriminantProperty(type, rightAccess, operator, left, assumeTrue);
68831                         }
68832                         if (isMatchingConstructorReference(left)) {
68833                             return narrowTypeByConstructor(type, operator, right, assumeTrue);
68834                         }
68835                         if (isMatchingConstructorReference(right)) {
68836                             return narrowTypeByConstructor(type, operator, left, assumeTrue);
68837                         }
68838                         break;
68839                     case 102 /* InstanceOfKeyword */:
68840                         return narrowTypeByInstanceof(type, expr, assumeTrue);
68841                     case 101 /* InKeyword */:
68842                         if (ts.isPrivateIdentifier(expr.left)) {
68843                             return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue);
68844                         }
68845                         var target = getReferenceCandidate(expr.right);
68846                         var leftType = getTypeOfNode(expr.left);
68847                         if (leftType.flags & 128 /* StringLiteral */) {
68848                             var name = ts.escapeLeadingUnderscores(leftType.value);
68849                             if (containsMissingType(type) && ts.isAccessExpression(reference) && isMatchingReference(reference.expression, target) &&
68850                                 getAccessedPropertyName(reference) === name) {
68851                                 return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
68852                             }
68853                             if (isMatchingReference(reference, target)) {
68854                                 return narrowByInKeyword(type, name, assumeTrue);
68855                             }
68856                         }
68857                         break;
68858                     case 27 /* CommaToken */:
68859                         return narrowType(type, expr.right, assumeTrue);
68860                     // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those
68861                     // expressions down to individual conditional control flows. However, we may encounter them when analyzing
68862                     // aliased conditional expressions.
68863                     case 55 /* AmpersandAmpersandToken */:
68864                         return assumeTrue ?
68865                             narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ true) :
68866                             getUnionType([narrowType(type, expr.left, /*assumeTrue*/ false), narrowType(type, expr.right, /*assumeTrue*/ false)]);
68867                     case 56 /* BarBarToken */:
68868                         return assumeTrue ?
68869                             getUnionType([narrowType(type, expr.left, /*assumeTrue*/ true), narrowType(type, expr.right, /*assumeTrue*/ true)]) :
68870                             narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ false);
68871                 }
68872                 return type;
68873             }
68874             function narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue) {
68875                 var target = getReferenceCandidate(expr.right);
68876                 if (!isMatchingReference(reference, target)) {
68877                     return type;
68878                 }
68879                 ts.Debug.assertNode(expr.left, ts.isPrivateIdentifier);
68880                 var symbol = getSymbolForPrivateIdentifierExpression(expr.left);
68881                 if (symbol === undefined) {
68882                     return type;
68883                 }
68884                 var classSymbol = symbol.parent;
68885                 var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration"))
68886                     ? getTypeOfSymbol(classSymbol)
68887                     : getDeclaredTypeOfSymbol(classSymbol);
68888                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
68889             }
68890             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
68891                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
68892                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
68893                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
68894                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
68895                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
68896                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
68897                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
68898                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
68899                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
68900                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
68901                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
68902                 var valueType = getTypeOfExpression(value);
68903                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
68904                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
68905                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
68906                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
68907             }
68908             function narrowTypeByEquality(type, operator, value, assumeTrue) {
68909                 if (type.flags & 1 /* Any */) {
68910                     return type;
68911                 }
68912                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
68913                     assumeTrue = !assumeTrue;
68914                 }
68915                 var valueType = getTypeOfExpression(value);
68916                 if (assumeTrue && (type.flags & 2 /* Unknown */) && (operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */) && (valueType.flags & 65536 /* Null */)) {
68917                     return getUnionType([nullType, undefinedType]);
68918                 }
68919                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
68920                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
68921                         return valueType;
68922                     }
68923                     if (valueType.flags & 524288 /* Object */) {
68924                         return nonPrimitiveType;
68925                     }
68926                     return type;
68927                 }
68928                 if (valueType.flags & 98304 /* Nullable */) {
68929                     if (!strictNullChecks) {
68930                         return type;
68931                     }
68932                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
68933                     var facts = doubleEquals ?
68934                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
68935                         valueType.flags & 65536 /* Null */ ?
68936                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
68937                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
68938                     return type.flags & 2 /* Unknown */ && facts & (1048576 /* NENull */ | 2097152 /* NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts);
68939                 }
68940                 if (assumeTrue) {
68941                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
68942                         function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } :
68943                         function (t) { return areTypesComparable(t, valueType); };
68944                     return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType);
68945                 }
68946                 if (isUnitType(valueType)) {
68947                     return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); });
68948                 }
68949                 return type;
68950             }
68951             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
68952                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
68953                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
68954                     assumeTrue = !assumeTrue;
68955                 }
68956                 var target = getReferenceCandidate(typeOfExpr.expression);
68957                 if (!isMatchingReference(reference, target)) {
68958                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
68959                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
68960                     }
68961                     return type;
68962                 }
68963                 if (type.flags & 1 /* Any */ && literal.text === "function") {
68964                     return type;
68965                 }
68966                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
68967                     // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type
68968                     // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null
68969                     // unknown type, and then narrows that to the non-primitive type.
68970                     return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]);
68971                 }
68972                 var facts = assumeTrue ?
68973                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
68974                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
68975                 var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text);
68976                 return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts);
68977             }
68978             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
68979                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
68980                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
68981             }
68982             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
68983                 // We only narrow if all case expressions specify
68984                 // values with unit types, except for the case where
68985                 // `type` is unknown. In this instance we map object
68986                 // types to the nonPrimitive type and narrow with that.
68987                 var switchTypes = getSwitchClauseTypes(switchStatement);
68988                 if (!switchTypes.length) {
68989                     return type;
68990                 }
68991                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
68992                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
68993                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
68994                     var groundClauseTypes = void 0;
68995                     for (var i = 0; i < clauseTypes.length; i += 1) {
68996                         var t = clauseTypes[i];
68997                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
68998                             if (groundClauseTypes !== undefined) {
68999                                 groundClauseTypes.push(t);
69000                             }
69001                         }
69002                         else if (t.flags & 524288 /* Object */) {
69003                             if (groundClauseTypes === undefined) {
69004                                 groundClauseTypes = clauseTypes.slice(0, i);
69005                             }
69006                             groundClauseTypes.push(nonPrimitiveType);
69007                         }
69008                         else {
69009                             return type;
69010                         }
69011                     }
69012                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
69013                 }
69014                 var discriminantType = getUnionType(clauseTypes);
69015                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
69016                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
69017                 if (!hasDefaultClause) {
69018                     return caseType;
69019                 }
69020                 var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); });
69021                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
69022             }
69023             function getImpliedTypeFromTypeofGuard(type, text) {
69024                 switch (text) {
69025                     case "function":
69026                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
69027                     case "object":
69028                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
69029                     default:
69030                         return typeofTypesByName.get(text);
69031                 }
69032             }
69033             // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are
69034             // super-types of the implied guard will be retained in the final type: this is because type-facts only
69035             // filter. Instead, we would like to replace those union constituents with the more precise type implied by
69036             // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not
69037             // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to
69038             // filtering by type-facts.
69039             function narrowUnionMemberByTypeof(candidate) {
69040                 return function (type) {
69041                     if (isTypeSubtypeOf(type, candidate)) {
69042                         return type;
69043                     }
69044                     if (isTypeSubtypeOf(candidate, type)) {
69045                         return candidate;
69046                     }
69047                     if (type.flags & 465829888 /* Instantiable */) {
69048                         var constraint = getBaseConstraintOfType(type) || anyType;
69049                         if (isTypeSubtypeOf(candidate, constraint)) {
69050                             return getIntersectionType([type, candidate]);
69051                         }
69052                     }
69053                     return type;
69054                 };
69055             }
69056             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
69057                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
69058                 if (!switchWitnesses.length) {
69059                     return type;
69060                 }
69061                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
69062                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
69063                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
69064                 var clauseWitnesses;
69065                 var switchFacts;
69066                 if (defaultCaseLocation > -1) {
69067                     // We no longer need the undefined denoting an explicit default case. Remove the undefined and
69068                     // fix-up clauseStart and clauseEnd.  This means that we don't have to worry about undefined in the
69069                     // witness array.
69070                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
69071                     // The adjusted clause start and end after removing the `default` statement.
69072                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
69073                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
69074                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
69075                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
69076                 }
69077                 else {
69078                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
69079                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
69080                 }
69081                 if (hasDefaultClause) {
69082                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
69083                 }
69084                 /*
69085                   The implied type is the raw type suggested by a
69086                   value being caught in this clause.
69087
69088                   When the clause contains a default case we ignore
69089                   the implied type and try to narrow using any facts
69090                   we can learn: see `switchFacts`.
69091
69092                   Example:
69093                   switch (typeof x) {
69094                       case 'number':
69095                       case 'string': break;
69096                       default: break;
69097                       case 'number':
69098                       case 'boolean': break
69099                   }
69100
69101                   In the first clause (case `number` and `string`) the
69102                   implied type is number | string.
69103
69104                   In the default clause we de not compute an implied type.
69105
69106                   In the third clause (case `number` and `boolean`)
69107                   the naive implied type is number | boolean, however
69108                   we use the type facts to narrow the implied type to
69109                   boolean. We know that number cannot be selected
69110                   because it is caught in the first clause.
69111                 */
69112                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts);
69113                 return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts);
69114             }
69115             function isMatchingConstructorReference(expr) {
69116                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
69117                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
69118                     isMatchingReference(reference, expr.expression);
69119             }
69120             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
69121                 // Do not narrow when checking inequality.
69122                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
69123                     return type;
69124                 }
69125                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
69126                 var identifierType = getTypeOfExpression(identifier);
69127                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
69128                     return type;
69129                 }
69130                 // Get the prototype property of the type identifier so we can find out its type.
69131                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
69132                 if (!prototypeProperty) {
69133                     return type;
69134                 }
69135                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
69136                 var prototypeType = getTypeOfSymbol(prototypeProperty);
69137                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
69138                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
69139                     return type;
69140                 }
69141                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
69142                 if (isTypeAny(type)) {
69143                     return candidate;
69144                 }
69145                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
69146                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
69147                 function isConstructedBy(source, target) {
69148                     // If either the source or target type are a class type then we need to check that they are the same exact type.
69149                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
69150                     // that defines the same set of properties as class `A`, in that case they are structurally the same
69151                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
69152                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
69153                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
69154                         return source.symbol === target.symbol;
69155                     }
69156                     // For all other types just check that the `source` type is a subtype of the `target` type.
69157                     return isTypeSubtypeOf(source, target);
69158                 }
69159             }
69160             function narrowTypeByInstanceof(type, expr, assumeTrue) {
69161                 var left = getReferenceCandidate(expr.left);
69162                 if (!isMatchingReference(reference, left)) {
69163                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
69164                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
69165                     }
69166                     return type;
69167                 }
69168                 // Check that right operand is a function type with a prototype property
69169                 var rightType = getTypeOfExpression(expr.right);
69170                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
69171                     return type;
69172                 }
69173                 var targetType;
69174                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
69175                 if (prototypeProperty) {
69176                     // Target type is type of the prototype property
69177                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
69178                     if (!isTypeAny(prototypePropertyType)) {
69179                         targetType = prototypePropertyType;
69180                     }
69181                 }
69182                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
69183                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
69184                     return type;
69185                 }
69186                 if (!targetType) {
69187                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
69188                     targetType = constructSignatures.length ?
69189                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
69190                         emptyObjectType;
69191                 }
69192                 // We can't narrow a union based off instanceof without negated types see #31576 for more info
69193                 if (!assumeTrue && rightType.flags & 1048576 /* Union */) {
69194                     var nonConstructorTypeInUnion = ts.find(rightType.types, function (t) { return !isConstructorType(t); });
69195                     if (!nonConstructorTypeInUnion)
69196                         return type;
69197                 }
69198                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
69199             }
69200             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
69201                 if (!assumeTrue) {
69202                     return filterType(type, function (t) { return !isRelated(t, candidate); });
69203                 }
69204                 // If the current type is a union type, remove all constituents that couldn't be instances of
69205                 // the candidate type. If one or more constituents remain, return a union of those.
69206                 if (type.flags & 1048576 /* Union */) {
69207                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
69208                     if (!(assignableType.flags & 131072 /* Never */)) {
69209                         return assignableType;
69210                     }
69211                 }
69212                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
69213                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
69214                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
69215                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
69216                 // two types.
69217                 return isTypeSubtypeOf(candidate, type) ? candidate :
69218                     isTypeAssignableTo(type, candidate) ? type :
69219                         isTypeAssignableTo(candidate, type) ? candidate :
69220                             getIntersectionType([type, candidate]);
69221             }
69222             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
69223                 if (hasMatchingArgument(callExpression, reference)) {
69224                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
69225                     var predicate = signature && getTypePredicateOfSignature(signature);
69226                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
69227                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
69228                     }
69229                 }
69230                 if (containsMissingType(type) && ts.isAccessExpression(reference) && ts.isPropertyAccessExpression(callExpression.expression)) {
69231                     var callAccess = callExpression.expression;
69232                     if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) &&
69233                         ts.isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) {
69234                         var argument = callExpression.arguments[0];
69235                         if (ts.isStringLiteralLike(argument) && getAccessedPropertyName(reference) === ts.escapeLeadingUnderscores(argument.text)) {
69236                             return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
69237                         }
69238                     }
69239                 }
69240                 return type;
69241             }
69242             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
69243                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
69244                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
69245                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
69246                     if (predicateArgument) {
69247                         if (isMatchingReference(reference, predicateArgument)) {
69248                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
69249                         }
69250                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
69251                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
69252                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
69253                         }
69254                         var access = getDiscriminantPropertyAccess(predicateArgument, type);
69255                         if (access) {
69256                             return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
69257                         }
69258                     }
69259                 }
69260                 return type;
69261             }
69262             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
69263             // will be a subtype or the same type as the argument.
69264             function narrowType(type, expr, assumeTrue) {
69265                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
69266                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
69267                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
69268                     return narrowTypeByOptionality(type, expr, assumeTrue);
69269                 }
69270                 switch (expr.kind) {
69271                     case 79 /* Identifier */:
69272                         // When narrowing a reference to a const variable, non-assigned parameter, or readonly property, we inline
69273                         // up to five levels of aliased conditional expressions that are themselves declared as const variables.
69274                         if (!isMatchingReference(reference, expr) && inlineLevel < 5) {
69275                             var symbol = getResolvedSymbol(expr);
69276                             if (isConstVariable(symbol)) {
69277                                 var declaration = symbol.valueDeclaration;
69278                                 if (declaration && ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) {
69279                                     inlineLevel++;
69280                                     var result = narrowType(type, declaration.initializer, assumeTrue);
69281                                     inlineLevel--;
69282                                     return result;
69283                                 }
69284                             }
69285                         }
69286                     // falls through
69287                     case 108 /* ThisKeyword */:
69288                     case 106 /* SuperKeyword */:
69289                     case 205 /* PropertyAccessExpression */:
69290                     case 206 /* ElementAccessExpression */:
69291                         return narrowTypeByTruthiness(type, expr, assumeTrue);
69292                     case 207 /* CallExpression */:
69293                         return narrowTypeByCallExpression(type, expr, assumeTrue);
69294                     case 211 /* ParenthesizedExpression */:
69295                     case 229 /* NonNullExpression */:
69296                         return narrowType(type, expr.expression, assumeTrue);
69297                     case 220 /* BinaryExpression */:
69298                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
69299                     case 218 /* PrefixUnaryExpression */:
69300                         if (expr.operator === 53 /* ExclamationToken */) {
69301                             return narrowType(type, expr.operand, !assumeTrue);
69302                         }
69303                         break;
69304                 }
69305                 return type;
69306             }
69307             function narrowTypeByOptionality(type, expr, assumePresent) {
69308                 if (isMatchingReference(reference, expr)) {
69309                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
69310                 }
69311                 var access = getDiscriminantPropertyAccess(expr, type);
69312                 if (access) {
69313                     return narrowTypeByDiscriminant(type, access, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
69314                 }
69315                 return type;
69316             }
69317         }
69318         function getTypeOfSymbolAtLocation(symbol, location) {
69319             symbol = symbol.exportSymbol || symbol;
69320             // If we have an identifier or a property access at the given location, if the location is
69321             // an dotted name expression, and if the location is not an assignment target, obtain the type
69322             // of the expression (which will reflect control flow analysis). If the expression indeed
69323             // resolved to the given symbol, return the narrowed type.
69324             if (location.kind === 79 /* Identifier */ || location.kind === 80 /* PrivateIdentifier */) {
69325                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
69326                     location = location.parent;
69327                 }
69328                 if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) {
69329                     var type = getTypeOfExpression(location);
69330                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
69331                         return type;
69332                     }
69333                 }
69334             }
69335             if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) {
69336                 return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true);
69337             }
69338             // The location isn't a reference to the given symbol, meaning we're being asked
69339             // a hypothetical question of what type the symbol would have if there was a reference
69340             // to it at the given location. Since we have no control flow information for the
69341             // hypothetical reference (control flow information is created and attached by the
69342             // binder), we simply return the declared type of the symbol.
69343             return getNonMissingTypeOfSymbol(symbol);
69344         }
69345         function getControlFlowContainer(node) {
69346             return ts.findAncestor(node.parent, function (node) {
69347                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
69348                     node.kind === 261 /* ModuleBlock */ ||
69349                     node.kind === 303 /* SourceFile */ ||
69350                     node.kind === 166 /* PropertyDeclaration */;
69351             });
69352         }
69353         // Check if a parameter or catch variable is assigned anywhere
69354         function isSymbolAssigned(symbol) {
69355             if (!symbol.valueDeclaration) {
69356                 return false;
69357             }
69358             var parent = ts.getRootDeclaration(symbol.valueDeclaration).parent;
69359             var links = getNodeLinks(parent);
69360             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
69361                 links.flags |= 8388608 /* AssignmentsMarked */;
69362                 if (!hasParentWithAssignmentsMarked(parent)) {
69363                     markNodeAssignments(parent);
69364                 }
69365             }
69366             return symbol.isAssigned || false;
69367         }
69368         function hasParentWithAssignmentsMarked(node) {
69369             return !!ts.findAncestor(node.parent, function (node) {
69370                 return (ts.isFunctionLike(node) || ts.isCatchClause(node)) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */);
69371             });
69372         }
69373         function markNodeAssignments(node) {
69374             if (node.kind === 79 /* Identifier */) {
69375                 if (ts.isAssignmentTarget(node)) {
69376                     var symbol = getResolvedSymbol(node);
69377                     if (ts.isParameterOrCatchClauseVariable(symbol)) {
69378                         symbol.isAssigned = true;
69379                     }
69380                 }
69381             }
69382             else {
69383                 ts.forEachChild(node, markNodeAssignments);
69384             }
69385         }
69386         function isConstVariable(symbol) {
69387             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0;
69388         }
69389         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
69390         function removeOptionalityFromDeclaredType(declaredType, declaration) {
69391             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
69392                 var annotationIncludesUndefined = strictNullChecks &&
69393                     declaration.kind === 163 /* Parameter */ &&
69394                     declaration.initializer &&
69395                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
69396                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
69397                 popTypeResolution();
69398                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
69399             }
69400             else {
69401                 reportCircularityError(declaration.symbol);
69402                 return declaredType;
69403             }
69404         }
69405         function isConstraintPosition(type, node) {
69406             var parent = node.parent;
69407             // In an element access obj[x], we consider obj to be in a constraint position, except when obj is of
69408             // a generic type without a nullable constraint and x is a generic type. This is because when both obj
69409             // and x are of generic types T and K, we want the resulting type to be T[K].
69410             return parent.kind === 205 /* PropertyAccessExpression */ ||
69411                 parent.kind === 207 /* CallExpression */ && parent.expression === node ||
69412                 parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node &&
69413                     !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression)));
69414         }
69415         function isGenericTypeWithUnionConstraint(type) {
69416             return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */));
69417         }
69418         function isGenericTypeWithoutNullableConstraint(type) {
69419             return !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */));
69420         }
69421         function hasNonBindingPatternContextualTypeWithNoGenericTypes(node) {
69422             // Computing the contextual type for a child of a JSX element involves resolving the type of the
69423             // element's tag name, so we exclude that here to avoid circularities.
69424             var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) &&
69425                 !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) &&
69426                 getContextualType(node, 8 /* SkipBindingPatterns */);
69427             return contextualType && !isGenericType(contextualType);
69428         }
69429         function getNarrowableTypeForReference(type, reference, checkMode) {
69430             // When the type of a reference is or contains an instantiable type with a union type constraint, and
69431             // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or
69432             // has a contextual type containing no top-level instantiables (meaning constraints will determine
69433             // assignability), we substitute constraints for all instantiables in the type of the reference to give
69434             // control flow analysis an opportunity to narrow it further. For example, for a reference of a type
69435             // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute
69436             // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'.
69437             var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) &&
69438                 someType(type, isGenericTypeWithUnionConstraint) &&
69439                 (isConstraintPosition(type, reference) || hasNonBindingPatternContextualTypeWithNoGenericTypes(reference));
69440             return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type;
69441         }
69442         function isExportOrExportExpression(location) {
69443             return !!ts.findAncestor(location, function (n) {
69444                 var parent = n.parent;
69445                 if (parent === undefined) {
69446                     return "quit";
69447                 }
69448                 if (ts.isExportAssignment(parent)) {
69449                     return parent.expression === n && ts.isEntityNameExpression(n);
69450                 }
69451                 if (ts.isExportSpecifier(parent)) {
69452                     return parent.name === n || parent.propertyName === n;
69453                 }
69454                 return false;
69455             });
69456         }
69457         function markAliasReferenced(symbol, location) {
69458             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
69459                 var target = resolveAlias(symbol);
69460                 if (target.flags & 111551 /* Value */) {
69461                     // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled
69462                     // (because the const enum value will not be inlined), or if (2) the alias is an export
69463                     // of a const enum declaration that will be preserved.
69464                     if (compilerOptions.isolatedModules ||
69465                         ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) ||
69466                         !isConstEnumOrConstEnumOnlyModule(target)) {
69467                         markAliasSymbolAsReferenced(symbol);
69468                     }
69469                     else {
69470                         markConstEnumAliasAsReferenced(symbol);
69471                     }
69472                 }
69473             }
69474         }
69475         function checkIdentifier(node, checkMode) {
69476             var symbol = getResolvedSymbol(node);
69477             if (symbol === unknownSymbol) {
69478                 return errorType;
69479             }
69480             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
69481             // Although in down-level emit of arrow function, we emit it using function expression which means that
69482             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
69483             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
69484             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
69485             // can explicitly bound arguments objects
69486             if (symbol === argumentsSymbol) {
69487                 if (isInPropertyInitializerOrClassStaticBlock(node)) {
69488                     error(node, ts.Diagnostics.arguments_cannot_be_referenced_in_property_initializers);
69489                     return errorType;
69490                 }
69491                 var container = ts.getContainingFunction(node);
69492                 if (languageVersion < 2 /* ES2015 */) {
69493                     if (container.kind === 213 /* ArrowFunction */) {
69494                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
69495                     }
69496                     else if (ts.hasSyntacticModifier(container, 256 /* Async */)) {
69497                         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);
69498                     }
69499                 }
69500                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
69501                 return getTypeOfSymbol(symbol);
69502             }
69503             // We should only mark aliases as referenced if there isn't a local value declaration
69504             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
69505             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
69506                 markAliasReferenced(symbol, node);
69507             }
69508             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
69509             var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol;
69510             if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) {
69511                 addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText);
69512             }
69513             var declaration = localOrExportSymbol.valueDeclaration;
69514             if (declaration && localOrExportSymbol.flags & 32 /* Class */) {
69515                 // Due to the emit for class decorators, any reference to the class from inside of the class body
69516                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
69517                 // behavior of class names in ES6.
69518                 if (declaration.kind === 256 /* ClassDeclaration */
69519                     && ts.nodeIsDecorated(declaration)) {
69520                     var container = ts.getContainingClass(node);
69521                     while (container !== undefined) {
69522                         if (container === declaration && container.name !== node) {
69523                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
69524                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
69525                             break;
69526                         }
69527                         container = ts.getContainingClass(container);
69528                     }
69529                 }
69530                 else if (declaration.kind === 225 /* ClassExpression */) {
69531                     // When we emit a class expression with static members that contain a reference
69532                     // to the constructor in the initializer, we will need to substitute that
69533                     // binding with an alias as the class name is not in scope.
69534                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
69535                     while (container.kind !== 303 /* SourceFile */) {
69536                         if (container.parent === declaration) {
69537                             if (ts.isPropertyDeclaration(container) && ts.isStatic(container) || ts.isClassStaticBlockDeclaration(container)) {
69538                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
69539                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
69540                             }
69541                             break;
69542                         }
69543                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
69544                     }
69545                 }
69546             }
69547             checkNestedBlockScopedBinding(node, symbol);
69548             var type = getTypeOfSymbol(localOrExportSymbol);
69549             var assignmentKind = ts.getAssignmentTargetKind(node);
69550             if (assignmentKind) {
69551                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
69552                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
69553                     var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum
69554                         : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class
69555                             : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace
69556                                 : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function
69557                                     : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import
69558                                         : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable;
69559                     error(node, assignmentError, symbolToString(symbol));
69560                     return errorType;
69561                 }
69562                 if (isReadonlySymbol(localOrExportSymbol)) {
69563                     if (localOrExportSymbol.flags & 3 /* Variable */) {
69564                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
69565                     }
69566                     else {
69567                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
69568                     }
69569                     return errorType;
69570                 }
69571             }
69572             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
69573             // We only narrow variables and parameters occurring in a non-assignment position. For all other
69574             // entities we simply return the declared type.
69575             if (localOrExportSymbol.flags & 3 /* Variable */) {
69576                 if (assignmentKind === 1 /* Definite */) {
69577                     return type;
69578                 }
69579             }
69580             else if (isAlias) {
69581                 declaration = getDeclarationOfAliasSymbol(symbol);
69582             }
69583             else {
69584                 return type;
69585             }
69586             if (!declaration) {
69587                 return type;
69588             }
69589             type = getNarrowableTypeForReference(type, node, checkMode);
69590             // The declaration container is the innermost function that encloses the declaration of the variable
69591             // or parameter. The flow container is the innermost function starting with which we analyze the control
69592             // flow graph to determine the control flow based type.
69593             var isParameter = ts.getRootDeclaration(declaration).kind === 163 /* Parameter */;
69594             var declarationContainer = getControlFlowContainer(declaration);
69595             var flowContainer = getControlFlowContainer(node);
69596             var isOuterVariable = flowContainer !== declarationContainer;
69597             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
69598             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
69599             // When the control flow originates in a function expression or arrow function and we are referencing
69600             // a const variable or parameter from an outer function, we extend the origin of the control flow
69601             // analysis to include the immediately enclosing function.
69602             while (flowContainer !== declarationContainer && (flowContainer.kind === 212 /* FunctionExpression */ ||
69603                 flowContainer.kind === 213 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) &&
69604                 (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) {
69605                 flowContainer = getControlFlowContainer(flowContainer);
69606             }
69607             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
69608             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
69609             // declaration container are the same).
69610             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
69611                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
69612                     isInTypeQuery(node) || node.parent.kind === 274 /* ExportSpecifier */) ||
69613                 node.parent.kind === 229 /* NonNullExpression */ ||
69614                 declaration.kind === 253 /* VariableDeclaration */ && declaration.exclamationToken ||
69615                 declaration.flags & 8388608 /* Ambient */;
69616             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
69617                 type === autoType || type === autoArrayType ? undefinedType :
69618                     getOptionalType(type);
69619             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer);
69620             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
69621             // from declaration to use, and when the variable's declared type doesn't include undefined but the
69622             // control flow based type does include undefined.
69623             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
69624                 if (flowType === autoType || flowType === autoArrayType) {
69625                     if (noImplicitAny) {
69626                         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));
69627                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
69628                     }
69629                     return convertAutoToAny(flowType);
69630                 }
69631             }
69632             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
69633                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
69634                 // Return the declared type to reduce follow-on errors
69635                 return type;
69636             }
69637             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
69638         }
69639         function isInsideFunctionOrInstancePropertyInitializer(node, threshold) {
69640             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); });
69641         }
69642         function getPartOfForStatementContainingNode(node, container) {
69643             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
69644         }
69645         function getEnclosingIterationStatement(node) {
69646             return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); });
69647         }
69648         function checkNestedBlockScopedBinding(node, symbol) {
69649             if (languageVersion >= 2 /* ES2015 */ ||
69650                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
69651                 !symbol.valueDeclaration ||
69652                 ts.isSourceFile(symbol.valueDeclaration) ||
69653                 symbol.valueDeclaration.parent.kind === 291 /* CatchClause */) {
69654                 return;
69655             }
69656             // 1. walk from the use site up to the declaration and check
69657             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
69658             // 2. walk from the declaration up to the boundary of lexical environment and check
69659             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
69660             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
69661             var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container);
69662             var enclosingIterationStatement = getEnclosingIterationStatement(container);
69663             if (enclosingIterationStatement) {
69664                 if (isCaptured) {
69665                     // mark iteration statement as containing block-scoped binding captured in some function
69666                     var capturesBlockScopeBindingInLoopBody = true;
69667                     if (ts.isForStatement(container)) {
69668                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 254 /* VariableDeclarationList */);
69669                         if (varDeclList && varDeclList.parent === container) {
69670                             var part = getPartOfForStatementContainingNode(node.parent, container);
69671                             if (part) {
69672                                 var links = getNodeLinks(part);
69673                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
69674                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
69675                                 ts.pushIfUnique(capturedBindings, symbol);
69676                                 if (part === container.initializer) {
69677                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
69678                                 }
69679                             }
69680                         }
69681                     }
69682                     if (capturesBlockScopeBindingInLoopBody) {
69683                         getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
69684                     }
69685                 }
69686                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
69687                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
69688                 if (ts.isForStatement(container)) {
69689                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 254 /* VariableDeclarationList */);
69690                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
69691                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
69692                     }
69693                 }
69694                 // set 'declared inside loop' bit on the block-scoped binding
69695                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
69696             }
69697             if (isCaptured) {
69698                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
69699             }
69700         }
69701         function isBindingCapturedByNode(node, decl) {
69702             var links = getNodeLinks(node);
69703             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
69704         }
69705         function isAssignedInBodyOfForStatement(node, container) {
69706             // skip parenthesized nodes
69707             var current = node;
69708             while (current.parent.kind === 211 /* ParenthesizedExpression */) {
69709                 current = current.parent;
69710             }
69711             // check if node is used as LHS in some assignment expression
69712             var isAssigned = false;
69713             if (ts.isAssignmentTarget(current)) {
69714                 isAssigned = true;
69715             }
69716             else if ((current.parent.kind === 218 /* PrefixUnaryExpression */ || current.parent.kind === 219 /* PostfixUnaryExpression */)) {
69717                 var expr = current.parent;
69718                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
69719             }
69720             if (!isAssigned) {
69721                 return false;
69722             }
69723             // at this point we know that node is the target of assignment
69724             // now check that modification happens inside the statement part of the ForStatement
69725             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
69726         }
69727         function captureLexicalThis(node, container) {
69728             getNodeLinks(node).flags |= 2 /* LexicalThis */;
69729             if (container.kind === 166 /* PropertyDeclaration */ || container.kind === 170 /* Constructor */) {
69730                 var classNode = container.parent;
69731                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
69732             }
69733             else {
69734                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
69735             }
69736         }
69737         function findFirstSuperCall(node) {
69738             return ts.isSuperCall(node) ? node :
69739                 ts.isFunctionLike(node) ? undefined :
69740                     ts.forEachChild(node, findFirstSuperCall);
69741         }
69742         /**
69743          * Check if the given class-declaration extends null then return true.
69744          * Otherwise, return false
69745          * @param classDecl a class declaration to check if it extends null
69746          */
69747         function classDeclarationExtendsNull(classDecl) {
69748             var classSymbol = getSymbolOfNode(classDecl);
69749             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
69750             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
69751             return baseConstructorType === nullWideningType;
69752         }
69753         function checkThisBeforeSuper(node, container, diagnosticMessage) {
69754             var containingClassDecl = container.parent;
69755             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
69756             // If a containing class does not have extends clause or the class extends null
69757             // skip checking whether super statement is called before "this" accessing.
69758             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
69759                 if (node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) {
69760                     error(node, diagnosticMessage);
69761                 }
69762             }
69763         }
69764         function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) {
69765             if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) &&
69766                 container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) {
69767                 error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class);
69768             }
69769         }
69770         function checkThisExpression(node) {
69771             var isNodeInTypeQuery = isInTypeQuery(node);
69772             // Stop at the first arrow function so that we can
69773             // tell whether 'this' needs to be captured.
69774             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
69775             var capturedByArrowFunction = false;
69776             if (container.kind === 170 /* Constructor */) {
69777                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
69778             }
69779             // Now skip arrow functions to get the "real" owner of 'this'.
69780             if (container.kind === 213 /* ArrowFunction */) {
69781                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
69782                 capturedByArrowFunction = true;
69783             }
69784             checkThisInStaticClassFieldInitializerInDecoratedClass(node, container);
69785             switch (container.kind) {
69786                 case 260 /* ModuleDeclaration */:
69787                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
69788                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
69789                     break;
69790                 case 259 /* EnumDeclaration */:
69791                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
69792                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
69793                     break;
69794                 case 170 /* Constructor */:
69795                     if (isInConstructorArgumentInitializer(node, container)) {
69796                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
69797                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
69798                     }
69799                     break;
69800                 case 161 /* ComputedPropertyName */:
69801                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
69802                     break;
69803             }
69804             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
69805             if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
69806                 captureLexicalThis(node, container);
69807             }
69808             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
69809             if (noImplicitThis) {
69810                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
69811                 if (type === globalThisType_1 && capturedByArrowFunction) {
69812                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
69813                 }
69814                 else if (!type) {
69815                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
69816                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
69817                     if (!ts.isSourceFile(container)) {
69818                         var outsideThis = tryGetThisTypeAt(container);
69819                         if (outsideThis && outsideThis !== globalThisType_1) {
69820                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
69821                         }
69822                     }
69823                 }
69824             }
69825             return type || anyType;
69826         }
69827         function tryGetThisTypeAt(node, includeGlobalThis, container) {
69828             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
69829             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
69830             var isInJS = ts.isInJSFile(node);
69831             if (ts.isFunctionLike(container) &&
69832                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
69833                 var thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
69834                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
69835                 // If this is a function in a JS file, it might be a class method.
69836                 if (!thisType) {
69837                     var className = getClassNameFromPrototypeMethod(container);
69838                     if (isInJS && className) {
69839                         var classSymbol = checkExpression(className).symbol;
69840                         if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
69841                             thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
69842                         }
69843                     }
69844                     else if (isJSConstructor(container)) {
69845                         thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
69846                     }
69847                     thisType || (thisType = getContextualThisParameterType(container));
69848                 }
69849                 if (thisType) {
69850                     return getFlowTypeOfReference(node, thisType);
69851                 }
69852             }
69853             if (ts.isClassLike(container.parent)) {
69854                 var symbol = getSymbolOfNode(container.parent);
69855                 var type = ts.isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
69856                 return getFlowTypeOfReference(node, type);
69857             }
69858             if (ts.isSourceFile(container)) {
69859                 // look up in the source file's locals or exports
69860                 if (container.commonJsModuleIndicator) {
69861                     var fileSymbol = getSymbolOfNode(container);
69862                     return fileSymbol && getTypeOfSymbol(fileSymbol);
69863                 }
69864                 else if (container.externalModuleIndicator) {
69865                     // TODO: Maybe issue a better error than 'object is possibly undefined'
69866                     return undefinedType;
69867                 }
69868                 else if (includeGlobalThis) {
69869                     return getTypeOfSymbol(globalThisSymbol);
69870                 }
69871             }
69872         }
69873         function getExplicitThisType(node) {
69874             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
69875             if (ts.isFunctionLike(container)) {
69876                 var signature = getSignatureFromDeclaration(container);
69877                 if (signature.thisParameter) {
69878                     return getExplicitTypeOfSymbol(signature.thisParameter);
69879                 }
69880             }
69881             if (ts.isClassLike(container.parent)) {
69882                 var symbol = getSymbolOfNode(container.parent);
69883                 return ts.isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
69884             }
69885         }
69886         function getClassNameFromPrototypeMethod(container) {
69887             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
69888             if (container.kind === 212 /* FunctionExpression */ &&
69889                 ts.isBinaryExpression(container.parent) &&
69890                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
69891                 // Get the 'x' of 'x.prototype.y = container'
69892                 return container.parent // x.prototype.y = container
69893                     .left // x.prototype.y
69894                     .expression // x.prototype
69895                     .expression; // x
69896             }
69897             // x.prototype = { method() { } }
69898             else if (container.kind === 168 /* MethodDeclaration */ &&
69899                 container.parent.kind === 204 /* ObjectLiteralExpression */ &&
69900                 ts.isBinaryExpression(container.parent.parent) &&
69901                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
69902                 return container.parent.parent.left.expression;
69903             }
69904             // x.prototype = { method: function() { } }
69905             else if (container.kind === 212 /* FunctionExpression */ &&
69906                 container.parent.kind === 294 /* PropertyAssignment */ &&
69907                 container.parent.parent.kind === 204 /* ObjectLiteralExpression */ &&
69908                 ts.isBinaryExpression(container.parent.parent.parent) &&
69909                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
69910                 return container.parent.parent.parent.left.expression;
69911             }
69912             // Object.defineProperty(x, "method", { value: function() { } });
69913             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
69914             // Object.defineProperty(x, "method", { get: () => function() { }) });
69915             else if (container.kind === 212 /* FunctionExpression */ &&
69916                 ts.isPropertyAssignment(container.parent) &&
69917                 ts.isIdentifier(container.parent.name) &&
69918                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
69919                 ts.isObjectLiteralExpression(container.parent.parent) &&
69920                 ts.isCallExpression(container.parent.parent.parent) &&
69921                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
69922                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
69923                 return container.parent.parent.parent.arguments[0].expression;
69924             }
69925             // Object.defineProperty(x, "method", { value() { } });
69926             // Object.defineProperty(x, "method", { set(x: () => void) {} });
69927             // Object.defineProperty(x, "method", { get() { return () => {} } });
69928             else if (ts.isMethodDeclaration(container) &&
69929                 ts.isIdentifier(container.name) &&
69930                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
69931                 ts.isObjectLiteralExpression(container.parent) &&
69932                 ts.isCallExpression(container.parent.parent) &&
69933                 container.parent.parent.arguments[2] === container.parent &&
69934                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
69935                 return container.parent.parent.arguments[0].expression;
69936             }
69937         }
69938         function getTypeForThisExpressionFromJSDoc(node) {
69939             var jsdocType = ts.getJSDocType(node);
69940             if (jsdocType && jsdocType.kind === 315 /* JSDocFunctionType */) {
69941                 var jsDocFunctionType = jsdocType;
69942                 if (jsDocFunctionType.parameters.length > 0 &&
69943                     jsDocFunctionType.parameters[0].name &&
69944                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
69945                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
69946                 }
69947             }
69948             var thisTag = ts.getJSDocThisTag(node);
69949             if (thisTag && thisTag.typeExpression) {
69950                 return getTypeFromTypeNode(thisTag.typeExpression);
69951             }
69952         }
69953         function isInConstructorArgumentInitializer(node, constructorDecl) {
69954             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 163 /* Parameter */ && n.parent === constructorDecl; });
69955         }
69956         function checkSuperExpression(node) {
69957             var isCallExpression = node.parent.kind === 207 /* CallExpression */ && node.parent.expression === node;
69958             var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
69959             var container = immediateContainer;
69960             var needToCaptureLexicalThis = false;
69961             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
69962             if (!isCallExpression) {
69963                 while (container && container.kind === 213 /* ArrowFunction */) {
69964                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
69965                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
69966                 }
69967             }
69968             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
69969             var nodeCheckFlag = 0;
69970             if (!canUseSuperExpression) {
69971                 // issue more specific error if super is used in computed property name
69972                 // class A { foo() { return "1" }}
69973                 // class B {
69974                 //     [super.foo()]() {}
69975                 // }
69976                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 161 /* ComputedPropertyName */; });
69977                 if (current && current.kind === 161 /* ComputedPropertyName */) {
69978                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
69979                 }
69980                 else if (isCallExpression) {
69981                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
69982                 }
69983                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 204 /* ObjectLiteralExpression */)) {
69984                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
69985                 }
69986                 else {
69987                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
69988                 }
69989                 return errorType;
69990             }
69991             if (!isCallExpression && immediateContainer.kind === 170 /* Constructor */) {
69992                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
69993             }
69994             if (ts.isStatic(container) || isCallExpression) {
69995                 nodeCheckFlag = 512 /* SuperStatic */;
69996                 if (!isCallExpression &&
69997                     languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ &&
69998                     (ts.isPropertyDeclaration(container) || ts.isClassStaticBlockDeclaration(container))) {
69999                     // for `super.x` or `super[x]` in a static initializer, mark all enclosing
70000                     // block scope containers so that we can report potential collisions with
70001                     // `Reflect`.
70002                     ts.forEachEnclosingBlockScopeContainer(node.parent, function (current) {
70003                         if (!ts.isSourceFile(current) || ts.isExternalOrCommonJsModule(current)) {
70004                             getNodeLinks(current).flags |= 134217728 /* ContainsSuperPropertyInStaticInitializer */;
70005                         }
70006                     });
70007                 }
70008             }
70009             else {
70010                 nodeCheckFlag = 256 /* SuperInstance */;
70011             }
70012             getNodeLinks(node).flags |= nodeCheckFlag;
70013             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
70014             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
70015             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
70016             // uses an arrow function, which is permitted to reference `super`.
70017             //
70018             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
70019             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
70020             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
70021             //
70022             // The simplest case is reading a value, in which case we will emit something like the following:
70023             //
70024             //  // ts
70025             //  ...
70026             //  async asyncMethod() {
70027             //    let x = await super.asyncMethod();
70028             //    return x;
70029             //  }
70030             //  ...
70031             //
70032             //  // js
70033             //  ...
70034             //  asyncMethod() {
70035             //      const _super = Object.create(null, {
70036             //        asyncMethod: { get: () => super.asyncMethod },
70037             //      });
70038             //      return __awaiter(this, arguments, Promise, function *() {
70039             //          let x = yield _super.asyncMethod.call(this);
70040             //          return x;
70041             //      });
70042             //  }
70043             //  ...
70044             //
70045             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
70046             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
70047             //
70048             //  // ts
70049             //  ...
70050             //  async asyncMethod(ar: Promise<any[]>) {
70051             //      [super.a, super.b] = await ar;
70052             //  }
70053             //  ...
70054             //
70055             //  // js
70056             //  ...
70057             //  asyncMethod(ar) {
70058             //      const _super = Object.create(null, {
70059             //        a: { get: () => super.a, set: (v) => super.a = v },
70060             //        b: { get: () => super.b, set: (v) => super.b = v }
70061             //      };
70062             //      return __awaiter(this, arguments, Promise, function *() {
70063             //          [_super.a, _super.b] = yield ar;
70064             //      });
70065             //  }
70066             //  ...
70067             //
70068             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
70069             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
70070             //
70071             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
70072             if (container.kind === 168 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) {
70073                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
70074                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
70075                 }
70076                 else {
70077                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
70078                 }
70079             }
70080             if (needToCaptureLexicalThis) {
70081                 // call expressions are allowed only in constructors so they should always capture correct 'this'
70082                 // super property access expressions can also appear in arrow functions -
70083                 // in this case they should also use correct lexical this
70084                 captureLexicalThis(node.parent, container);
70085             }
70086             if (container.parent.kind === 204 /* ObjectLiteralExpression */) {
70087                 if (languageVersion < 2 /* ES2015 */) {
70088                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
70089                     return errorType;
70090                 }
70091                 else {
70092                     // for object literal assume that type of 'super' is 'any'
70093                     return anyType;
70094                 }
70095             }
70096             // at this point the only legal case for parent is ClassLikeDeclaration
70097             var classLikeDeclaration = container.parent;
70098             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
70099                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
70100                 return errorType;
70101             }
70102             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
70103             var baseClassType = classType && getBaseTypes(classType)[0];
70104             if (!baseClassType) {
70105                 return errorType;
70106             }
70107             if (container.kind === 170 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
70108                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
70109                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
70110                 return errorType;
70111             }
70112             return nodeCheckFlag === 512 /* SuperStatic */
70113                 ? getBaseConstructorTypeOfClass(classType)
70114                 : getTypeWithThisArgument(baseClassType, classType.thisType);
70115             function isLegalUsageOfSuperExpression(container) {
70116                 if (!container) {
70117                     return false;
70118                 }
70119                 if (isCallExpression) {
70120                     // TS 1.0 SPEC (April 2014): 4.8.1
70121                     // Super calls are only permitted in constructors of derived classes
70122                     return container.kind === 170 /* Constructor */;
70123                 }
70124                 else {
70125                     // TS 1.0 SPEC (April 2014)
70126                     // 'super' property access is allowed
70127                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
70128                     // - In a static member function or static member accessor
70129                     // topmost container must be something that is directly nested in the class declaration\object literal expression
70130                     if (ts.isClassLike(container.parent) || container.parent.kind === 204 /* ObjectLiteralExpression */) {
70131                         if (ts.isStatic(container)) {
70132                             return container.kind === 168 /* MethodDeclaration */ ||
70133                                 container.kind === 167 /* MethodSignature */ ||
70134                                 container.kind === 171 /* GetAccessor */ ||
70135                                 container.kind === 172 /* SetAccessor */ ||
70136                                 container.kind === 166 /* PropertyDeclaration */ ||
70137                                 container.kind === 169 /* ClassStaticBlockDeclaration */;
70138                         }
70139                         else {
70140                             return container.kind === 168 /* MethodDeclaration */ ||
70141                                 container.kind === 167 /* MethodSignature */ ||
70142                                 container.kind === 171 /* GetAccessor */ ||
70143                                 container.kind === 172 /* SetAccessor */ ||
70144                                 container.kind === 166 /* PropertyDeclaration */ ||
70145                                 container.kind === 165 /* PropertySignature */ ||
70146                                 container.kind === 170 /* Constructor */;
70147                         }
70148                     }
70149                 }
70150                 return false;
70151             }
70152         }
70153         function getContainingObjectLiteral(func) {
70154             return (func.kind === 168 /* MethodDeclaration */ ||
70155                 func.kind === 171 /* GetAccessor */ ||
70156                 func.kind === 172 /* SetAccessor */) && func.parent.kind === 204 /* ObjectLiteralExpression */ ? func.parent :
70157                 func.kind === 212 /* FunctionExpression */ && func.parent.kind === 294 /* PropertyAssignment */ ? func.parent.parent :
70158                     undefined;
70159         }
70160         function getThisTypeArgument(type) {
70161             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
70162         }
70163         function getThisTypeFromContextualType(type) {
70164             return mapType(type, function (t) {
70165                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
70166             });
70167         }
70168         function getContextualThisParameterType(func) {
70169             if (func.kind === 213 /* ArrowFunction */) {
70170                 return undefined;
70171             }
70172             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
70173                 var contextualSignature = getContextualSignature(func);
70174                 if (contextualSignature) {
70175                     var thisParameter = contextualSignature.thisParameter;
70176                     if (thisParameter) {
70177                         return getTypeOfSymbol(thisParameter);
70178                     }
70179                 }
70180             }
70181             var inJs = ts.isInJSFile(func);
70182             if (noImplicitThis || inJs) {
70183                 var containingLiteral = getContainingObjectLiteral(func);
70184                 if (containingLiteral) {
70185                     // We have an object literal method. Check if the containing object literal has a contextual type
70186                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
70187                     // any directly enclosing object literals.
70188                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
70189                     var literal = containingLiteral;
70190                     var type = contextualType;
70191                     while (type) {
70192                         var thisType = getThisTypeFromContextualType(type);
70193                         if (thisType) {
70194                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
70195                         }
70196                         if (literal.parent.kind !== 294 /* PropertyAssignment */) {
70197                             break;
70198                         }
70199                         literal = literal.parent.parent;
70200                         type = getApparentTypeOfContextualType(literal);
70201                     }
70202                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
70203                     // for 'this' is the non-null form of the contextual type for the containing object literal or
70204                     // the type of the object literal itself.
70205                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
70206                 }
70207                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
70208                 // contextual type for 'this' is 'obj'.
70209                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
70210                 if (parent.kind === 220 /* BinaryExpression */ && parent.operatorToken.kind === 63 /* EqualsToken */) {
70211                     var target = parent.left;
70212                     if (ts.isAccessExpression(target)) {
70213                         var expression = target.expression;
70214                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
70215                         if (inJs && ts.isIdentifier(expression)) {
70216                             var sourceFile = ts.getSourceFileOfNode(parent);
70217                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
70218                                 return undefined;
70219                             }
70220                         }
70221                         return getWidenedType(checkExpressionCached(expression));
70222                     }
70223                 }
70224             }
70225             return undefined;
70226         }
70227         // Return contextual type of parameter or undefined if no contextual type is available
70228         function getContextuallyTypedParameterType(parameter) {
70229             var func = parameter.parent;
70230             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
70231                 return undefined;
70232             }
70233             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
70234             if (iife && iife.arguments) {
70235                 var args = getEffectiveCallArguments(iife);
70236                 var indexOfParameter = func.parameters.indexOf(parameter);
70237                 if (parameter.dotDotDotToken) {
70238                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined, 0 /* Normal */);
70239                 }
70240                 var links = getNodeLinks(iife);
70241                 var cached = links.resolvedSignature;
70242                 links.resolvedSignature = anySignature;
70243                 var type = indexOfParameter < args.length ?
70244                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
70245                     parameter.initializer ? undefined : undefinedWideningType;
70246                 links.resolvedSignature = cached;
70247                 return type;
70248             }
70249             var contextualSignature = getContextualSignature(func);
70250             if (contextualSignature) {
70251                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
70252                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
70253                     getRestTypeAtPosition(contextualSignature, index) :
70254                     tryGetTypeAtPosition(contextualSignature, index);
70255             }
70256         }
70257         function getContextualTypeForVariableLikeDeclaration(declaration) {
70258             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
70259             if (typeNode) {
70260                 return getTypeFromTypeNode(typeNode);
70261             }
70262             switch (declaration.kind) {
70263                 case 163 /* Parameter */:
70264                     return getContextuallyTypedParameterType(declaration);
70265                 case 202 /* BindingElement */:
70266                     return getContextualTypeForBindingElement(declaration);
70267                 case 166 /* PropertyDeclaration */:
70268                     if (ts.isStatic(declaration)) {
70269                         return getContextualTypeForStaticPropertyDeclaration(declaration);
70270                     }
70271                 // By default, do nothing and return undefined - only the above cases have context implied by a parent
70272             }
70273         }
70274         function getContextualTypeForBindingElement(declaration) {
70275             var parent = declaration.parent.parent;
70276             var name = declaration.propertyName || declaration.name;
70277             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
70278                 parent.kind !== 202 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
70279             if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name))
70280                 return undefined;
70281             if (parent.name.kind === 201 /* ArrayBindingPattern */) {
70282                 var index = ts.indexOfNode(declaration.parent.elements, declaration);
70283                 if (index < 0)
70284                     return undefined;
70285                 return getContextualTypeForElementExpression(parentType, index);
70286             }
70287             var nameType = getLiteralTypeFromPropertyName(name);
70288             if (isTypeUsableAsPropertyName(nameType)) {
70289                 var text = getPropertyNameFromType(nameType);
70290                 return getTypeOfPropertyOfType(parentType, text);
70291             }
70292         }
70293         function getContextualTypeForStaticPropertyDeclaration(declaration) {
70294             var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent);
70295             if (!parentType)
70296                 return undefined;
70297             return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName);
70298         }
70299         // In a variable, parameter or property declaration with a type annotation,
70300         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
70301         // Otherwise, in a parameter declaration of a contextually typed function expression,
70302         //   the contextual type of an initializer expression is the contextual type of the parameter.
70303         // Otherwise, in a variable or parameter declaration with a binding pattern name,
70304         //   the contextual type of an initializer expression is the type implied by the binding pattern.
70305         // Otherwise, in a binding pattern inside a variable or parameter declaration,
70306         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
70307         function getContextualTypeForInitializerExpression(node, contextFlags) {
70308             var declaration = node.parent;
70309             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
70310                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
70311                 if (result) {
70312                     return result;
70313                 }
70314                 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
70315                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
70316                 }
70317             }
70318             return undefined;
70319         }
70320         function getContextualTypeForReturnExpression(node) {
70321             var func = ts.getContainingFunction(node);
70322             if (func) {
70323                 var contextualReturnType = getContextualReturnType(func);
70324                 if (contextualReturnType) {
70325                     var functionFlags = ts.getFunctionFlags(func);
70326                     if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
70327                         var use = functionFlags & 2 /* Async */ ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
70328                         var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined);
70329                         if (!iterationTypes) {
70330                             return undefined;
70331                         }
70332                         contextualReturnType = iterationTypes.returnType;
70333                         // falls through to unwrap Promise for AsyncGenerators
70334                     }
70335                     if (functionFlags & 2 /* Async */) { // Async function or AsyncGenerator function
70336                         // Get the awaited type without the `Awaited<T>` alias
70337                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias);
70338                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
70339                     }
70340                     return contextualReturnType; // Regular function or Generator function
70341                 }
70342             }
70343             return undefined;
70344         }
70345         function getContextualTypeForAwaitOperand(node, contextFlags) {
70346             var contextualType = getContextualType(node, contextFlags);
70347             if (contextualType) {
70348                 var contextualAwaitedType = getAwaitedTypeNoAlias(contextualType);
70349                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
70350             }
70351             return undefined;
70352         }
70353         function getContextualTypeForYieldOperand(node) {
70354             var func = ts.getContainingFunction(node);
70355             if (func) {
70356                 var functionFlags = ts.getFunctionFlags(func);
70357                 var contextualReturnType = getContextualReturnType(func);
70358                 if (contextualReturnType) {
70359                     return node.asteriskToken
70360                         ? contextualReturnType
70361                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
70362                 }
70363             }
70364             return undefined;
70365         }
70366         function isInParameterInitializerBeforeContainingFunction(node) {
70367             var inBindingInitializer = false;
70368             while (node.parent && !ts.isFunctionLike(node.parent)) {
70369                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
70370                     return true;
70371                 }
70372                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
70373                     inBindingInitializer = true;
70374                 }
70375                 node = node.parent;
70376             }
70377             return false;
70378         }
70379         function getContextualIterationType(kind, functionDecl) {
70380             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
70381             var contextualReturnType = getContextualReturnType(functionDecl);
70382             if (contextualReturnType) {
70383                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
70384                     || undefined;
70385             }
70386             return undefined;
70387         }
70388         function getContextualReturnType(functionDecl) {
70389             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
70390             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
70391             var returnType = getReturnTypeFromAnnotation(functionDecl);
70392             if (returnType) {
70393                 return returnType;
70394             }
70395             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
70396             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
70397             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
70398             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
70399                 return getReturnTypeOfSignature(signature);
70400             }
70401             var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl);
70402             if (iife) {
70403                 return getContextualType(iife);
70404             }
70405             return undefined;
70406         }
70407         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
70408         function getContextualTypeForArgument(callTarget, arg) {
70409             var args = getEffectiveCallArguments(callTarget);
70410             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
70411             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
70412         }
70413         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
70414             if (ts.isImportCall(callTarget)) {
70415                 return argIndex === 0 ? stringType :
70416                     argIndex === 1 ? getGlobalImportCallOptionsType(/*reportErrors*/ false) :
70417                         anyType;
70418             }
70419             // If we're already in the process of resolving the given signature, don't resolve again as
70420             // that could cause infinite recursion. Instead, return anySignature.
70421             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
70422             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
70423                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
70424             }
70425             var restIndex = signature.parameters.length - 1;
70426             return signatureHasRestParameter(signature) && argIndex >= restIndex ?
70427                 getIndexedAccessType(getTypeOfSymbol(signature.parameters[restIndex]), getNumberLiteralType(argIndex - restIndex), 256 /* Contextual */) :
70428                 getTypeAtPosition(signature, argIndex);
70429         }
70430         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
70431             if (template.parent.kind === 209 /* TaggedTemplateExpression */) {
70432                 return getContextualTypeForArgument(template.parent, substitutionExpression);
70433             }
70434             return undefined;
70435         }
70436         function getContextualTypeForBinaryOperand(node, contextFlags) {
70437             var binaryExpression = node.parent;
70438             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
70439             switch (operatorToken.kind) {
70440                 case 63 /* EqualsToken */:
70441                 case 76 /* AmpersandAmpersandEqualsToken */:
70442                 case 75 /* BarBarEqualsToken */:
70443                 case 77 /* QuestionQuestionEqualsToken */:
70444                     return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : undefined;
70445                 case 56 /* BarBarToken */:
70446                 case 60 /* QuestionQuestionToken */:
70447                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
70448                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
70449                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
70450                     // by the type of the left operand, except for the special case of Javascript declarations of the form
70451                     // `namespace.prop = namespace.prop || {}`.
70452                     var type = getContextualType(binaryExpression, contextFlags);
70453                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
70454                         getTypeOfExpression(left) : type;
70455                 case 55 /* AmpersandAmpersandToken */:
70456                 case 27 /* CommaToken */:
70457                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
70458                 default:
70459                     return undefined;
70460             }
70461         }
70462         /**
70463          * Try to find a resolved symbol for an expression without also resolving its type, as
70464          * getSymbolAtLocation would (as that could be reentrant into contextual typing)
70465          */
70466         function getSymbolForExpression(e) {
70467             if (e.symbol) {
70468                 return e.symbol;
70469             }
70470             if (ts.isIdentifier(e)) {
70471                 return getResolvedSymbol(e);
70472             }
70473             if (ts.isPropertyAccessExpression(e)) {
70474                 var lhsType = getTypeOfExpression(e.expression);
70475                 return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText);
70476             }
70477             return undefined;
70478             function tryGetPrivateIdentifierPropertyOfType(type, id) {
70479                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id);
70480                 return lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(type, lexicallyScopedSymbol);
70481             }
70482         }
70483         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
70484         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
70485         function getContextualTypeForAssignmentDeclaration(binaryExpression) {
70486             var _a, _b;
70487             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
70488             switch (kind) {
70489                 case 0 /* None */:
70490                 case 4 /* ThisProperty */:
70491                     var lhsSymbol = getSymbolForExpression(binaryExpression.left);
70492                     var decl = lhsSymbol && lhsSymbol.valueDeclaration;
70493                     // Unannotated, uninitialized property declarations have a type implied by their usage in the constructor.
70494                     // We avoid calling back into `getTypeOfExpression` and reentering contextual typing to avoid a bogus circularity error in that case.
70495                     if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) {
70496                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
70497                         return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) ||
70498                             (decl.initializer && getTypeOfExpression(binaryExpression.left));
70499                     }
70500                     if (kind === 0 /* None */) {
70501                         return getTypeOfExpression(binaryExpression.left);
70502                     }
70503                     return getContextualTypeForThisPropertyAssignment(binaryExpression);
70504                 case 5 /* Property */:
70505                     if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
70506                         return getContextualTypeForThisPropertyAssignment(binaryExpression);
70507                     }
70508                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
70509                     // See `bindStaticPropertyAssignment` in `binder.ts`.
70510                     else if (!binaryExpression.left.symbol) {
70511                         return getTypeOfExpression(binaryExpression.left);
70512                     }
70513                     else {
70514                         var decl_1 = binaryExpression.left.symbol.valueDeclaration;
70515                         if (!decl_1) {
70516                             return undefined;
70517                         }
70518                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
70519                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl_1);
70520                         if (overallAnnotation) {
70521                             return getTypeFromTypeNode(overallAnnotation);
70522                         }
70523                         else if (ts.isIdentifier(lhs.expression)) {
70524                             var id = lhs.expression;
70525                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
70526                             if (parentSymbol) {
70527                                 var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
70528                                 if (annotated_1) {
70529                                     var nameStr = ts.getElementOrPropertyAccessName(lhs);
70530                                     if (nameStr !== undefined) {
70531                                         return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr);
70532                                     }
70533                                 }
70534                                 return undefined;
70535                             }
70536                         }
70537                         return ts.isInJSFile(decl_1) ? undefined : getTypeOfExpression(binaryExpression.left);
70538                     }
70539                 case 1 /* ExportsProperty */:
70540                 case 6 /* Prototype */:
70541                 case 3 /* PrototypeProperty */:
70542                     var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
70543                 // falls through
70544                 case 2 /* ModuleExports */:
70545                     valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration);
70546                     var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration);
70547                     return annotated ? getTypeFromTypeNode(annotated) : undefined;
70548                 case 7 /* ObjectDefinePropertyValue */:
70549                 case 8 /* ObjectDefinePropertyExports */:
70550                 case 9 /* ObjectDefinePrototypeProperty */:
70551                     return ts.Debug.fail("Does not apply");
70552                 default:
70553                     return ts.Debug.assertNever(kind);
70554             }
70555         }
70556         function isPossiblyAliasedThisProperty(declaration, kind) {
70557             if (kind === void 0) { kind = ts.getAssignmentDeclarationKind(declaration); }
70558             if (kind === 4 /* ThisProperty */) {
70559                 return true;
70560             }
70561             if (!ts.isInJSFile(declaration) || kind !== 5 /* Property */ || !ts.isIdentifier(declaration.left.expression)) {
70562                 return false;
70563             }
70564             var name = declaration.left.expression.escapedText;
70565             var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true);
70566             return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration);
70567         }
70568         function getContextualTypeForThisPropertyAssignment(binaryExpression) {
70569             if (!binaryExpression.symbol)
70570                 return getTypeOfExpression(binaryExpression.left);
70571             if (binaryExpression.symbol.valueDeclaration) {
70572                 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
70573                 if (annotated) {
70574                     var type = getTypeFromTypeNode(annotated);
70575                     if (type) {
70576                         return type;
70577                     }
70578                 }
70579             }
70580             var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
70581             if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
70582                 return undefined;
70583             }
70584             var thisType = checkThisExpression(thisAccess.expression);
70585             var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
70586             return nameStr !== undefined && getTypeOfPropertyOfContextualType(thisType, nameStr) || undefined;
70587         }
70588         function isCircularMappedProperty(symbol) {
70589             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
70590         }
70591         function getTypeOfPropertyOfContextualType(type, name) {
70592             return mapType(type, function (t) {
70593                 var _a;
70594                 if (isGenericMappedType(t)) {
70595                     var constraint = getConstraintTypeFromMappedType(t);
70596                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
70597                     var propertyNameType = getStringLiteralType(ts.unescapeLeadingUnderscores(name));
70598                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
70599                         return substituteIndexedMappedType(t, propertyNameType);
70600                     }
70601                 }
70602                 else if (t.flags & 3670016 /* StructuredType */) {
70603                     var prop = getPropertyOfType(t, name);
70604                     if (prop) {
70605                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
70606                     }
70607                     if (isTupleType(t)) {
70608                         var restType = getRestTypeOfTupleType(t);
70609                         if (restType && isNumericLiteralName(name) && +name >= 0) {
70610                             return restType;
70611                         }
70612                     }
70613                     return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), getStringLiteralType(ts.unescapeLeadingUnderscores(name)))) === null || _a === void 0 ? void 0 : _a.type;
70614                 }
70615                 return undefined;
70616             }, /*noReductions*/ true);
70617         }
70618         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
70619         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
70620         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
70621         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
70622             ts.Debug.assert(ts.isObjectLiteralMethod(node));
70623             if (node.flags & 16777216 /* InWithStatement */) {
70624                 // We cannot answer semantic questions within a with block, do not proceed any further
70625                 return undefined;
70626             }
70627             return getContextualTypeForObjectLiteralElement(node, contextFlags);
70628         }
70629         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
70630             var objectLiteral = element.parent;
70631             var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element);
70632             if (propertyAssignmentType) {
70633                 return propertyAssignmentType;
70634             }
70635             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
70636             if (type) {
70637                 if (hasBindableName(element)) {
70638                     // For a (non-symbol) computed property, there is no reason to look up the name
70639                     // in the type. It will just be "__computed", which does not appear in any
70640                     // SymbolTable.
70641                     return getTypeOfPropertyOfContextualType(type, getSymbolOfNode(element).escapedName);
70642                 }
70643                 if (element.name) {
70644                     var nameType_2 = getLiteralTypeFromPropertyName(element.name);
70645                     // We avoid calling getApplicableIndexInfo here because it performs potentially expensive intersection reduction.
70646                     return mapType(type, function (t) { var _a; return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType_2)) === null || _a === void 0 ? void 0 : _a.type; }, /*noReductions*/ true);
70647                 }
70648             }
70649             return undefined;
70650         }
70651         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
70652         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
70653         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
70654         // type of T.
70655         function getContextualTypeForElementExpression(arrayContextualType, index) {
70656             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
70657                 || mapType(arrayContextualType, function (t) { return getIteratedTypeOrElementType(1 /* Element */, t, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); }, 
70658                 /*noReductions*/ true));
70659         }
70660         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
70661         function getContextualTypeForConditionalOperand(node, contextFlags) {
70662             var conditional = node.parent;
70663             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
70664         }
70665         function getContextualTypeForChildJsxExpression(node, child) {
70666             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
70667             // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty)
70668             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
70669             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
70670                 return undefined;
70671             }
70672             var realChildren = ts.getSemanticJsxChildren(node.children);
70673             var childIndex = realChildren.indexOf(child);
70674             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
70675             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
70676                 if (isArrayLikeType(t)) {
70677                     return getIndexedAccessType(t, getNumberLiteralType(childIndex));
70678                 }
70679                 else {
70680                     return t;
70681                 }
70682             }, /*noReductions*/ true));
70683         }
70684         function getContextualTypeForJsxExpression(node) {
70685             var exprParent = node.parent;
70686             return ts.isJsxAttributeLike(exprParent)
70687                 ? getContextualType(node)
70688                 : ts.isJsxElement(exprParent)
70689                     ? getContextualTypeForChildJsxExpression(exprParent, node)
70690                     : undefined;
70691         }
70692         function getContextualTypeForJsxAttribute(attribute) {
70693             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
70694             // which is a type of the parameter of the signature we are trying out.
70695             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
70696             if (ts.isJsxAttribute(attribute)) {
70697                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
70698                 if (!attributesType || isTypeAny(attributesType)) {
70699                     return undefined;
70700                 }
70701                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
70702             }
70703             else {
70704                 return getContextualType(attribute.parent);
70705             }
70706         }
70707         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
70708         // expressions we check to those that don't depend on their contextual type in order not to cause
70709         // recursive (and possibly infinite) invocations of getContextualType.
70710         function isPossiblyDiscriminantValue(node) {
70711             switch (node.kind) {
70712                 case 10 /* StringLiteral */:
70713                 case 8 /* NumericLiteral */:
70714                 case 9 /* BigIntLiteral */:
70715                 case 14 /* NoSubstitutionTemplateLiteral */:
70716                 case 110 /* TrueKeyword */:
70717                 case 95 /* FalseKeyword */:
70718                 case 104 /* NullKeyword */:
70719                 case 79 /* Identifier */:
70720                 case 152 /* UndefinedKeyword */:
70721                     return true;
70722                 case 205 /* PropertyAccessExpression */:
70723                 case 211 /* ParenthesizedExpression */:
70724                     return isPossiblyDiscriminantValue(node.expression);
70725                 case 287 /* JsxExpression */:
70726                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
70727             }
70728             return false;
70729         }
70730         function discriminateContextualTypeByObjectMembers(node, contextualType) {
70731             return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType);
70732         }
70733         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
70734             return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType);
70735         }
70736         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
70737         // be "pushed" onto a node using the contextualType property.
70738         function getApparentTypeOfContextualType(node, contextFlags) {
70739             var contextualType = ts.isObjectLiteralMethod(node) ?
70740                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
70741                 getContextualType(node, contextFlags);
70742             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
70743             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
70744                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
70745                 return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) :
70746                     apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) :
70747                         apparentType;
70748             }
70749         }
70750         // If the given contextual type contains instantiable types and if a mapper representing
70751         // return type inferences is available, instantiate those types using that mapper.
70752         function instantiateContextualType(contextualType, node, contextFlags) {
70753             if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
70754                 var inferenceContext = getInferenceContext(node);
70755                 // If no inferences have been made, nothing is gained from instantiating as type parameters
70756                 // would just be replaced with their defaults similar to the apparent type.
70757                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
70758                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
70759                     // types as well as arguments to the left in a function call.
70760                     if (contextFlags && contextFlags & 1 /* Signature */) {
70761                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
70762                     }
70763                     // For other purposes (e.g. determining whether to produce literal types) we only
70764                     // incorporate inferences made from the return type in a function call.
70765                     if (inferenceContext.returnMapper) {
70766                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
70767                     }
70768                 }
70769             }
70770             return contextualType;
70771         }
70772         // This function is similar to instantiateType, except that (a) it only instantiates types that
70773         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
70774         // no reductions on instantiated union types.
70775         function instantiateInstantiableTypes(type, mapper) {
70776             if (type.flags & 465829888 /* Instantiable */) {
70777                 return instantiateType(type, mapper);
70778             }
70779             if (type.flags & 1048576 /* Union */) {
70780                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
70781             }
70782             if (type.flags & 2097152 /* Intersection */) {
70783                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
70784             }
70785             return type;
70786         }
70787         /**
70788          * Whoa! Do you really want to use this function?
70789          *
70790          * Unless you're trying to get the *non-apparent* type for a
70791          * value-literal type or you're authoring relevant portions of this algorithm,
70792          * you probably meant to use 'getApparentTypeOfContextualType'.
70793          * Otherwise this may not be very useful.
70794          *
70795          * In cases where you *are* working on this function, you should understand
70796          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
70797          *
70798          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
70799          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
70800          *
70801          * @param node the expression whose contextual type will be returned.
70802          * @returns the contextual type of an expression.
70803          */
70804         function getContextualType(node, contextFlags) {
70805             if (node.flags & 16777216 /* InWithStatement */) {
70806                 // We cannot answer semantic questions within a with block, do not proceed any further
70807                 return undefined;
70808             }
70809             if (node.contextualType) {
70810                 return node.contextualType;
70811             }
70812             var parent = node.parent;
70813             switch (parent.kind) {
70814                 case 253 /* VariableDeclaration */:
70815                 case 163 /* Parameter */:
70816                 case 166 /* PropertyDeclaration */:
70817                 case 165 /* PropertySignature */:
70818                 case 202 /* BindingElement */:
70819                     return getContextualTypeForInitializerExpression(node, contextFlags);
70820                 case 213 /* ArrowFunction */:
70821                 case 246 /* ReturnStatement */:
70822                     return getContextualTypeForReturnExpression(node);
70823                 case 223 /* YieldExpression */:
70824                     return getContextualTypeForYieldOperand(parent);
70825                 case 217 /* AwaitExpression */:
70826                     return getContextualTypeForAwaitOperand(parent, contextFlags);
70827                 case 207 /* CallExpression */:
70828                 case 208 /* NewExpression */:
70829                     return getContextualTypeForArgument(parent, node);
70830                 case 210 /* TypeAssertionExpression */:
70831                 case 228 /* AsExpression */:
70832                     return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type);
70833                 case 220 /* BinaryExpression */:
70834                     return getContextualTypeForBinaryOperand(node, contextFlags);
70835                 case 294 /* PropertyAssignment */:
70836                 case 295 /* ShorthandPropertyAssignment */:
70837                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
70838                 case 296 /* SpreadAssignment */:
70839                     return getContextualType(parent.parent, contextFlags);
70840                 case 203 /* ArrayLiteralExpression */: {
70841                     var arrayLiteral = parent;
70842                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
70843                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
70844                 }
70845                 case 221 /* ConditionalExpression */:
70846                     return getContextualTypeForConditionalOperand(node, contextFlags);
70847                 case 232 /* TemplateSpan */:
70848                     ts.Debug.assert(parent.parent.kind === 222 /* TemplateExpression */);
70849                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
70850                 case 211 /* ParenthesizedExpression */: {
70851                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
70852                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
70853                     return !tag ? getContextualType(parent, contextFlags) :
70854                         ts.isJSDocTypeTag(tag) && ts.isConstTypeReference(tag.typeExpression.type) ? tryFindWhenConstTypeReference(parent) :
70855                             getTypeFromTypeNode(tag.typeExpression.type);
70856                 }
70857                 case 229 /* NonNullExpression */:
70858                     return getContextualType(parent, contextFlags);
70859                 case 287 /* JsxExpression */:
70860                     return getContextualTypeForJsxExpression(parent);
70861                 case 284 /* JsxAttribute */:
70862                 case 286 /* JsxSpreadAttribute */:
70863                     return getContextualTypeForJsxAttribute(parent);
70864                 case 279 /* JsxOpeningElement */:
70865                 case 278 /* JsxSelfClosingElement */:
70866                     return getContextualJsxElementAttributesType(parent, contextFlags);
70867             }
70868             return undefined;
70869             function tryFindWhenConstTypeReference(node) {
70870                 return getContextualType(node);
70871             }
70872         }
70873         function getInferenceContext(node) {
70874             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
70875             return ancestor && ancestor.inferenceContext;
70876         }
70877         function getContextualJsxElementAttributesType(node, contextFlags) {
70878             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
70879                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
70880                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
70881                 // (as below) instead!
70882                 return node.parent.contextualType;
70883             }
70884             return getContextualTypeForArgumentAtIndex(node, 0);
70885         }
70886         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
70887             return getJsxReferenceKind(node) !== 0 /* Component */
70888                 ? getJsxPropsTypeFromCallSignature(signature, node)
70889                 : getJsxPropsTypeFromClassType(signature, node);
70890         }
70891         function getJsxPropsTypeFromCallSignature(sig, context) {
70892             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
70893             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
70894             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
70895             if (!isErrorType(intrinsicAttribs)) {
70896                 propsType = intersectTypes(intrinsicAttribs, propsType);
70897             }
70898             return propsType;
70899         }
70900         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
70901             if (sig.compositeSignatures) {
70902                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
70903                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
70904                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
70905                 // 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.
70906                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
70907                 var results = [];
70908                 for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) {
70909                     var signature = _a[_i];
70910                     var instance = getReturnTypeOfSignature(signature);
70911                     if (isTypeAny(instance)) {
70912                         return instance;
70913                     }
70914                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
70915                     if (!propType) {
70916                         return;
70917                     }
70918                     results.push(propType);
70919                 }
70920                 return getIntersectionType(results); // Same result for both union and intersection signatures
70921             }
70922             var instanceType = getReturnTypeOfSignature(sig);
70923             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
70924         }
70925         function getStaticTypeOfReferencedJsxConstructor(context) {
70926             if (isJsxIntrinsicIdentifier(context.tagName)) {
70927                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
70928                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
70929                 return getOrCreateTypeFromSignature(fakeSignature);
70930             }
70931             var tagType = checkExpressionCached(context.tagName);
70932             if (tagType.flags & 128 /* StringLiteral */) {
70933                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
70934                 if (!result) {
70935                     return errorType;
70936                 }
70937                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
70938                 return getOrCreateTypeFromSignature(fakeSignature);
70939             }
70940             return tagType;
70941         }
70942         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
70943             var managedSym = getJsxLibraryManagedAttributes(ns);
70944             if (managedSym) {
70945                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters
70946                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
70947                 if (managedSym.flags & 524288 /* TypeAlias */) {
70948                     var params = getSymbolLinks(managedSym).typeParameters;
70949                     if (ts.length(params) >= 2) {
70950                         var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context));
70951                         return getTypeAliasInstantiation(managedSym, args);
70952                     }
70953                 }
70954                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
70955                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
70956                     return createTypeReference(declaredManagedType, args);
70957                 }
70958             }
70959             return attributesType;
70960         }
70961         function getJsxPropsTypeFromClassType(sig, context) {
70962             var ns = getJsxNamespaceAt(context);
70963             var forcedLookupLocation = getJsxElementPropertiesName(ns);
70964             var attributesType = forcedLookupLocation === undefined
70965                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
70966                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
70967                 : forcedLookupLocation === ""
70968                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
70969                     ? getReturnTypeOfSignature(sig)
70970                     // Otherwise get the type of the property on the signature return type
70971                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
70972             if (!attributesType) {
70973                 // There is no property named 'props' on this instance type
70974                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
70975                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
70976                 }
70977                 return unknownType;
70978             }
70979             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
70980             if (isTypeAny(attributesType)) {
70981                 // Props is of type 'any' or unknown
70982                 return attributesType;
70983             }
70984             else {
70985                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
70986                 var apparentAttributesType = attributesType;
70987                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
70988                 if (!isErrorType(intrinsicClassAttribs)) {
70989                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
70990                     var hostClassType = getReturnTypeOfSignature(sig);
70991                     apparentAttributesType = intersectTypes(typeParams
70992                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
70993                         : intrinsicClassAttribs, apparentAttributesType);
70994                 }
70995                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
70996                 if (!isErrorType(intrinsicAttribs)) {
70997                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
70998                 }
70999                 return apparentAttributesType;
71000             }
71001         }
71002         function getIntersectedSignatures(signatures) {
71003             return ts.getStrictOptionValue(compilerOptions, "noImplicitAny")
71004                 ? ts.reduceLeft(signatures, function (left, right) {
71005                     return left === right || !left ? left
71006                         : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right)
71007                             : undefined;
71008                 })
71009                 : undefined;
71010         }
71011         function combineIntersectionThisParam(left, right, mapper) {
71012             if (!left || !right) {
71013                 return left || right;
71014             }
71015             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
71016             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
71017             // pessimistic when contextual typing, for now, we'll union the `this` types.
71018             var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
71019             return createSymbolWithType(left, thisType);
71020         }
71021         function combineIntersectionParameters(left, right, mapper) {
71022             var leftCount = getParameterCount(left);
71023             var rightCount = getParameterCount(right);
71024             var longest = leftCount >= rightCount ? left : right;
71025             var shorter = longest === left ? right : left;
71026             var longestCount = longest === left ? leftCount : rightCount;
71027             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
71028             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
71029             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
71030             for (var i = 0; i < longestCount; i++) {
71031                 var longestParamType = tryGetTypeAtPosition(longest, i);
71032                 if (longest === right) {
71033                     longestParamType = instantiateType(longestParamType, mapper);
71034                 }
71035                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
71036                 if (shorter === right) {
71037                     shorterParamType = instantiateType(shorterParamType, mapper);
71038                 }
71039                 var unionParamType = getUnionType([longestParamType, shorterParamType]);
71040                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
71041                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
71042                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
71043                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
71044                 var paramName = leftName === rightName ? leftName :
71045                     !leftName ? rightName :
71046                         !rightName ? leftName :
71047                             undefined;
71048                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg".concat(i));
71049                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
71050                 params[i] = paramSymbol;
71051             }
71052             if (needsExtraRestElement) {
71053                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
71054                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
71055                 if (shorter === right) {
71056                     restParamSymbol.type = instantiateType(restParamSymbol.type, mapper);
71057                 }
71058                 params[longestCount] = restParamSymbol;
71059             }
71060             return params;
71061         }
71062         function combineSignaturesOfIntersectionMembers(left, right) {
71063             var typeParams = left.typeParameters || right.typeParameters;
71064             var paramMapper;
71065             if (left.typeParameters && right.typeParameters) {
71066                 paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
71067                 // We just use the type parameter defaults from the first signature
71068             }
71069             var declaration = left.declaration;
71070             var params = combineIntersectionParameters(left, right, paramMapper);
71071             var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper);
71072             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
71073             var result = createSignature(declaration, typeParams, thisParam, params, 
71074             /*resolvedReturnType*/ undefined, 
71075             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */);
71076             result.compositeKind = 2097152 /* Intersection */;
71077             result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]);
71078             if (paramMapper) {
71079                 result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
71080             }
71081             return result;
71082         }
71083         // If the given type is an object or union type with a single signature, and if that signature has at
71084         // least as many parameters as the given function, return the signature. Otherwise return undefined.
71085         function getContextualCallSignature(type, node) {
71086             var signatures = getSignaturesOfType(type, 0 /* Call */);
71087             var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); });
71088             return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity);
71089         }
71090         /** If the contextual signature has fewer parameters than the function expression, do not use it */
71091         function isAritySmaller(signature, target) {
71092             var targetParameterCount = 0;
71093             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
71094                 var param = target.parameters[targetParameterCount];
71095                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
71096                     break;
71097                 }
71098             }
71099             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
71100                 targetParameterCount--;
71101             }
71102             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
71103         }
71104         function getContextualSignatureForFunctionLikeDeclaration(node) {
71105             // Only function expressions, arrow functions, and object literal methods are contextually typed.
71106             return ts.isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
71107                 ? getContextualSignature(node)
71108                 : undefined;
71109         }
71110         // Return the contextual signature for a given expression node. A contextual type provides a
71111         // contextual signature if it has a single call signature and if that call signature is non-generic.
71112         // If the contextual type is a union type, get the signature from each type possible and if they are
71113         // all identical ignoring their return type, the result is same signature but with return type as
71114         // union type of return types from these signatures
71115         function getContextualSignature(node) {
71116             ts.Debug.assert(node.kind !== 168 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
71117             var typeTagSignature = getSignatureOfTypeTag(node);
71118             if (typeTagSignature) {
71119                 return typeTagSignature;
71120             }
71121             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
71122             if (!type) {
71123                 return undefined;
71124             }
71125             if (!(type.flags & 1048576 /* Union */)) {
71126                 return getContextualCallSignature(type, node);
71127             }
71128             var signatureList;
71129             var types = type.types;
71130             for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
71131                 var current = types_19[_i];
71132                 var signature = getContextualCallSignature(current, node);
71133                 if (signature) {
71134                     if (!signatureList) {
71135                         // This signature will contribute to contextual union signature
71136                         signatureList = [signature];
71137                     }
71138                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
71139                         // Signatures aren't identical, do not use
71140                         return undefined;
71141                     }
71142                     else {
71143                         // Use this signature for contextual union signature
71144                         signatureList.push(signature);
71145                     }
71146                 }
71147             }
71148             // Result is union of signatures collected (return type is union of return types of this signature set)
71149             if (signatureList) {
71150                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
71151             }
71152         }
71153         function checkSpreadExpression(node, checkMode) {
71154             if (languageVersion < 2 /* ES2015 */) {
71155                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
71156             }
71157             var arrayOrIterableType = checkExpression(node.expression, checkMode);
71158             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
71159         }
71160         function checkSyntheticExpression(node) {
71161             return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
71162         }
71163         function hasDefaultValue(node) {
71164             return (node.kind === 202 /* BindingElement */ && !!node.initializer) ||
71165                 (node.kind === 220 /* BinaryExpression */ && node.operatorToken.kind === 63 /* EqualsToken */);
71166         }
71167         function checkArrayLiteral(node, checkMode, forceTuple) {
71168             var elements = node.elements;
71169             var elementCount = elements.length;
71170             var elementTypes = [];
71171             var elementFlags = [];
71172             var contextualType = getApparentTypeOfContextualType(node);
71173             var inDestructuringPattern = ts.isAssignmentTarget(node);
71174             var inConstContext = isConstContext(node);
71175             var hasOmittedExpression = false;
71176             for (var i = 0; i < elementCount; i++) {
71177                 var e = elements[i];
71178                 if (e.kind === 224 /* SpreadElement */) {
71179                     if (languageVersion < 2 /* ES2015 */) {
71180                         checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
71181                     }
71182                     var spreadType = checkExpression(e.expression, checkMode, forceTuple);
71183                     if (isArrayLikeType(spreadType)) {
71184                         elementTypes.push(spreadType);
71185                         elementFlags.push(8 /* Variadic */);
71186                     }
71187                     else if (inDestructuringPattern) {
71188                         // Given the following situation:
71189                         //    var c: {};
71190                         //    [...c] = ["", 0];
71191                         //
71192                         // c is represented in the tree as a spread element in an array literal.
71193                         // But c really functions as a rest element, and its purpose is to provide
71194                         // a contextual type for the right hand side of the assignment. Therefore,
71195                         // instead of calling checkExpression on "...c", which will give an error
71196                         // if c is not iterable/array-like, we need to act as if we are trying to
71197                         // get the contextual element type from it. So we do something similar to
71198                         // getContextualTypeForElementExpression, which will crucially not error
71199                         // if there is no index type / iterated type.
71200                         var restElementType = getIndexTypeOfType(spreadType, numberType) ||
71201                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false) ||
71202                             unknownType;
71203                         elementTypes.push(restElementType);
71204                         elementFlags.push(4 /* Rest */);
71205                     }
71206                     else {
71207                         elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
71208                         elementFlags.push(4 /* Rest */);
71209                     }
71210                 }
71211                 else if (exactOptionalPropertyTypes && e.kind === 226 /* OmittedExpression */) {
71212                     hasOmittedExpression = true;
71213                     elementTypes.push(missingType);
71214                     elementFlags.push(2 /* Optional */);
71215                 }
71216                 else {
71217                     var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
71218                     var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
71219                     elementTypes.push(addOptionality(type, /*isProperty*/ true, hasOmittedExpression));
71220                     elementFlags.push(hasOmittedExpression ? 2 /* Optional */ : 1 /* Required */);
71221                 }
71222             }
71223             if (inDestructuringPattern) {
71224                 return createTupleType(elementTypes, elementFlags);
71225             }
71226             if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) {
71227                 return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext));
71228             }
71229             return createArrayLiteralType(createArrayType(elementTypes.length ?
71230                 getUnionType(ts.sameMap(elementTypes, function (t, i) { return elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t; }), 2 /* Subtype */) :
71231                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
71232         }
71233         function createArrayLiteralType(type) {
71234             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
71235                 return type;
71236             }
71237             var literalType = type.literalType;
71238             if (!literalType) {
71239                 literalType = type.literalType = cloneTypeReference(type);
71240                 literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */;
71241             }
71242             return literalType;
71243         }
71244         function isNumericName(name) {
71245             switch (name.kind) {
71246                 case 161 /* ComputedPropertyName */:
71247                     return isNumericComputedName(name);
71248                 case 79 /* Identifier */:
71249                     return isNumericLiteralName(name.escapedText);
71250                 case 8 /* NumericLiteral */:
71251                 case 10 /* StringLiteral */:
71252                     return isNumericLiteralName(name.text);
71253                 default:
71254                     return false;
71255             }
71256         }
71257         function isNumericComputedName(name) {
71258             // It seems odd to consider an expression of type Any to result in a numeric name,
71259             // but this behavior is consistent with checkIndexedAccess
71260             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
71261         }
71262         function isNumericLiteralName(name) {
71263             // The intent of numeric names is that
71264             //     - they are names with text in a numeric form, and that
71265             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
71266             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
71267             //
71268             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
71269             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
71270             //
71271             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
71272             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
71273             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
71274             // because their 'ToString' representation is not equal to their original text.
71275             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
71276             //
71277             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
71278             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
71279             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
71280             //
71281             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
71282             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
71283             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
71284             return (+name).toString() === name;
71285         }
71286         function checkComputedPropertyName(node) {
71287             var links = getNodeLinks(node.expression);
71288             if (!links.resolvedType) {
71289                 if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent))
71290                     && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) {
71291                     return links.resolvedType = errorType;
71292                 }
71293                 links.resolvedType = checkExpression(node.expression);
71294                 // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding.
71295                 // (It needs to be bound at class evaluation time.)
71296                 if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) {
71297                     var container = ts.getEnclosingBlockScopeContainer(node.parent.parent);
71298                     var enclosingIterationStatement = getEnclosingIterationStatement(container);
71299                     if (enclosingIterationStatement) {
71300                         // The computed field name will use a block scoped binding which can be unique for each iteration of the loop.
71301                         getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
71302                         // The generated variable which stores the computed field name must be block-scoped.
71303                         getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */;
71304                         // The generated variable which stores the class must be block-scoped.
71305                         getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */;
71306                     }
71307                 }
71308                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
71309                 // type, and any union of these types (like string | number).
71310                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
71311                     !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
71312                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
71313                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
71314                 }
71315             }
71316             return links.resolvedType;
71317         }
71318         function isSymbolWithNumericName(symbol) {
71319             var _a;
71320             var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
71321             return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name));
71322         }
71323         function isSymbolWithSymbolName(symbol) {
71324             var _a;
71325             var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
71326             return ts.isKnownSymbol(symbol) || (firstDecl && ts.isNamedDeclaration(firstDecl) && ts.isComputedPropertyName(firstDecl.name) &&
71327                 isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */));
71328         }
71329         function getObjectLiteralIndexInfo(node, offset, properties, keyType) {
71330             var propTypes = [];
71331             for (var i = offset; i < properties.length; i++) {
71332                 var prop = properties[i];
71333                 if (keyType === stringType && !isSymbolWithSymbolName(prop) ||
71334                     keyType === numberType && isSymbolWithNumericName(prop) ||
71335                     keyType === esSymbolType && isSymbolWithSymbolName(prop)) {
71336                     propTypes.push(getTypeOfSymbol(properties[i]));
71337                 }
71338             }
71339             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
71340             return createIndexInfo(keyType, unionType, isConstContext(node));
71341         }
71342         function getImmediateAliasedSymbol(symbol) {
71343             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
71344             var links = getSymbolLinks(symbol);
71345             if (!links.immediateTarget) {
71346                 var node = getDeclarationOfAliasSymbol(symbol);
71347                 if (!node)
71348                     return ts.Debug.fail();
71349                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
71350             }
71351             return links.immediateTarget;
71352         }
71353         function checkObjectLiteral(node, checkMode) {
71354             var inDestructuringPattern = ts.isAssignmentTarget(node);
71355             // Grammar checking
71356             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
71357             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
71358             var propertiesTable = ts.createSymbolTable();
71359             var propertiesArray = [];
71360             var spread = emptyObjectType;
71361             var contextualType = getApparentTypeOfContextualType(node);
71362             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
71363                 (contextualType.pattern.kind === 200 /* ObjectBindingPattern */ || contextualType.pattern.kind === 204 /* ObjectLiteralExpression */);
71364             var inConstContext = isConstContext(node);
71365             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
71366             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
71367             var enumTag = ts.getJSDocEnumTag(node);
71368             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
71369             var objectFlags = freshObjectLiteralFlag;
71370             var patternWithComputedProperties = false;
71371             var hasComputedStringProperty = false;
71372             var hasComputedNumberProperty = false;
71373             var hasComputedSymbolProperty = false;
71374             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
71375             // As otherwise they may not be checked until exports for the type at this position are retrieved,
71376             // which may never occur.
71377             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
71378                 var elem = _a[_i];
71379                 if (elem.name && ts.isComputedPropertyName(elem.name)) {
71380                     checkComputedPropertyName(elem.name);
71381                 }
71382             }
71383             var offset = 0;
71384             for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
71385                 var memberDecl = _c[_b];
71386                 var member = getSymbolOfNode(memberDecl);
71387                 var computedNameType = memberDecl.name && memberDecl.name.kind === 161 /* ComputedPropertyName */ ?
71388                     checkComputedPropertyName(memberDecl.name) : undefined;
71389                 if (memberDecl.kind === 294 /* PropertyAssignment */ ||
71390                     memberDecl.kind === 295 /* ShorthandPropertyAssignment */ ||
71391                     ts.isObjectLiteralMethod(memberDecl)) {
71392                     var type = memberDecl.kind === 294 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
71393                         // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
71394                         // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
71395                         // we don't want to say "could not find 'a'".
71396                         memberDecl.kind === 295 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) :
71397                             checkObjectLiteralMethod(memberDecl, checkMode);
71398                     if (isInJavascript) {
71399                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
71400                         if (jsDocType) {
71401                             checkTypeAssignableTo(type, jsDocType, memberDecl);
71402                             type = jsDocType;
71403                         }
71404                         else if (enumTag && enumTag.typeExpression) {
71405                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
71406                         }
71407                     }
71408                     objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
71409                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
71410                     var prop = nameType ?
71411                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
71412                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
71413                     if (nameType) {
71414                         prop.nameType = nameType;
71415                     }
71416                     if (inDestructuringPattern) {
71417                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
71418                         // for the property, make the property optional.
71419                         var isOptional = (memberDecl.kind === 294 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
71420                             (memberDecl.kind === 295 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
71421                         if (isOptional) {
71422                             prop.flags |= 16777216 /* Optional */;
71423                         }
71424                     }
71425                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
71426                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
71427                         // binding pattern specifies a default value for the property, make the property optional.
71428                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
71429                         if (impliedProp) {
71430                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
71431                         }
71432                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, stringType)) {
71433                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
71434                         }
71435                     }
71436                     prop.declarations = member.declarations;
71437                     prop.parent = member.parent;
71438                     if (member.valueDeclaration) {
71439                         prop.valueDeclaration = member.valueDeclaration;
71440                     }
71441                     prop.type = type;
71442                     prop.target = member;
71443                     member = prop;
71444                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
71445                 }
71446                 else if (memberDecl.kind === 296 /* SpreadAssignment */) {
71447                     if (languageVersion < 2 /* ES2015 */) {
71448                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
71449                     }
71450                     if (propertiesArray.length > 0) {
71451                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
71452                         propertiesArray = [];
71453                         propertiesTable = ts.createSymbolTable();
71454                         hasComputedStringProperty = false;
71455                         hasComputedNumberProperty = false;
71456                         hasComputedSymbolProperty = false;
71457                     }
71458                     var type = getReducedType(checkExpression(memberDecl.expression));
71459                     if (isValidSpreadType(type)) {
71460                         var mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext);
71461                         if (allPropertiesTable) {
71462                             checkSpreadPropOverrides(mergedType, allPropertiesTable, memberDecl);
71463                         }
71464                         offset = propertiesArray.length;
71465                         if (isErrorType(spread)) {
71466                             continue;
71467                         }
71468                         spread = getSpreadType(spread, mergedType, node.symbol, objectFlags, inConstContext);
71469                     }
71470                     else {
71471                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
71472                         spread = errorType;
71473                     }
71474                     continue;
71475                 }
71476                 else {
71477                     // TypeScript 1.0 spec (April 2014)
71478                     // A get accessor declaration is processed in the same manner as
71479                     // an ordinary function declaration(section 6.1) with no parameters.
71480                     // A set accessor declaration is processed in the same manner
71481                     // as an ordinary function declaration with a single parameter and a Void return type.
71482                     ts.Debug.assert(memberDecl.kind === 171 /* GetAccessor */ || memberDecl.kind === 172 /* SetAccessor */);
71483                     checkNodeDeferred(memberDecl);
71484                 }
71485                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
71486                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
71487                         if (isTypeAssignableTo(computedNameType, numberType)) {
71488                             hasComputedNumberProperty = true;
71489                         }
71490                         else if (isTypeAssignableTo(computedNameType, esSymbolType)) {
71491                             hasComputedSymbolProperty = true;
71492                         }
71493                         else {
71494                             hasComputedStringProperty = true;
71495                         }
71496                         if (inDestructuringPattern) {
71497                             patternWithComputedProperties = true;
71498                         }
71499                     }
71500                 }
71501                 else {
71502                     propertiesTable.set(member.escapedName, member);
71503                 }
71504                 propertiesArray.push(member);
71505             }
71506             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
71507             // type with those properties for which the binding pattern specifies a default value.
71508             // If the object literal is spread into another object literal, skip this step and let the top-level object
71509             // literal handle it instead.
71510             if (contextualTypeHasPattern && node.parent.kind !== 296 /* SpreadAssignment */) {
71511                 for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) {
71512                     var prop = _e[_d];
71513                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
71514                         if (!(prop.flags & 16777216 /* Optional */)) {
71515                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
71516                         }
71517                         propertiesTable.set(prop.escapedName, prop);
71518                         propertiesArray.push(prop);
71519                     }
71520                 }
71521             }
71522             if (isErrorType(spread)) {
71523                 return errorType;
71524             }
71525             if (spread !== emptyObjectType) {
71526                 if (propertiesArray.length > 0) {
71527                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
71528                     propertiesArray = [];
71529                     propertiesTable = ts.createSymbolTable();
71530                     hasComputedStringProperty = false;
71531                     hasComputedNumberProperty = false;
71532                 }
71533                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
71534                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
71535             }
71536             return createObjectLiteralType();
71537             function createObjectLiteralType() {
71538                 var indexInfos = [];
71539                 if (hasComputedStringProperty)
71540                     indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType));
71541                 if (hasComputedNumberProperty)
71542                     indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType));
71543                 if (hasComputedSymbolProperty)
71544                     indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType));
71545                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, indexInfos);
71546                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */;
71547                 if (isJSObjectLiteral) {
71548                     result.objectFlags |= 8192 /* JSLiteral */;
71549                 }
71550                 if (patternWithComputedProperties) {
71551                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
71552                 }
71553                 if (inDestructuringPattern) {
71554                     result.pattern = node;
71555                 }
71556                 return result;
71557             }
71558         }
71559         function isValidSpreadType(type) {
71560             if (type.flags & 465829888 /* Instantiable */) {
71561                 var constraint = getBaseConstraintOfType(type);
71562                 if (constraint !== undefined) {
71563                     return isValidSpreadType(constraint);
71564                 }
71565             }
71566             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
71567                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
71568                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
71569         }
71570         function checkJsxSelfClosingElementDeferred(node) {
71571             checkJsxOpeningLikeElementOrOpeningFragment(node);
71572         }
71573         function checkJsxSelfClosingElement(node, _checkMode) {
71574             checkNodeDeferred(node);
71575             return getJsxElementTypeAt(node) || anyType;
71576         }
71577         function checkJsxElementDeferred(node) {
71578             // Check attributes
71579             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
71580             // Perform resolution on the closing tag so that rename/go to definition/etc work
71581             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
71582                 getIntrinsicTagSymbol(node.closingElement);
71583             }
71584             else {
71585                 checkExpression(node.closingElement.tagName);
71586             }
71587             checkJsxChildren(node);
71588         }
71589         function checkJsxElement(node, _checkMode) {
71590             checkNodeDeferred(node);
71591             return getJsxElementTypeAt(node) || anyType;
71592         }
71593         function checkJsxFragment(node) {
71594             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
71595             // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment
71596             // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too
71597             var nodeSourceFile = ts.getSourceFileOfNode(node);
71598             if (ts.getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx"))
71599                 && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
71600                 error(node, compilerOptions.jsxFactory
71601                     ? ts.Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option
71602                     : ts.Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments);
71603             }
71604             checkJsxChildren(node);
71605             return getJsxElementTypeAt(node) || anyType;
71606         }
71607         function isHyphenatedJsxName(name) {
71608             return ts.stringContains(name, "-");
71609         }
71610         /**
71611          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
71612          */
71613         function isJsxIntrinsicIdentifier(tagName) {
71614             return tagName.kind === 79 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
71615         }
71616         function checkJsxAttribute(node, checkMode) {
71617             return node.initializer
71618                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
71619                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
71620         }
71621         /**
71622          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
71623          *
71624          * @param openingLikeElement a JSX opening-like element
71625          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
71626          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
71627          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
71628          * which also calls getSpreadType.
71629          */
71630         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
71631             var attributes = openingLikeElement.attributes;
71632             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
71633             var attributesTable = ts.createSymbolTable();
71634             var spread = emptyJsxObjectType;
71635             var hasSpreadAnyType = false;
71636             var typeToIntersect;
71637             var explicitlySpecifyChildrenAttribute = false;
71638             var objectFlags = 2048 /* JsxAttributes */;
71639             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
71640             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
71641                 var attributeDecl = _a[_i];
71642                 var member = attributeDecl.symbol;
71643                 if (ts.isJsxAttribute(attributeDecl)) {
71644                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
71645                     objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
71646                     var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName);
71647                     attributeSymbol.declarations = member.declarations;
71648                     attributeSymbol.parent = member.parent;
71649                     if (member.valueDeclaration) {
71650                         attributeSymbol.valueDeclaration = member.valueDeclaration;
71651                     }
71652                     attributeSymbol.type = exprType;
71653                     attributeSymbol.target = member;
71654                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
71655                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
71656                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
71657                         explicitlySpecifyChildrenAttribute = true;
71658                     }
71659                 }
71660                 else {
71661                     ts.Debug.assert(attributeDecl.kind === 286 /* JsxSpreadAttribute */);
71662                     if (attributesTable.size > 0) {
71663                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
71664                         attributesTable = ts.createSymbolTable();
71665                     }
71666                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
71667                     if (isTypeAny(exprType)) {
71668                         hasSpreadAnyType = true;
71669                     }
71670                     if (isValidSpreadType(exprType)) {
71671                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
71672                         if (allAttributesTable) {
71673                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
71674                         }
71675                     }
71676                     else {
71677                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
71678                     }
71679                 }
71680             }
71681             if (!hasSpreadAnyType) {
71682                 if (attributesTable.size > 0) {
71683                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
71684                 }
71685             }
71686             // Handle children attribute
71687             var parent = openingLikeElement.parent.kind === 277 /* JsxElement */ ? openingLikeElement.parent : undefined;
71688             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
71689             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
71690                 var childrenTypes = checkJsxChildren(parent, checkMode);
71691                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
71692                     // Error if there is a attribute named "children" explicitly specified and children element.
71693                     // This is because children element will overwrite the value from attributes.
71694                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
71695                     if (explicitlySpecifyChildrenAttribute) {
71696                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
71697                     }
71698                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
71699                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
71700                     // 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
71701                     var childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName);
71702                     childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] :
71703                         childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
71704                             createArrayType(getUnionType(childrenTypes));
71705                     // Fake up a property declaration for the children
71706                     childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
71707                     ts.setParent(childrenPropSymbol.valueDeclaration, attributes);
71708                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
71709                     var childPropMap = ts.createSymbolTable();
71710                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
71711                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, ts.emptyArray), attributes.symbol, objectFlags, /*readonly*/ false);
71712                 }
71713             }
71714             if (hasSpreadAnyType) {
71715                 return anyType;
71716             }
71717             if (typeToIntersect && spread !== emptyJsxObjectType) {
71718                 return getIntersectionType([typeToIntersect, spread]);
71719             }
71720             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
71721             /**
71722              * Create anonymous type from given attributes symbol table.
71723              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
71724              * @param attributesTable a symbol table of attributes property
71725              */
71726             function createJsxAttributesType() {
71727                 objectFlags |= freshObjectLiteralFlag;
71728                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, ts.emptyArray);
71729                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */;
71730                 return result;
71731             }
71732         }
71733         function checkJsxChildren(node, checkMode) {
71734             var childrenTypes = [];
71735             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
71736                 var child = _a[_i];
71737                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
71738                 // because then type of children property will have constituent of string type.
71739                 if (child.kind === 11 /* JsxText */) {
71740                     if (!child.containsOnlyTriviaWhiteSpaces) {
71741                         childrenTypes.push(stringType);
71742                     }
71743                 }
71744                 else if (child.kind === 287 /* JsxExpression */ && !child.expression) {
71745                     continue; // empty jsx expressions don't *really* count as present children
71746                 }
71747                 else {
71748                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
71749                 }
71750             }
71751             return childrenTypes;
71752         }
71753         function checkSpreadPropOverrides(type, props, spread) {
71754             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
71755                 var right = _a[_i];
71756                 if (!(right.flags & 16777216 /* Optional */)) {
71757                     var left = props.get(right.escapedName);
71758                     if (left) {
71759                         var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
71760                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
71761                     }
71762                 }
71763             }
71764         }
71765         /**
71766          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
71767          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
71768          * @param node a JSXAttributes to be resolved of its type
71769          */
71770         function checkJsxAttributes(node, checkMode) {
71771             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
71772         }
71773         function getJsxType(name, location) {
71774             var namespace = getJsxNamespaceAt(location);
71775             var exports = namespace && getExportsOfSymbol(namespace);
71776             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
71777             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
71778         }
71779         /**
71780          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
71781          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
71782          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
71783          * May also return unknownSymbol if both of these lookups fail.
71784          */
71785         function getIntrinsicTagSymbol(node) {
71786             var links = getNodeLinks(node);
71787             if (!links.resolvedSymbol) {
71788                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
71789                 if (!isErrorType(intrinsicElementsType)) {
71790                     // Property case
71791                     if (!ts.isIdentifier(node.tagName))
71792                         return ts.Debug.fail();
71793                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
71794                     if (intrinsicProp) {
71795                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
71796                         return links.resolvedSymbol = intrinsicProp;
71797                     }
71798                     // Intrinsic string indexer case
71799                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType);
71800                     if (indexSignatureType) {
71801                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
71802                         return links.resolvedSymbol = intrinsicElementsType.symbol;
71803                     }
71804                     // Wasn't found
71805                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
71806                     return links.resolvedSymbol = unknownSymbol;
71807                 }
71808                 else {
71809                     if (noImplicitAny) {
71810                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
71811                     }
71812                     return links.resolvedSymbol = unknownSymbol;
71813                 }
71814             }
71815             return links.resolvedSymbol;
71816         }
71817         function getJsxNamespaceContainerForImplicitImport(location) {
71818             var file = location && ts.getSourceFileOfNode(location);
71819             var links = file && getNodeLinks(file);
71820             if (links && links.jsxImplicitImportContainer === false) {
71821                 return undefined;
71822             }
71823             if (links && links.jsxImplicitImportContainer) {
71824                 return links.jsxImplicitImportContainer;
71825             }
71826             var runtimeImportSpecifier = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
71827             if (!runtimeImportSpecifier) {
71828                 return undefined;
71829             }
71830             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
71831             var errorMessage = isClassic
71832                 ? ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
71833                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
71834             var mod = resolveExternalModule(location, runtimeImportSpecifier, errorMessage, location);
71835             var result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined;
71836             if (links) {
71837                 links.jsxImplicitImportContainer = result || false;
71838             }
71839             return result;
71840         }
71841         function getJsxNamespaceAt(location) {
71842             var links = location && getNodeLinks(location);
71843             if (links && links.jsxNamespace) {
71844                 return links.jsxNamespace;
71845             }
71846             if (!links || links.jsxNamespace !== false) {
71847                 var resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
71848                 if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
71849                     var namespaceName = getJsxNamespace(location);
71850                     resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
71851                 }
71852                 if (resolvedNamespace) {
71853                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
71854                     if (candidate && candidate !== unknownSymbol) {
71855                         if (links) {
71856                             links.jsxNamespace = candidate;
71857                         }
71858                         return candidate;
71859                     }
71860                 }
71861                 if (links) {
71862                     links.jsxNamespace = false;
71863                 }
71864             }
71865             // JSX global fallback
71866             var s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined));
71867             if (s === unknownSymbol) {
71868                 return undefined; // TODO: GH#18217
71869             }
71870             return s; // TODO: GH#18217
71871         }
71872         /**
71873          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
71874          * Get a single property from that container if existed. Report an error if there are more than one property.
71875          *
71876          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
71877          *          if other string is given or the container doesn't exist, return undefined.
71878          */
71879         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
71880             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
71881             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
71882             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
71883             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
71884             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
71885             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
71886             if (propertiesOfJsxElementAttribPropInterface) {
71887                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
71888                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
71889                     return "";
71890                 }
71891                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
71892                 // property of the class instance type
71893                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
71894                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
71895                 }
71896                 else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) {
71897                     // More than one property on ElementAttributesProperty is an error
71898                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
71899                 }
71900             }
71901             return undefined;
71902         }
71903         function getJsxLibraryManagedAttributes(jsxNamespace) {
71904             // JSX.LibraryManagedAttributes [symbol]
71905             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
71906         }
71907         /// e.g. "props" for React.d.ts,
71908         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
71909         ///     non-intrinsic elements' attributes type is 'any'),
71910         /// or '' if it has 0 properties (which means every
71911         ///     non-intrinsic elements' attributes type is the element instance type)
71912         function getJsxElementPropertiesName(jsxNamespace) {
71913             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
71914         }
71915         function getJsxElementChildrenPropertyName(jsxNamespace) {
71916             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
71917         }
71918         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
71919             if (elementType.flags & 4 /* String */) {
71920                 return [anySignature];
71921             }
71922             else if (elementType.flags & 128 /* StringLiteral */) {
71923                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
71924                 if (!intrinsicType) {
71925                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
71926                     return ts.emptyArray;
71927                 }
71928                 else {
71929                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
71930                     return [fakeSignature];
71931                 }
71932             }
71933             var apparentElemType = getApparentType(elementType);
71934             // Resolve the signatures, preferring constructor
71935             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
71936             if (signatures.length === 0) {
71937                 // No construct signatures, try call signatures
71938                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
71939             }
71940             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
71941                 // If each member has some combination of new/call signatures; make a union signature list for those
71942                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
71943             }
71944             return signatures;
71945         }
71946         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
71947             // 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
71948             // For example:
71949             //      var CustomTag: "h1" = "h1";
71950             //      <CustomTag> Hello World </CustomTag>
71951             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
71952             if (!isErrorType(intrinsicElementsType)) {
71953                 var stringLiteralTypeName = type.value;
71954                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
71955                 if (intrinsicProp) {
71956                     return getTypeOfSymbol(intrinsicProp);
71957                 }
71958                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType);
71959                 if (indexSignatureType) {
71960                     return indexSignatureType;
71961                 }
71962                 return undefined;
71963             }
71964             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
71965             return anyType;
71966         }
71967         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
71968             if (refKind === 1 /* Function */) {
71969                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
71970                 if (sfcReturnConstraint) {
71971                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
71972                 }
71973             }
71974             else if (refKind === 0 /* Component */) {
71975                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
71976                 if (classConstraint) {
71977                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
71978                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
71979                 }
71980             }
71981             else { // Mixed
71982                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
71983                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
71984                 if (!sfcReturnConstraint || !classConstraint) {
71985                     return;
71986                 }
71987                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
71988                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
71989             }
71990             function generateInitialErrorChain() {
71991                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
71992                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
71993             }
71994         }
71995         /**
71996          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
71997          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
71998          * @param node an intrinsic JSX opening-like element
71999          */
72000         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
72001             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
72002             var links = getNodeLinks(node);
72003             if (!links.resolvedJsxElementAttributesType) {
72004                 var symbol = getIntrinsicTagSymbol(node);
72005                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
72006                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType;
72007                 }
72008                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
72009                     return links.resolvedJsxElementAttributesType =
72010                         getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), stringType) || errorType;
72011                 }
72012                 else {
72013                     return links.resolvedJsxElementAttributesType = errorType;
72014                 }
72015             }
72016             return links.resolvedJsxElementAttributesType;
72017         }
72018         function getJsxElementClassTypeAt(location) {
72019             var type = getJsxType(JsxNames.ElementClass, location);
72020             if (isErrorType(type))
72021                 return undefined;
72022             return type;
72023         }
72024         function getJsxElementTypeAt(location) {
72025             return getJsxType(JsxNames.Element, location);
72026         }
72027         function getJsxStatelessElementTypeAt(location) {
72028             var jsxElementType = getJsxElementTypeAt(location);
72029             if (jsxElementType) {
72030                 return getUnionType([jsxElementType, nullType]);
72031             }
72032         }
72033         /**
72034          * Returns all the properties of the Jsx.IntrinsicElements interface
72035          */
72036         function getJsxIntrinsicTagNamesAt(location) {
72037             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
72038             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
72039         }
72040         function checkJsxPreconditions(errorNode) {
72041             // Preconditions for using JSX
72042             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
72043                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
72044             }
72045             if (getJsxElementTypeAt(errorNode) === undefined) {
72046                 if (noImplicitAny) {
72047                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
72048                 }
72049             }
72050         }
72051         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
72052             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
72053             if (isNodeOpeningLikeElement) {
72054                 checkGrammarJsxElement(node);
72055             }
72056             checkJsxPreconditions(node);
72057             if (!getJsxNamespaceContainerForImplicitImport(node)) {
72058                 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
72059                 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
72060                 var jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
72061                 var jsxFactoryNamespace = getJsxNamespace(node);
72062                 var jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node;
72063                 // allow null as jsxFragmentFactory
72064                 var jsxFactorySym = void 0;
72065                 if (!(ts.isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
72066                     jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true);
72067                 }
72068                 if (jsxFactorySym) {
72069                     // Mark local symbol as referenced here because it might not have been marked
72070                     // if jsx emit was not jsxFactory as there wont be error being emitted
72071                     jsxFactorySym.isReferenced = 67108863 /* All */;
72072                     // If react/jsxFactory symbol is alias, mark it as refereced
72073                     if (jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
72074                         markAliasSymbolAsReferenced(jsxFactorySym);
72075                     }
72076                 }
72077                 // For JsxFragment, mark jsx pragma as referenced via resolveName
72078                 if (ts.isJsxOpeningFragment(node)) {
72079                     var file = ts.getSourceFileOfNode(node);
72080                     var localJsxNamespace = getLocalJsxNamespace(file);
72081                     if (localJsxNamespace) {
72082                         resolveName(jsxFactoryLocation, localJsxNamespace, 111551 /* Value */, jsxFactoryRefErr, localJsxNamespace, /*isUse*/ true);
72083                     }
72084                 }
72085             }
72086             if (isNodeOpeningLikeElement) {
72087                 var jsxOpeningLikeNode = node;
72088                 var sig = getResolvedSignature(jsxOpeningLikeNode);
72089                 checkDeprecatedSignature(sig, node);
72090                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
72091             }
72092         }
72093         /**
72094          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
72095          * is considered known if
72096          * 1. the object type is empty and the check is for assignability, or
72097          * 2. if the object type has index signatures, or
72098          * 3. if the property is actually declared in the object type
72099          *    (this means that 'toString', for example, is not usually a known property).
72100          * 4. In a union or intersection type,
72101          *    a property is considered known if it is known in any constituent type.
72102          * @param targetType a type to search a given name in
72103          * @param name a property name to search
72104          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
72105          */
72106         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
72107             if (targetType.flags & 524288 /* Object */) {
72108                 // For backwards compatibility a symbol-named property is satisfied by a string index signature. This
72109                 // is incorrect and inconsistent with element access expressions, where it is an error, so eventually
72110                 // we should remove this exception.
72111                 if (getPropertyOfObjectType(targetType, name) ||
72112                     getApplicableIndexInfoForName(targetType, name) ||
72113                     isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) ||
72114                     isComparingJsxAttributes && isHyphenatedJsxName(name)) {
72115                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
72116                     return true;
72117                 }
72118             }
72119             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
72120                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
72121                     var t = _a[_i];
72122                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
72123                         return true;
72124                     }
72125                 }
72126             }
72127             return false;
72128         }
72129         function isExcessPropertyCheckTarget(type) {
72130             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
72131                 type.flags & 67108864 /* NonPrimitive */ ||
72132                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
72133                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
72134         }
72135         function checkJsxExpression(node, checkMode) {
72136             checkGrammarJsxExpression(node);
72137             if (node.expression) {
72138                 var type = checkExpression(node.expression, checkMode);
72139                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
72140                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
72141                 }
72142                 return type;
72143             }
72144             else {
72145                 return errorType;
72146             }
72147         }
72148         function getDeclarationNodeFlagsFromSymbol(s) {
72149             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
72150         }
72151         /**
72152          * Return whether this symbol is a member of a prototype somewhere
72153          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
72154          */
72155         function isPrototypeProperty(symbol) {
72156             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
72157                 return true;
72158             }
72159             if (ts.isInJSFile(symbol.valueDeclaration)) {
72160                 var parent = symbol.valueDeclaration.parent;
72161                 return parent && ts.isBinaryExpression(parent) &&
72162                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
72163             }
72164         }
72165         /**
72166          * Check whether the requested property access is valid.
72167          * Returns true if node is a valid property access, and false otherwise.
72168          * @param node The node to be checked.
72169          * @param isSuper True if the access is from `super.`.
72170          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
72171          * @param prop The symbol for the property being accessed.
72172          */
72173         function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) {
72174             if (reportError === void 0) { reportError = true; }
72175             var errorNode = !reportError ? undefined :
72176                 node.kind === 160 /* QualifiedName */ ? node.right :
72177                     node.kind === 199 /* ImportType */ ? node :
72178                         node.kind === 202 /* BindingElement */ && node.propertyName ? node.propertyName : node.name;
72179             return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode);
72180         }
72181         /**
72182          * Check whether the requested property can be accessed at the requested location.
72183          * Returns true if node is a valid property access, and false otherwise.
72184          * @param location The location node where we want to check if the property is accessible.
72185          * @param isSuper True if the access is from `super.`.
72186          * @param writing True if this is a write property access, false if it is a read property access.
72187          * @param containingType The type of the object whose property is being accessed. (Not the type of the property.)
72188          * @param prop The symbol for the property being accessed.
72189          * @param errorNode The node where we should report an invalid property access error, or undefined if we should not report errors.
72190          */
72191         function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) {
72192             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing);
72193             if (isSuper) {
72194                 // TS 1.0 spec (April 2014): 4.8.2
72195                 // - In a constructor, instance member function, instance member accessor, or
72196                 //   instance member variable initializer where this references a derived class instance,
72197                 //   a super property access is permitted and must specify a public instance member function of the base class.
72198                 // - In a static member function or static member accessor
72199                 //   where this references the constructor function object of a derived class,
72200                 //   a super property access is permitted and must specify a public static member function of the base class.
72201                 if (languageVersion < 2 /* ES2015 */) {
72202                     if (symbolHasNonMethodDeclaration(prop)) {
72203                         if (errorNode) {
72204                             error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
72205                         }
72206                         return false;
72207                     }
72208                 }
72209                 if (flags & 128 /* Abstract */) {
72210                     // A method cannot be accessed in a super property access if the method is abstract.
72211                     // This error could mask a private property access error. But, a member
72212                     // cannot simultaneously be private and abstract, so this will trigger an
72213                     // additional error elsewhere.
72214                     if (errorNode) {
72215                         error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
72216                     }
72217                     return false;
72218                 }
72219             }
72220             // Referencing abstract properties within their own constructors is not allowed
72221             if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) &&
72222                 (ts.isThisProperty(location) || ts.isThisInitializedObjectBindingExpression(location) || ts.isObjectBindingPattern(location.parent) && ts.isThisInitializedDeclaration(location.parent.parent))) {
72223                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
72224                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) {
72225                     if (errorNode) {
72226                         error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name));
72227                     }
72228                     return false;
72229                 }
72230             }
72231             // Public properties are otherwise accessible.
72232             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
72233                 return true;
72234             }
72235             // Property is known to be private or protected at this point
72236             // Private property is accessible if the property is within the declaring class
72237             if (flags & 8 /* Private */) {
72238                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
72239                 if (!isNodeWithinClass(location, declaringClassDeclaration)) {
72240                     if (errorNode) {
72241                         error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
72242                     }
72243                     return false;
72244                 }
72245                 return true;
72246             }
72247             // Property is known to be protected at this point
72248             // All protected properties of a supertype are accessible in a super access
72249             if (isSuper) {
72250                 return true;
72251             }
72252             // Find the first enclosing class that has the declaring classes of the protected constituents
72253             // of the property as base classes
72254             var enclosingClass = forEachEnclosingClass(location, function (enclosingDeclaration) {
72255                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
72256                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined;
72257             });
72258             // A protected property is accessible if the property is within the declaring class or classes derived from it
72259             if (!enclosingClass) {
72260                 // allow PropertyAccessibility if context is in function with this parameter
72261                 // static member access is disallow
72262                 var thisParameter = void 0;
72263                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(location)) || !thisParameter.type) {
72264                     if (errorNode) {
72265                         error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType));
72266                     }
72267                     return false;
72268                 }
72269                 var thisType = getTypeFromTypeNode(thisParameter.type);
72270                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
72271             }
72272             // No further restrictions for static properties
72273             if (flags & 32 /* Static */) {
72274                 return true;
72275             }
72276             if (containingType.flags & 262144 /* TypeParameter */) {
72277                 // get the original type -- represented as the type constraint of the 'this' type
72278                 containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType); // TODO: GH#18217 Use a different variable that's allowed to be undefined
72279             }
72280             if (!containingType || !hasBaseType(containingType, enclosingClass)) {
72281                 if (errorNode) {
72282                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType));
72283                 }
72284                 return false;
72285             }
72286             return true;
72287         }
72288         function getThisParameterFromNodeContext(node) {
72289             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
72290             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
72291         }
72292         function symbolHasNonMethodDeclaration(symbol) {
72293             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
72294         }
72295         function checkNonNullExpression(node) {
72296             return checkNonNullType(checkExpression(node), node);
72297         }
72298         function isNullableType(type) {
72299             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
72300         }
72301         function getNonNullableTypeIfNeeded(type) {
72302             return isNullableType(type) ? getNonNullableType(type) : type;
72303         }
72304         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
72305             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
72306                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
72307                 ts.Diagnostics.Object_is_possibly_undefined :
72308                 ts.Diagnostics.Object_is_possibly_null);
72309         }
72310         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
72311             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
72312                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
72313                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
72314                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
72315         }
72316         function checkNonNullTypeWithReporter(type, node, reportError) {
72317             if (strictNullChecks && type.flags & 2 /* Unknown */) {
72318                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
72319                 return errorType;
72320             }
72321             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
72322             if (kind) {
72323                 reportError(node, kind);
72324                 var t = getNonNullableType(type);
72325                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
72326             }
72327             return type;
72328         }
72329         function checkNonNullType(type, node) {
72330             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
72331         }
72332         function checkNonNullNonVoidType(type, node) {
72333             var nonNullType = checkNonNullType(type, node);
72334             if (nonNullType.flags & 16384 /* Void */) {
72335                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
72336             }
72337             return nonNullType;
72338         }
72339         function checkPropertyAccessExpression(node, checkMode) {
72340             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) :
72341                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode);
72342         }
72343         function checkPropertyAccessChain(node, checkMode) {
72344             var leftType = checkExpression(node.expression);
72345             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
72346             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType);
72347         }
72348         function checkQualifiedName(node, checkMode) {
72349             var leftType = ts.isPartOfTypeQuery(node) && ts.isThisIdentifier(node.left) ? checkNonNullType(checkThisExpression(node.left), node.left) : checkNonNullExpression(node.left);
72350             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode);
72351         }
72352         function isMethodAccessForCall(node) {
72353             while (node.parent.kind === 211 /* ParenthesizedExpression */) {
72354                 node = node.parent;
72355             }
72356             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
72357         }
72358         // Lookup the private identifier lexically.
72359         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
72360             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
72361                 var symbol = containingClass.symbol;
72362                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
72363                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
72364                 if (prop) {
72365                     return prop;
72366                 }
72367             }
72368         }
72369         function checkGrammarPrivateIdentifierExpression(privId) {
72370             if (!ts.getContainingClass(privId)) {
72371                 return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
72372             }
72373             if (!ts.isExpressionNode(privId)) {
72374                 return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression);
72375             }
72376             if (!getSymbolForPrivateIdentifierExpression(privId)) {
72377                 return grammarErrorOnNode(privId, ts.Diagnostics.Cannot_find_name_0, ts.idText(privId));
72378             }
72379             return false;
72380         }
72381         function checkPrivateIdentifierExpression(privId) {
72382             checkGrammarPrivateIdentifierExpression(privId);
72383             var symbol = getSymbolForPrivateIdentifierExpression(privId);
72384             if (symbol) {
72385                 markPropertyAsReferenced(symbol, /* nodeForCheckWriteOnly: */ undefined, /* isThisAccess: */ false);
72386             }
72387             return anyType;
72388         }
72389         function getSymbolForPrivateIdentifierExpression(privId) {
72390             if (!ts.isExpressionNode(privId)) {
72391                 return undefined;
72392             }
72393             var links = getNodeLinks(privId);
72394             if (links.resolvedSymbol === undefined) {
72395                 links.resolvedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId);
72396             }
72397             return links.resolvedSymbol;
72398         }
72399         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
72400             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
72401         }
72402         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
72403             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
72404             // Find a private identifier with the same description on the type.
72405             var propertyOnType;
72406             var properties = getPropertiesOfType(leftType);
72407             if (properties) {
72408                 ts.forEach(properties, function (symbol) {
72409                     var decl = symbol.valueDeclaration;
72410                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
72411                         propertyOnType = symbol;
72412                         return true;
72413                     }
72414                 });
72415             }
72416             var diagName = diagnosticName(right);
72417             if (propertyOnType) {
72418                 var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration);
72419                 var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl));
72420                 // We found a private identifier property with the same description.
72421                 // Either:
72422                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
72423                 // - It is an attempt to access the private identifier outside of the class.
72424                 if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) {
72425                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
72426                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
72427                     ts.Debug.assert(!!lexicalClass);
72428                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
72429                         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));
72430                         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));
72431                         return true;
72432                     }
72433                 }
72434                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
72435                 return true;
72436             }
72437             return false;
72438         }
72439         function isThisPropertyAccessInConstructor(node, prop) {
72440             return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop))
72441                 && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop);
72442         }
72443         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) {
72444             var parentSymbol = getNodeLinks(left).resolvedSymbol;
72445             var assignmentKind = ts.getAssignmentTargetKind(node);
72446             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
72447             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
72448             var prop;
72449             if (ts.isPrivateIdentifier(right)) {
72450                 if (languageVersion < 99 /* ESNext */) {
72451                     if (assignmentKind !== 0 /* None */) {
72452                         checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */);
72453                     }
72454                     if (assignmentKind !== 1 /* Definite */) {
72455                         checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */);
72456                     }
72457                 }
72458                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
72459                 if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) {
72460                     grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right));
72461                 }
72462                 if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && !useDefineForClassFields)) {
72463                     var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration);
72464                     var parentStaticFieldInitializer = ts.findAncestor(node, function (n) {
72465                         if (n === lexicalClass_1)
72466                             return "quit";
72467                         if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) {
72468                             return true;
72469                         }
72470                         return false;
72471                     });
72472                     if (parentStaticFieldInitializer) {
72473                         var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent);
72474                         ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol");
72475                         var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol));
72476                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol)));
72477                     }
72478                 }
72479                 if (isAnyLike) {
72480                     if (lexicallyScopedSymbol) {
72481                         return isErrorType(apparentType) ? errorType : apparentType;
72482                     }
72483                     if (!ts.getContainingClass(right)) {
72484                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
72485                         return anyType;
72486                     }
72487                 }
72488                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
72489                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
72490                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
72491                     return errorType;
72492                 }
72493                 else {
72494                     var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
72495                     if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) {
72496                         error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter);
72497                     }
72498                 }
72499             }
72500             else {
72501                 if (isAnyLike) {
72502                     if (ts.isIdentifier(left) && parentSymbol) {
72503                         markAliasReferenced(parentSymbol, node);
72504                     }
72505                     return isErrorType(apparentType) ? errorType : apparentType;
72506                     ;
72507                 }
72508                 prop = getPropertyOfType(apparentType, right.escapedText);
72509             }
72510             // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums.
72511             // The exceptions are:
72512             //   1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and
72513             //   2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`.
72514             if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) {
72515                 markAliasReferenced(parentSymbol, node);
72516             }
72517             var propType;
72518             if (!prop) {
72519                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ?
72520                     getApplicableIndexInfoForName(apparentType, right.escapedText) : undefined;
72521                 if (!(indexInfo && indexInfo.type)) {
72522                     var isUncheckedJS = isUncheckedJSSuggestion(node, leftType.symbol, /*excludeClasses*/ true);
72523                     if (!isUncheckedJS && isJSLiteralType(leftType)) {
72524                         return anyType;
72525                     }
72526                     if (leftType.symbol === globalThisSymbol) {
72527                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
72528                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
72529                         }
72530                         else if (noImplicitAny) {
72531                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
72532                         }
72533                         return anyType;
72534                     }
72535                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
72536                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS);
72537                     }
72538                     return errorType;
72539                 }
72540                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
72541                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
72542                 }
72543                 propType = (compilerOptions.noUncheckedIndexedAccess && !ts.isAssignmentTarget(node)) ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
72544                 if (compilerOptions.noPropertyAccessFromIndexSignature && ts.isPropertyAccessExpression(node)) {
72545                     error(right, ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, ts.unescapeLeadingUnderscores(right.escapedText));
72546                 }
72547             }
72548             else {
72549                 if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
72550                     addDeprecatedSuggestion(right, prop.declarations, right.escapedText);
72551                 }
72552                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
72553                 markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol));
72554                 getNodeLinks(node).resolvedSymbol = prop;
72555                 var writing = ts.isWriteAccess(node);
72556                 checkPropertyAccessibility(node, left.kind === 106 /* SuperKeyword */, writing, apparentType, prop);
72557                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
72558                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
72559                     return errorType;
72560                 }
72561                 propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop);
72562             }
72563             return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode);
72564         }
72565         /**
72566          * Determines whether a did-you-mean error should be a suggestion in an unchecked JS file.
72567          * Only applies to unchecked JS files without checkJS, // @ts-check or // @ts-nocheck
72568          * It does not suggest when the suggestion:
72569          * - Is from a global file that is different from the reference file, or
72570          * - (optionally) Is a class, or is a this.x property access expression
72571          */
72572         function isUncheckedJSSuggestion(node, suggestion, excludeClasses) {
72573             var file = ts.getSourceFileOfNode(node);
72574             if (file) {
72575                 if (compilerOptions.checkJs === undefined && file.checkJsDirective === undefined && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) {
72576                     var declarationFile = ts.forEach(suggestion === null || suggestion === void 0 ? void 0 : suggestion.declarations, ts.getSourceFileOfNode);
72577                     return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile))
72578                         && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */)
72579                         && !(!!node && excludeClasses && ts.isPropertyAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */);
72580                 }
72581             }
72582             return false;
72583         }
72584         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) {
72585             // Only compute control flow type if this is a property access expression that isn't an
72586             // assignment target, and the referenced property was declared as a variable, property,
72587             // accessor, or optional method.
72588             var assignmentKind = ts.getAssignmentTargetKind(node);
72589             if (assignmentKind === 1 /* Definite */) {
72590                 return removeMissingType(propType, !!(prop && prop.flags & 16777216 /* Optional */));
72591             }
72592             if (prop &&
72593                 !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */))
72594                 && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)
72595                 && !isDuplicatedCommonJSExport(prop.declarations)) {
72596                 return propType;
72597             }
72598             if (propType === autoType) {
72599                 return getFlowTypeOfProperty(node, prop);
72600             }
72601             propType = getNarrowableTypeForReference(propType, node, checkMode);
72602             // If strict null checks and strict property initialization checks are enabled, if we have
72603             // a this.xxx property access, if the property is an instance property without an initializer,
72604             // and if we are in a constructor of the same class as the property declaration, assume that
72605             // the property is uninitialized at the top of the control flow.
72606             var assumeUninitialized = false;
72607             if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 108 /* ThisKeyword */) {
72608                 var declaration = prop && prop.valueDeclaration;
72609                 if (declaration && isPropertyWithoutInitializer(declaration)) {
72610                     if (!ts.isStatic(declaration)) {
72611                         var flowContainer = getControlFlowContainer(node);
72612                         if (flowContainer.kind === 170 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
72613                             assumeUninitialized = true;
72614                         }
72615                     }
72616                 }
72617             }
72618             else if (strictNullChecks && prop && prop.valueDeclaration &&
72619                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
72620                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
72621                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
72622                 assumeUninitialized = true;
72623             }
72624             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
72625             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
72626                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
72627                 // Return the declared type to reduce follow-on errors
72628                 return propType;
72629             }
72630             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
72631         }
72632         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
72633             var valueDeclaration = prop.valueDeclaration;
72634             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
72635                 return;
72636             }
72637             var diagnosticMessage;
72638             var declarationName = ts.idText(right);
72639             if (isInPropertyInitializerOrClassStaticBlock(node)
72640                 && !isOptionalPropertyDeclaration(valueDeclaration)
72641                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
72642                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
72643                 && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) {
72644                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
72645             }
72646             else if (valueDeclaration.kind === 256 /* ClassDeclaration */ &&
72647                 node.parent.kind !== 177 /* TypeReference */ &&
72648                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
72649                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
72650                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
72651             }
72652             if (diagnosticMessage) {
72653                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
72654             }
72655         }
72656         function isInPropertyInitializerOrClassStaticBlock(node) {
72657             return !!ts.findAncestor(node, function (node) {
72658                 switch (node.kind) {
72659                     case 166 /* PropertyDeclaration */:
72660                         return true;
72661                     case 294 /* PropertyAssignment */:
72662                     case 168 /* MethodDeclaration */:
72663                     case 171 /* GetAccessor */:
72664                     case 172 /* SetAccessor */:
72665                     case 296 /* SpreadAssignment */:
72666                     case 161 /* ComputedPropertyName */:
72667                     case 232 /* TemplateSpan */:
72668                     case 287 /* JsxExpression */:
72669                     case 284 /* JsxAttribute */:
72670                     case 285 /* JsxAttributes */:
72671                     case 286 /* JsxSpreadAttribute */:
72672                     case 279 /* JsxOpeningElement */:
72673                     case 227 /* ExpressionWithTypeArguments */:
72674                     case 290 /* HeritageClause */:
72675                         return false;
72676                     case 213 /* ArrowFunction */:
72677                     case 237 /* ExpressionStatement */:
72678                         return ts.isBlock(node.parent) && ts.isClassStaticBlockDeclaration(node.parent.parent) ? true : "quit";
72679                     default:
72680                         return ts.isExpressionNode(node) ? false : "quit";
72681                 }
72682             });
72683         }
72684         /**
72685          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
72686          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
72687          */
72688         function isPropertyDeclaredInAncestorClass(prop) {
72689             if (!(prop.parent.flags & 32 /* Class */)) {
72690                 return false;
72691             }
72692             var classType = getTypeOfSymbol(prop.parent);
72693             while (true) {
72694                 classType = classType.symbol && getSuperClass(classType);
72695                 if (!classType) {
72696                     return false;
72697                 }
72698                 var superProperty = getPropertyOfType(classType, prop.escapedName);
72699                 if (superProperty && superProperty.valueDeclaration) {
72700                     return true;
72701                 }
72702             }
72703         }
72704         function getSuperClass(classType) {
72705             var x = getBaseTypes(classType);
72706             if (x.length === 0) {
72707                 return undefined;
72708             }
72709             return getIntersectionType(x);
72710         }
72711         function reportNonexistentProperty(propNode, containingType, isUncheckedJS) {
72712             var errorInfo;
72713             var relatedInfo;
72714             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
72715                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
72716                     var subtype = _a[_i];
72717                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getApplicableIndexInfoForName(subtype, propNode.escapedText)) {
72718                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
72719                         break;
72720                     }
72721                 }
72722             }
72723             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
72724                 var propName = ts.declarationNameToString(propNode);
72725                 var typeName = typeToString(containingType);
72726                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "." + propName);
72727             }
72728             else {
72729                 var promisedType = getPromisedTypeOfPromise(containingType);
72730                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
72731                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
72732                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
72733                 }
72734                 else {
72735                     var missingProperty = ts.declarationNameToString(propNode);
72736                     var container = typeToString(containingType);
72737                     var libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
72738                     if (libSuggestion !== undefined) {
72739                         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);
72740                     }
72741                     else {
72742                         var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
72743                         if (suggestion !== undefined) {
72744                             var suggestedName = ts.symbolName(suggestion);
72745                             var message = isUncheckedJS ? ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2 : ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2;
72746                             errorInfo = ts.chainDiagnosticMessages(errorInfo, message, missingProperty, container, suggestedName);
72747                             relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
72748                         }
72749                         else {
72750                             var diagnostic = containerSeemsToBeEmptyDomElement(containingType)
72751                                 ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom
72752                                 : ts.Diagnostics.Property_0_does_not_exist_on_type_1;
72753                             errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container);
72754                         }
72755                     }
72756                 }
72757             }
72758             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
72759             if (relatedInfo) {
72760                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
72761             }
72762             addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic);
72763         }
72764         function containerSeemsToBeEmptyDomElement(containingType) {
72765             return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) &&
72766                 everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) &&
72767                 isEmptyObjectType(containingType);
72768         }
72769         function typeHasStaticProperty(propName, containingType) {
72770             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
72771             return prop !== undefined && !!prop.valueDeclaration && ts.isStatic(prop.valueDeclaration);
72772         }
72773         function getSuggestedLibForNonExistentName(name) {
72774             var missingName = diagnosticName(name);
72775             var allFeatures = ts.getScriptTargetFeatures();
72776             var libTargets = ts.getOwnKeys(allFeatures);
72777             for (var _i = 0, libTargets_1 = libTargets; _i < libTargets_1.length; _i++) {
72778                 var libTarget = libTargets_1[_i];
72779                 var containingTypes = ts.getOwnKeys(allFeatures[libTarget]);
72780                 if (containingTypes !== undefined && ts.contains(containingTypes, missingName)) {
72781                     return libTarget;
72782                 }
72783             }
72784         }
72785         function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
72786             var container = getApparentType(containingType).symbol;
72787             if (!container) {
72788                 return undefined;
72789             }
72790             var allFeatures = ts.getScriptTargetFeatures();
72791             var libTargets = ts.getOwnKeys(allFeatures);
72792             for (var _i = 0, libTargets_2 = libTargets; _i < libTargets_2.length; _i++) {
72793                 var libTarget = libTargets_2[_i];
72794                 var featuresOfLib = allFeatures[libTarget];
72795                 var featuresOfContainingType = featuresOfLib[ts.symbolName(container)];
72796                 if (featuresOfContainingType !== undefined && ts.contains(featuresOfContainingType, missingProperty)) {
72797                     return libTarget;
72798                 }
72799             }
72800         }
72801         function getSuggestedSymbolForNonexistentClassMember(name, baseType) {
72802             return getSpellingSuggestionForName(name, getPropertiesOfType(baseType), 106500 /* ClassMember */);
72803         }
72804         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
72805             var props = getPropertiesOfType(containingType);
72806             if (typeof name !== "string") {
72807                 var parent_2 = name.parent;
72808                 if (ts.isPropertyAccessExpression(parent_2)) {
72809                     props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); });
72810                 }
72811                 name = ts.idText(name);
72812             }
72813             return getSpellingSuggestionForName(name, props, 111551 /* Value */);
72814         }
72815         function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
72816             var strName = ts.isString(name) ? name : ts.idText(name);
72817             var properties = getPropertiesOfType(containingType);
72818             var jsxSpecific = strName === "for" ? ts.find(properties, function (x) { return ts.symbolName(x) === "htmlFor"; })
72819                 : strName === "class" ? ts.find(properties, function (x) { return ts.symbolName(x) === "className"; })
72820                     : undefined;
72821             return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
72822         }
72823         function getSuggestionForNonexistentProperty(name, containingType) {
72824             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
72825             return suggestion && ts.symbolName(suggestion);
72826         }
72827         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
72828             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
72829             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
72830                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
72831                 var symbol = getSymbol(symbols, name, meaning);
72832                 // 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
72833                 // So the table *contains* `x` but `x` isn't actually in scope.
72834                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
72835                 if (symbol)
72836                     return symbol;
72837                 var candidates;
72838                 if (symbols === globals) {
72839                     var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1)))
72840                         ? createSymbol(524288 /* TypeAlias */, s)
72841                         : undefined; });
72842                     candidates = primitives.concat(ts.arrayFrom(symbols.values()));
72843                 }
72844                 else {
72845                     candidates = ts.arrayFrom(symbols.values());
72846                 }
72847                 return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning);
72848             });
72849             return result;
72850         }
72851         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
72852             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
72853             return symbolResult && ts.symbolName(symbolResult);
72854         }
72855         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
72856             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
72857         }
72858         function getSuggestionForNonexistentExport(name, targetModule) {
72859             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
72860             return suggestion && ts.symbolName(suggestion);
72861         }
72862         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
72863             // check if object type has setter or getter
72864             function hasProp(name) {
72865                 var prop = getPropertyOfObjectType(objectType, name);
72866                 if (prop) {
72867                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
72868                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
72869                 }
72870                 return false;
72871             }
72872             ;
72873             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
72874             if (!hasProp(suggestedMethod)) {
72875                 return undefined;
72876             }
72877             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
72878             if (suggestion === undefined) {
72879                 suggestion = suggestedMethod;
72880             }
72881             else {
72882                 suggestion += "." + suggestedMethod;
72883             }
72884             return suggestion;
72885         }
72886         function getSuggestedTypeForNonexistentStringLiteralType(source, target) {
72887             var candidates = target.types.filter(function (type) { return !!(type.flags & 128 /* StringLiteral */); });
72888             return ts.getSpellingSuggestion(source.value, candidates, function (type) { return type.value; });
72889         }
72890         /**
72891          * 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.
72892          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
72893          *
72894          * If there is a candidate that's the same except for case, return that.
72895          * If there is a candidate that's within one edit of the name, return that.
72896          * Otherwise, return the candidate with the smallest Levenshtein distance,
72897          *    except for candidates:
72898          *      * With no name
72899          *      * Whose meaning doesn't match the `meaning` parameter.
72900          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
72901          *      * Whose levenshtein distance is more than 0.4 of the length of the name
72902          *        (0.4 allows 1 substitution/transposition for every 5 characters,
72903          *         and 1 insertion/deletion at 3 characters)
72904          */
72905         function getSpellingSuggestionForName(name, symbols, meaning) {
72906             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
72907             function getCandidateName(candidate) {
72908                 var candidateName = ts.symbolName(candidate);
72909                 if (ts.startsWith(candidateName, "\"")) {
72910                     return undefined;
72911                 }
72912                 if (candidate.flags & meaning) {
72913                     return candidateName;
72914                 }
72915                 if (candidate.flags & 2097152 /* Alias */) {
72916                     var alias = tryResolveAlias(candidate);
72917                     if (alias && alias.flags & meaning) {
72918                         return candidateName;
72919                     }
72920                 }
72921                 return undefined;
72922             }
72923         }
72924         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) {
72925             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
72926             if (!valueDeclaration) {
72927                 return;
72928             }
72929             var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */);
72930             var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
72931             if (!hasPrivateModifier && !hasPrivateIdentifier) {
72932                 return;
72933             }
72934             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
72935                 return;
72936             }
72937             if (isSelfTypeAccess) {
72938                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
72939                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
72940                 if (containingMethod && containingMethod.symbol === prop) {
72941                     return;
72942                 }
72943             }
72944             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
72945         }
72946         function isSelfTypeAccess(name, parent) {
72947             return name.kind === 108 /* ThisKeyword */
72948                 || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name));
72949         }
72950         function isValidPropertyAccess(node, propertyName) {
72951             switch (node.kind) {
72952                 case 205 /* PropertyAccessExpression */:
72953                     return isValidPropertyAccessWithType(node, node.expression.kind === 106 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
72954                 case 160 /* QualifiedName */:
72955                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
72956                 case 199 /* ImportType */:
72957                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
72958             }
72959         }
72960         /**
72961          * Checks if an existing property access is valid for completions purposes.
72962          * @param node a property access-like node where we want to check if we can access a property.
72963          * This node does not need to be an access of the property we are checking.
72964          * e.g. in completions, this node will often be an incomplete property access node, as in `foo.`.
72965          * Besides providing a location (i.e. scope) used to check property accessibility, we use this node for
72966          * computing whether this is a `super` property access.
72967          * @param type the type whose property we are checking.
72968          * @param property the accessed property's symbol.
72969          */
72970         function isValidPropertyAccessForCompletions(node, type, property) {
72971             return isPropertyAccessible(node, node.kind === 205 /* PropertyAccessExpression */ && node.expression.kind === 106 /* SuperKeyword */, 
72972             /* isWrite */ false, type, property);
72973             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
72974         }
72975         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
72976             // Short-circuiting for improved performance.
72977             if (isTypeAny(type)) {
72978                 return true;
72979             }
72980             var prop = getPropertyOfType(type, propertyName);
72981             return !!prop && isPropertyAccessible(node, isSuper, /* isWrite */ false, type, prop);
72982         }
72983         /**
72984          * Checks if a property can be accessed in a location.
72985          * The location is given by the `node` parameter.
72986          * The node does not need to be a property access.
72987          * @param node location where to check property accessibility
72988          * @param isSuper whether to consider this a `super` property access, e.g. `super.foo`.
72989          * @param isWrite whether this is a write access, e.g. `++foo.x`.
72990          * @param containingType type where the property comes from.
72991          * @param property property symbol.
72992          */
72993         function isPropertyAccessible(node, isSuper, isWrite, containingType, property) {
72994             // Short-circuiting for improved performance.
72995             if (isTypeAny(containingType)) {
72996                 return true;
72997             }
72998             // A #private property access in an optional chain is an error dealt with by the parser.
72999             // The checker does not check for it, so we need to do our own check here.
73000             if (property.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) {
73001                 var declClass_1 = ts.getContainingClass(property.valueDeclaration);
73002                 return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
73003             }
73004             return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property);
73005         }
73006         /**
73007          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
73008          */
73009         function getForInVariableSymbol(node) {
73010             var initializer = node.initializer;
73011             if (initializer.kind === 254 /* VariableDeclarationList */) {
73012                 var variable = initializer.declarations[0];
73013                 if (variable && !ts.isBindingPattern(variable.name)) {
73014                     return getSymbolOfNode(variable);
73015                 }
73016             }
73017             else if (initializer.kind === 79 /* Identifier */) {
73018                 return getResolvedSymbol(initializer);
73019             }
73020             return undefined;
73021         }
73022         /**
73023          * Return true if the given type is considered to have numeric property names.
73024          */
73025         function hasNumericPropertyNames(type) {
73026             return getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, numberType);
73027         }
73028         /**
73029          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
73030          * that references a for-in variable for an object with numeric property names.
73031          */
73032         function isForInVariableForNumericPropertyNames(expr) {
73033             var e = ts.skipParentheses(expr);
73034             if (e.kind === 79 /* Identifier */) {
73035                 var symbol = getResolvedSymbol(e);
73036                 if (symbol.flags & 3 /* Variable */) {
73037                     var child = expr;
73038                     var node = expr.parent;
73039                     while (node) {
73040                         if (node.kind === 242 /* ForInStatement */ &&
73041                             child === node.statement &&
73042                             getForInVariableSymbol(node) === symbol &&
73043                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
73044                             return true;
73045                         }
73046                         child = node;
73047                         node = node.parent;
73048                     }
73049                 }
73050             }
73051             return false;
73052         }
73053         function checkIndexedAccess(node, checkMode) {
73054             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) :
73055                 checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode);
73056         }
73057         function checkElementAccessChain(node, checkMode) {
73058             var exprType = checkExpression(node.expression);
73059             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
73060             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType);
73061         }
73062         function checkElementAccessExpression(node, exprType, checkMode) {
73063             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
73064             var indexExpression = node.argumentExpression;
73065             var indexType = checkExpression(indexExpression);
73066             if (isErrorType(objectType) || objectType === silentNeverType) {
73067                 return objectType;
73068             }
73069             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
73070                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
73071                 return errorType;
73072             }
73073             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
73074             var accessFlags = ts.isAssignmentTarget(node) ?
73075                 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0) :
73076                 32 /* ExpressionPosition */;
73077             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType;
73078             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node);
73079         }
73080         function callLikeExpressionMayHaveTypeArguments(node) {
73081             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
73082         }
73083         function resolveUntypedCall(node) {
73084             if (callLikeExpressionMayHaveTypeArguments(node)) {
73085                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
73086                 // This gets us diagnostics for the type arguments and marks them as referenced.
73087                 ts.forEach(node.typeArguments, checkSourceElement);
73088             }
73089             if (node.kind === 209 /* TaggedTemplateExpression */) {
73090                 checkExpression(node.template);
73091             }
73092             else if (ts.isJsxOpeningLikeElement(node)) {
73093                 checkExpression(node.attributes);
73094             }
73095             else if (node.kind !== 164 /* Decorator */) {
73096                 ts.forEach(node.arguments, function (argument) {
73097                     checkExpression(argument);
73098                 });
73099             }
73100             return anySignature;
73101         }
73102         function resolveErrorCall(node) {
73103             resolveUntypedCall(node);
73104             return unknownSignature;
73105         }
73106         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
73107         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
73108         // A nit here is that we reorder only signatures that belong to the same symbol,
73109         // so order how inherited signatures are processed is still preserved.
73110         // interface A { (x: string): void }
73111         // interface B extends A { (x: 'foo'): string }
73112         // const b: B;
73113         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
73114         function reorderCandidates(signatures, result, callChainFlags) {
73115             var lastParent;
73116             var lastSymbol;
73117             var cutoffIndex = 0;
73118             var index;
73119             var specializedIndex = -1;
73120             var spliceIndex;
73121             ts.Debug.assert(!result.length);
73122             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
73123                 var signature = signatures_7[_i];
73124                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
73125                 var parent = signature.declaration && signature.declaration.parent;
73126                 if (!lastSymbol || symbol === lastSymbol) {
73127                     if (lastParent && parent === lastParent) {
73128                         index = index + 1;
73129                     }
73130                     else {
73131                         lastParent = parent;
73132                         index = cutoffIndex;
73133                     }
73134                 }
73135                 else {
73136                     // current declaration belongs to a different symbol
73137                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
73138                     index = cutoffIndex = result.length;
73139                     lastParent = parent;
73140                 }
73141                 lastSymbol = symbol;
73142                 // specialized signatures always need to be placed before non-specialized signatures regardless
73143                 // of the cutoff position; see GH#1133
73144                 if (signatureHasLiteralTypes(signature)) {
73145                     specializedIndex++;
73146                     spliceIndex = specializedIndex;
73147                     // The cutoff index always needs to be greater than or equal to the specialized signature index
73148                     // in order to prevent non-specialized signatures from being added before a specialized
73149                     // signature.
73150                     cutoffIndex++;
73151                 }
73152                 else {
73153                     spliceIndex = index;
73154                 }
73155                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
73156             }
73157         }
73158         function isSpreadArgument(arg) {
73159             return !!arg && (arg.kind === 224 /* SpreadElement */ || arg.kind === 231 /* SyntheticExpression */ && arg.isSpread);
73160         }
73161         function getSpreadArgumentIndex(args) {
73162             return ts.findIndex(args, isSpreadArgument);
73163         }
73164         function acceptsVoid(t) {
73165             return !!(t.flags & 16384 /* Void */);
73166         }
73167         function acceptsVoidUndefinedUnknownOrAny(t) {
73168             return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
73169         }
73170         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
73171             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
73172             var argCount;
73173             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
73174             var effectiveParameterCount = getParameterCount(signature);
73175             var effectiveMinimumArguments = getMinArgumentCount(signature);
73176             if (node.kind === 209 /* TaggedTemplateExpression */) {
73177                 argCount = args.length;
73178                 if (node.template.kind === 222 /* TemplateExpression */) {
73179                     // If a tagged template expression lacks a tail literal, the call is incomplete.
73180                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
73181                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
73182                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
73183                 }
73184                 else {
73185                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
73186                     // then this might actually turn out to be a TemplateHead in the future;
73187                     // so we consider the call to be incomplete.
73188                     var templateLiteral = node.template;
73189                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
73190                     callIsIncomplete = !!templateLiteral.isUnterminated;
73191                 }
73192             }
73193             else if (node.kind === 164 /* Decorator */) {
73194                 argCount = getDecoratorArgumentCount(node, signature);
73195             }
73196             else if (ts.isJsxOpeningLikeElement(node)) {
73197                 callIsIncomplete = node.attributes.end === node.end;
73198                 if (callIsIncomplete) {
73199                     return true;
73200                 }
73201                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
73202                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
73203                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
73204             }
73205             else if (!node.arguments) {
73206                 // This only happens when we have something of the form: 'new C'
73207                 ts.Debug.assert(node.kind === 208 /* NewExpression */);
73208                 return getMinArgumentCount(signature) === 0;
73209             }
73210             else {
73211                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
73212                 // If we are missing the close parenthesis, the call is incomplete.
73213                 callIsIncomplete = node.arguments.end === node.end;
73214                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
73215                 var spreadArgIndex = getSpreadArgumentIndex(args);
73216                 if (spreadArgIndex >= 0) {
73217                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
73218                 }
73219             }
73220             // Too many arguments implies incorrect arity.
73221             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
73222                 return false;
73223             }
73224             // If the call is incomplete, we should skip the lower bound check.
73225             // JSX signatures can have extra parameters provided by the library which we don't check
73226             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
73227                 return true;
73228             }
73229             for (var i = argCount; i < effectiveMinimumArguments; i++) {
73230                 var type = getTypeAtPosition(signature, i);
73231                 if (filterType(type, ts.isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) {
73232                     return false;
73233                 }
73234             }
73235             return true;
73236         }
73237         function hasCorrectTypeArgumentArity(signature, typeArguments) {
73238             // If the user supplied type arguments, but the number of type arguments does not match
73239             // the declared number of type parameters, the call has an incorrect arity.
73240             var numTypeParameters = ts.length(signature.typeParameters);
73241             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
73242             return !ts.some(typeArguments) ||
73243                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
73244         }
73245         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
73246         function getSingleCallSignature(type) {
73247             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
73248         }
73249         function getSingleCallOrConstructSignature(type) {
73250             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
73251                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
73252         }
73253         function getSingleSignature(type, kind, allowMembers) {
73254             if (type.flags & 524288 /* Object */) {
73255                 var resolved = resolveStructuredTypeMembers(type);
73256                 if (allowMembers || resolved.properties.length === 0 && resolved.indexInfos.length === 0) {
73257                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
73258                         return resolved.callSignatures[0];
73259                     }
73260                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
73261                         return resolved.constructSignatures[0];
73262                     }
73263                 }
73264             }
73265             return undefined;
73266         }
73267         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
73268         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
73269             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
73270             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
73271             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
73272             // for T but leave it possible to later infer '[any]' back to A.
73273             var restType = getEffectiveRestType(contextualSignature);
73274             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
73275             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
73276             applyToParameterTypes(sourceSignature, signature, function (source, target) {
73277                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
73278                 inferTypes(context.inferences, source, target);
73279             });
73280             if (!inferenceContext) {
73281                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
73282                     inferTypes(context.inferences, source, target, 128 /* ReturnType */);
73283                 });
73284             }
73285             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
73286         }
73287         function inferJsxTypeArguments(node, signature, checkMode, context) {
73288             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
73289             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
73290             inferTypes(context.inferences, checkAttrType, paramType);
73291             return getInferredTypes(context);
73292         }
73293         function getThisArgumentType(thisArgumentNode) {
73294             if (!thisArgumentNode) {
73295                 return voidType;
73296             }
73297             var thisArgumentType = checkExpression(thisArgumentNode);
73298             return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) :
73299                 ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) :
73300                     thisArgumentType;
73301         }
73302         function inferTypeArguments(node, signature, args, checkMode, context) {
73303             if (ts.isJsxOpeningLikeElement(node)) {
73304                 return inferJsxTypeArguments(node, signature, checkMode, context);
73305             }
73306             // If a contextual type is available, infer from that type to the return type of the call expression. For
73307             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
73308             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
73309             // return type of 'wrap'.
73310             if (node.kind !== 164 /* Decorator */) {
73311                 var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */);
73312                 if (contextualType) {
73313                     // We clone the inference context to avoid disturbing a resolution in progress for an
73314                     // outer call expression. Effectively we just want a snapshot of whatever has been
73315                     // inferred for any outer call expression so far.
73316                     var outerContext = getInferenceContext(node);
73317                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
73318                     var instantiatedType = instantiateType(contextualType, outerMapper);
73319                     // If the contextual type is a generic function type with a single call signature, we
73320                     // instantiate the type with its own type parameters and type arguments. This ensures that
73321                     // the type parameters are not erased to type any during type inference such that they can
73322                     // be inferred as actual types from the contextual type. For example:
73323                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
73324                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
73325                     // Above, the type of the 'value' parameter is inferred to be 'A'.
73326                     var contextualSignature = getSingleCallSignature(instantiatedType);
73327                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
73328                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
73329                         instantiatedType;
73330                     var inferenceTargetType = getReturnTypeOfSignature(signature);
73331                     // Inferences made from return types have lower priority than all other inferences.
73332                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */);
73333                     // Create a type mapper for instantiating generic contextual types using the inferences made
73334                     // from the return type. We need a separate inference pass here because (a) instantiation of
73335                     // the source type uses the outer context's return mapper (which excludes inferences made from
73336                     // outer arguments), and (b) we don't want any further inferences going into this context.
73337                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
73338                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
73339                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
73340                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
73341                 }
73342             }
73343             var restType = getNonArrayRestType(signature);
73344             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
73345             if (restType && restType.flags & 262144 /* TypeParameter */) {
73346                 var info = ts.find(context.inferences, function (info) { return info.typeParameter === restType; });
73347                 if (info) {
73348                     info.impliedArity = ts.findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : undefined;
73349                 }
73350             }
73351             var thisType = getThisTypeOfSignature(signature);
73352             if (thisType) {
73353                 var thisArgumentNode = getThisArgumentOfCall(node);
73354                 inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType);
73355             }
73356             for (var i = 0; i < argCount; i++) {
73357                 var arg = args[i];
73358                 if (arg.kind !== 226 /* OmittedExpression */) {
73359                     var paramType = getTypeAtPosition(signature, i);
73360                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
73361                     inferTypes(context.inferences, argType, paramType);
73362                 }
73363             }
73364             if (restType) {
73365                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
73366                 inferTypes(context.inferences, spreadType, restType);
73367             }
73368             return getInferredTypes(context);
73369         }
73370         function getMutableArrayOrTupleType(type) {
73371             return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) :
73372                 type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type :
73373                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) :
73374                         createTupleType([type], [8 /* Variadic */]);
73375         }
73376         function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
73377             if (index >= argCount - 1) {
73378                 var arg = args[argCount - 1];
73379                 if (isSpreadArgument(arg)) {
73380                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
73381                     // and the argument are ...x forms.
73382                     return getMutableArrayOrTupleType(arg.kind === 231 /* SyntheticExpression */ ? arg.type :
73383                         checkExpressionWithContextualType(arg.expression, restType, context, checkMode));
73384                 }
73385             }
73386             var types = [];
73387             var flags = [];
73388             var names = [];
73389             for (var i = index; i < argCount; i++) {
73390                 var arg = args[i];
73391                 if (isSpreadArgument(arg)) {
73392                     var spreadType = arg.kind === 231 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
73393                     if (isArrayLikeType(spreadType)) {
73394                         types.push(spreadType);
73395                         flags.push(8 /* Variadic */);
73396                     }
73397                     else {
73398                         types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 224 /* SpreadElement */ ? arg.expression : arg));
73399                         flags.push(4 /* Rest */);
73400                     }
73401                 }
73402                 else {
73403                     var contextualType = getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */);
73404                     var argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
73405                     var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
73406                     types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
73407                     flags.push(1 /* Required */);
73408                 }
73409                 if (arg.kind === 231 /* SyntheticExpression */ && arg.tupleNameSource) {
73410                     names.push(arg.tupleNameSource);
73411                 }
73412             }
73413             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
73414         }
73415         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
73416             var isJavascript = ts.isInJSFile(signature.declaration);
73417             var typeParameters = signature.typeParameters;
73418             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
73419             var mapper;
73420             for (var i = 0; i < typeArgumentNodes.length; i++) {
73421                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
73422                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
73423                 if (constraint) {
73424                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
73425                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
73426                     if (!mapper) {
73427                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
73428                     }
73429                     var typeArgument = typeArgumentTypes[i];
73430                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
73431                         return undefined;
73432                     }
73433                 }
73434             }
73435             return typeArgumentTypes;
73436         }
73437         function getJsxReferenceKind(node) {
73438             if (isJsxIntrinsicIdentifier(node.tagName)) {
73439                 return 2 /* Mixed */;
73440             }
73441             var tagType = getApparentType(checkExpression(node.tagName));
73442             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
73443                 return 0 /* Component */;
73444             }
73445             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
73446                 return 1 /* Function */;
73447             }
73448             return 2 /* Mixed */;
73449         }
73450         /**
73451          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
73452          * @param node a JSX opening-like element we are trying to figure its call signature
73453          * @param signature a candidate signature we are trying whether it is a call signature
73454          * @param relation a relationship to check parameter and argument type
73455          */
73456         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
73457             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
73458             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
73459             // can be specified by users through attributes property.
73460             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
73461             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
73462             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
73463             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
73464             function checkTagNameDoesNotExpectTooManyArguments() {
73465                 var _a;
73466                 if (getJsxNamespaceContainerForImplicitImport(node)) {
73467                     return true; // factory is implicitly jsx/jsxdev - assume it fits the bill, since we don't strongly look for the jsx/jsxs/jsxDEV factory APIs anywhere else (at least not yet)
73468                 }
73469                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
73470                 if (!tagType) {
73471                     return true;
73472                 }
73473                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
73474                 if (!ts.length(tagCallSignatures)) {
73475                     return true;
73476                 }
73477                 var factory = getJsxFactoryEntity(node);
73478                 if (!factory) {
73479                     return true;
73480                 }
73481                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
73482                 if (!factorySymbol) {
73483                     return true;
73484                 }
73485                 var factoryType = getTypeOfSymbol(factorySymbol);
73486                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
73487                 if (!ts.length(callSignatures)) {
73488                     return true;
73489                 }
73490                 var hasFirstParamSignatures = false;
73491                 var maxParamCount = 0;
73492                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
73493                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
73494                     var sig = callSignatures_1[_i];
73495                     var firstparam = getTypeAtPosition(sig, 0);
73496                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
73497                     if (!ts.length(signaturesOfParam))
73498                         continue;
73499                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
73500                         var paramSig = signaturesOfParam_1[_b];
73501                         hasFirstParamSignatures = true;
73502                         if (hasEffectiveRestParameter(paramSig)) {
73503                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
73504                         }
73505                         var paramCount = getParameterCount(paramSig);
73506                         if (paramCount > maxParamCount) {
73507                             maxParamCount = paramCount;
73508                         }
73509                     }
73510                 }
73511                 if (!hasFirstParamSignatures) {
73512                     // Not a single signature had a first parameter which expected a signature - for back compat, and
73513                     // to guard against generic factories which won't have signatures directly, do not error
73514                     return true;
73515                 }
73516                 var absoluteMinArgCount = Infinity;
73517                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
73518                     var tagSig = tagCallSignatures_1[_c];
73519                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
73520                     if (tagRequiredArgCount < absoluteMinArgCount) {
73521                         absoluteMinArgCount = tagRequiredArgCount;
73522                     }
73523                 }
73524                 if (absoluteMinArgCount <= maxParamCount) {
73525                     return true; // some signature accepts the number of arguments the function component provides
73526                 }
73527                 if (reportErrors) {
73528                     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);
73529                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
73530                     if (tagNameDeclaration) {
73531                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
73532                     }
73533                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
73534                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
73535                     }
73536                     if (!errorOutputContainer.skipLogging) {
73537                         diagnostics.add(diag);
73538                     }
73539                 }
73540                 return false;
73541             }
73542         }
73543         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
73544             var errorOutputContainer = { errors: undefined, skipLogging: true };
73545             if (ts.isJsxOpeningLikeElement(node)) {
73546                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
73547                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
73548                     return errorOutputContainer.errors || ts.emptyArray;
73549                 }
73550                 return undefined;
73551             }
73552             var thisType = getThisTypeOfSignature(signature);
73553             if (thisType && thisType !== voidType && node.kind !== 208 /* NewExpression */) {
73554                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
73555                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
73556                 // If the expression is a new expression, then the check is skipped.
73557                 var thisArgumentNode = getThisArgumentOfCall(node);
73558                 var thisArgumentType = getThisArgumentType(thisArgumentNode);
73559                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
73560                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
73561                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
73562                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
73563                     return errorOutputContainer.errors || ts.emptyArray;
73564                 }
73565             }
73566             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
73567             var restType = getNonArrayRestType(signature);
73568             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
73569             for (var i = 0; i < argCount; i++) {
73570                 var arg = args[i];
73571                 if (arg.kind !== 226 /* OmittedExpression */) {
73572                     var paramType = getTypeAtPosition(signature, i);
73573                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
73574                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
73575                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
73576                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
73577                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
73578                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
73579                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
73580                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
73581                         return errorOutputContainer.errors || ts.emptyArray;
73582                     }
73583                 }
73584             }
73585             if (restType) {
73586                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
73587                 var restArgCount = args.length - argCount;
73588                 var errorNode = !reportErrors ? undefined :
73589                     restArgCount === 0 ? node :
73590                         restArgCount === 1 ? args[argCount] :
73591                             ts.setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end);
73592                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
73593                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
73594                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
73595                     return errorOutputContainer.errors || ts.emptyArray;
73596                 }
73597             }
73598             return undefined;
73599             function maybeAddMissingAwaitInfo(errorNode, source, target) {
73600                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
73601                     // Bail if target is Promise-like---something else is wrong
73602                     if (getAwaitedTypeOfPromise(target)) {
73603                         return;
73604                     }
73605                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
73606                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
73607                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
73608                     }
73609                 }
73610             }
73611         }
73612         /**
73613          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
73614          */
73615         function getThisArgumentOfCall(node) {
73616             var expression = node.kind === 207 /* CallExpression */ ? node.expression :
73617                 node.kind === 209 /* TaggedTemplateExpression */ ? node.tag : undefined;
73618             if (expression) {
73619                 var callee = ts.skipOuterExpressions(expression);
73620                 if (ts.isAccessExpression(callee)) {
73621                     return callee.expression;
73622                 }
73623             }
73624         }
73625         function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
73626             var result = ts.parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
73627             ts.setTextRange(result, parent);
73628             ts.setParent(result, parent);
73629             return result;
73630         }
73631         /**
73632          * Returns the effective arguments for an expression that works like a function invocation.
73633          */
73634         function getEffectiveCallArguments(node) {
73635             if (node.kind === 209 /* TaggedTemplateExpression */) {
73636                 var template = node.template;
73637                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
73638                 if (template.kind === 222 /* TemplateExpression */) {
73639                     ts.forEach(template.templateSpans, function (span) {
73640                         args_3.push(span.expression);
73641                     });
73642                 }
73643                 return args_3;
73644             }
73645             if (node.kind === 164 /* Decorator */) {
73646                 return getEffectiveDecoratorArguments(node);
73647             }
73648             if (ts.isJsxOpeningLikeElement(node)) {
73649                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
73650             }
73651             var args = node.arguments || ts.emptyArray;
73652             var spreadIndex = getSpreadArgumentIndex(args);
73653             if (spreadIndex >= 0) {
73654                 // Create synthetic arguments from spreads of tuple types.
73655                 var effectiveArgs_1 = args.slice(0, spreadIndex);
73656                 var _loop_23 = function (i) {
73657                     var arg = args[i];
73658                     // We can call checkExpressionCached because spread expressions never have a contextual type.
73659                     var spreadType = arg.kind === 224 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
73660                     if (spreadType && isTupleType(spreadType)) {
73661                         ts.forEach(getTypeArguments(spreadType), function (t, i) {
73662                             var _a;
73663                             var flags = spreadType.target.elementFlags[i];
73664                             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]);
73665                             effectiveArgs_1.push(syntheticArg);
73666                         });
73667                     }
73668                     else {
73669                         effectiveArgs_1.push(arg);
73670                     }
73671                 };
73672                 for (var i = spreadIndex; i < args.length; i++) {
73673                     _loop_23(i);
73674                 }
73675                 return effectiveArgs_1;
73676             }
73677             return args;
73678         }
73679         /**
73680          * Returns the synthetic argument list for a decorator invocation.
73681          */
73682         function getEffectiveDecoratorArguments(node) {
73683             var parent = node.parent;
73684             var expr = node.expression;
73685             switch (parent.kind) {
73686                 case 256 /* ClassDeclaration */:
73687                 case 225 /* ClassExpression */:
73688                     // For a class decorator, the `target` is the type of the class (e.g. the
73689                     // "static" or "constructor" side of the class).
73690                     return [
73691                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
73692                     ];
73693                 case 163 /* Parameter */:
73694                     // A parameter declaration decorator will have three arguments (see
73695                     // `ParameterDecorator` in core.d.ts).
73696                     var func = parent.parent;
73697                     return [
73698                         createSyntheticExpression(expr, parent.parent.kind === 170 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
73699                         createSyntheticExpression(expr, anyType),
73700                         createSyntheticExpression(expr, numberType)
73701                     ];
73702                 case 166 /* PropertyDeclaration */:
73703                 case 168 /* MethodDeclaration */:
73704                 case 171 /* GetAccessor */:
73705                 case 172 /* SetAccessor */:
73706                     // A method or accessor declaration decorator will have two or three arguments (see
73707                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
73708                     // for ES3, we will only pass two arguments.
73709                     var hasPropDesc = parent.kind !== 166 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
73710                     return [
73711                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
73712                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
73713                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
73714                     ];
73715             }
73716             return ts.Debug.fail();
73717         }
73718         /**
73719          * Returns the argument count for a decorator node that works like a function invocation.
73720          */
73721         function getDecoratorArgumentCount(node, signature) {
73722             switch (node.parent.kind) {
73723                 case 256 /* ClassDeclaration */:
73724                 case 225 /* ClassExpression */:
73725                     return 1;
73726                 case 166 /* PropertyDeclaration */:
73727                     return 2;
73728                 case 168 /* MethodDeclaration */:
73729                 case 171 /* GetAccessor */:
73730                 case 172 /* SetAccessor */:
73731                     // For ES3 or decorators with only two parameters we supply only two arguments
73732                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
73733                 case 163 /* Parameter */:
73734                     return 3;
73735                 default:
73736                     return ts.Debug.fail();
73737             }
73738         }
73739         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
73740             var start;
73741             var length;
73742             var sourceFile = ts.getSourceFileOfNode(node);
73743             if (ts.isPropertyAccessExpression(node.expression)) {
73744                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
73745                 start = nameSpan.start;
73746                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
73747             }
73748             else {
73749                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
73750                 start = expressionSpan.start;
73751                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
73752             }
73753             return { start: start, length: length, sourceFile: sourceFile };
73754         }
73755         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
73756             if (ts.isCallExpression(node)) {
73757                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_6 = _a.length;
73758                 return ts.createFileDiagnostic(sourceFile, start, length_6, message, arg0, arg1, arg2, arg3);
73759             }
73760             else {
73761                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
73762             }
73763         }
73764         function isPromiseResolveArityError(node) {
73765             if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
73766                 return false;
73767             var symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, undefined, undefined, false);
73768             var decl = symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration;
73769             if (!decl || !ts.isParameter(decl) || !ts.isFunctionExpressionOrArrowFunction(decl.parent) || !ts.isNewExpression(decl.parent.parent) || !ts.isIdentifier(decl.parent.parent.expression)) {
73770                 return false;
73771             }
73772             var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
73773             if (!globalPromiseSymbol)
73774                 return false;
73775             var constructorSymbol = getSymbolAtLocation(decl.parent.parent.expression, /*ignoreErrors*/ true);
73776             return constructorSymbol === globalPromiseSymbol;
73777         }
73778         function getArgumentArityError(node, signatures, args) {
73779             var _a;
73780             var spreadIndex = getSpreadArgumentIndex(args);
73781             if (spreadIndex > -1) {
73782                 return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter);
73783             }
73784             var min = Number.POSITIVE_INFINITY; // smallest parameter count
73785             var max = Number.NEGATIVE_INFINITY; // largest parameter count
73786             var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments
73787             var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments
73788             var closestSignature;
73789             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
73790                 var sig = signatures_8[_i];
73791                 var minParameter = getMinArgumentCount(sig);
73792                 var maxParameter = getParameterCount(sig);
73793                 // smallest/largest parameter counts
73794                 if (minParameter < min) {
73795                     min = minParameter;
73796                     closestSignature = sig;
73797                 }
73798                 max = Math.max(max, maxParameter);
73799                 // shortest parameter count *longer than the call*/longest parameter count *shorter than the call*
73800                 if (minParameter < args.length && minParameter > maxBelow)
73801                     maxBelow = minParameter;
73802                 if (args.length < maxParameter && maxParameter < minAbove)
73803                     minAbove = maxParameter;
73804             }
73805             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
73806             var parameterRange = hasRestParameter ? min
73807                 : min < max ? min + "-" + max
73808                     : min;
73809             var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1
73810                 : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise
73811                     : ts.Diagnostics.Expected_0_arguments_but_got_1;
73812             if (min < args.length && args.length < max) {
73813                 // between min and max, but with no matching overload
73814                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove);
73815             }
73816             else if (args.length < min) {
73817                 // too short: put the error span on the call expression, not any of the args
73818                 var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length);
73819                 var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length];
73820                 if (parameter) {
73821                     var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided
73822                         : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided
73823                             : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined);
73824                     return ts.addRelatedInfo(diagnostic, parameterError);
73825                 }
73826                 return diagnostic;
73827             }
73828             else {
73829                 // too long; error goes on the excess parameters
73830                 var errorSpan = ts.factory.createNodeArray(args.slice(max));
73831                 var pos = ts.first(errorSpan).pos;
73832                 var end = ts.last(errorSpan).end;
73833                 if (end === pos) {
73834                     end++;
73835                 }
73836                 ts.setTextRangePosEnd(errorSpan, pos, end);
73837                 return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length);
73838             }
73839         }
73840         function getTypeArgumentArityError(node, signatures, typeArguments) {
73841             var argCount = typeArguments.length;
73842             // No overloads exist
73843             if (signatures.length === 1) {
73844                 var sig = signatures[0];
73845                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
73846                 var max = ts.length(sig.typeParameters);
73847                 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);
73848             }
73849             // Overloads exist
73850             var belowArgCount = -Infinity;
73851             var aboveArgCount = Infinity;
73852             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
73853                 var sig = signatures_9[_i];
73854                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
73855                 var max = ts.length(sig.typeParameters);
73856                 if (min_2 > argCount) {
73857                     aboveArgCount = Math.min(aboveArgCount, min_2);
73858                 }
73859                 else if (max < argCount) {
73860                     belowArgCount = Math.max(belowArgCount, max);
73861                 }
73862             }
73863             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
73864                 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);
73865             }
73866             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
73867         }
73868         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
73869             var isTaggedTemplate = node.kind === 209 /* TaggedTemplateExpression */;
73870             var isDecorator = node.kind === 164 /* Decorator */;
73871             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
73872             var reportErrors = !candidatesOutArray && produceDiagnostics;
73873             var typeArguments;
73874             if (!isDecorator) {
73875                 typeArguments = node.typeArguments;
73876                 // We already perform checking on the type arguments on the class declaration itself.
73877                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SuperKeyword */) {
73878                     ts.forEach(typeArguments, checkSourceElement);
73879                 }
73880             }
73881             var candidates = candidatesOutArray || [];
73882             // reorderCandidates fills up the candidates array directly
73883             reorderCandidates(signatures, candidates, callChainFlags);
73884             if (!candidates.length) {
73885                 if (reportErrors) {
73886                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
73887                 }
73888                 return resolveErrorCall(node);
73889             }
73890             var args = getEffectiveCallArguments(node);
73891             // The excludeArgument array contains true for each context sensitive argument (an argument
73892             // is context sensitive it is susceptible to a one-time permanent contextual typing).
73893             //
73894             // The idea is that we will perform type argument inference & assignability checking once
73895             // without using the susceptible parameters that are functions, and once more for those
73896             // parameters, contextually typing each as we go along.
73897             //
73898             // For a tagged template, then the first argument be 'undefined' if necessary because it
73899             // represents a TemplateStringsArray.
73900             //
73901             // For a decorator, no arguments are susceptible to contextual typing due to the fact
73902             // decorators are applied to a declaration by the emitter, and not to an expression.
73903             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
73904             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
73905             // The following variables are captured and modified by calls to chooseOverload.
73906             // If overload resolution or type argument inference fails, we want to report the
73907             // best error possible. The best error is one which says that an argument was not
73908             // assignable to a parameter. This implies that everything else about the overload
73909             // was fine. So if there is any overload that is only incorrect because of an
73910             // argument, we will report an error on that one.
73911             //
73912             //     function foo(s: string): void;
73913             //     function foo(n: number): void; // Report argument error on this overload
73914             //     function foo(): void;
73915             //     foo(true);
73916             //
73917             // If none of the overloads even made it that far, there are two possibilities.
73918             // There was a problem with type arguments for some overload, in which case
73919             // report an error on that. Or none of the overloads even had correct arity,
73920             // in which case give an arity error.
73921             //
73922             //     function foo<T extends string>(x: T): void; // Report type argument error
73923             //     function foo(): void;
73924             //     foo<number>(0);
73925             //
73926             var candidatesForArgumentError;
73927             var candidateForArgumentArityError;
73928             var candidateForTypeArgumentError;
73929             var result;
73930             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
73931             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
73932             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 207 /* CallExpression */ && node.arguments.hasTrailingComma;
73933             // Section 4.12.1:
73934             // if the candidate list contains one or more signatures for which the type of each argument
73935             // expression is a subtype of each corresponding parameter type, the return type of the first
73936             // of those signatures becomes the return type of the function call.
73937             // Otherwise, the return type of the first signature in the candidate list becomes the return
73938             // type of the function call.
73939             //
73940             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
73941             // is just important for choosing the best signature. So in the case where there is only one
73942             // signature, the subtype pass is useless. So skipping it is an optimization.
73943             if (candidates.length > 1) {
73944                 result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
73945             }
73946             if (!result) {
73947                 result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
73948             }
73949             if (result) {
73950                 return result;
73951             }
73952             // No signatures were applicable. Now report errors based on the last applicable signature with
73953             // no arguments excluded from assignability checks.
73954             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
73955             // skip the checkApplicableSignature check.
73956             if (reportErrors) {
73957                 if (candidatesForArgumentError) {
73958                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
73959                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
73960                         var chain_1;
73961                         if (candidatesForArgumentError.length > 3) {
73962                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
73963                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
73964                         }
73965                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
73966                         if (diags) {
73967                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
73968                                 var d = diags_1[_i];
73969                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
73970                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
73971                                 }
73972                                 addImplementationSuccessElaboration(last_2, d);
73973                                 diagnostics.add(d);
73974                             }
73975                         }
73976                         else {
73977                             ts.Debug.fail("No error for last overload signature");
73978                         }
73979                     }
73980                     else {
73981                         var allDiagnostics = [];
73982                         var max = 0;
73983                         var min_3 = Number.MAX_VALUE;
73984                         var minIndex = 0;
73985                         var i_1 = 0;
73986                         var _loop_24 = function (c) {
73987                             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)); };
73988                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
73989                             if (diags_2) {
73990                                 if (diags_2.length <= min_3) {
73991                                     min_3 = diags_2.length;
73992                                     minIndex = i_1;
73993                                 }
73994                                 max = Math.max(max, diags_2.length);
73995                                 allDiagnostics.push(diags_2);
73996                             }
73997                             else {
73998                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
73999                             }
74000                             i_1++;
74001                         };
74002                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
74003                             var c = candidatesForArgumentError_1[_a];
74004                             _loop_24(c);
74005                         }
74006                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
74007                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
74008                         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);
74009                         // 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
74010                         // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic
74011                         var related = __spreadArray([], ts.flatMap(diags_3, function (d) { return d.relatedInformation; }), true);
74012                         var diag = void 0;
74013                         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; })) {
74014                             var _b = diags_3[0], file = _b.file, start = _b.start, length_7 = _b.length;
74015                             diag = { file: file, start: start, length: length_7, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
74016                         }
74017                         else {
74018                             diag = ts.createDiagnosticForNodeFromMessageChain(node, chain, related);
74019                         }
74020                         addImplementationSuccessElaboration(candidatesForArgumentError[0], diag);
74021                         diagnostics.add(diag);
74022                     }
74023                 }
74024                 else if (candidateForArgumentArityError) {
74025                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
74026                 }
74027                 else if (candidateForTypeArgumentError) {
74028                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
74029                 }
74030                 else {
74031                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
74032                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
74033                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
74034                     }
74035                     else if (!isDecorator) {
74036                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
74037                     }
74038                     else if (fallbackError) {
74039                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
74040                     }
74041                 }
74042             }
74043             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
74044             function addImplementationSuccessElaboration(failed, diagnostic) {
74045                 var _a, _b;
74046                 var oldCandidatesForArgumentError = candidatesForArgumentError;
74047                 var oldCandidateForArgumentArityError = candidateForArgumentArityError;
74048                 var oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
74049                 var failedSignatureDeclarations = ((_b = (_a = failed.declaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.declarations) || ts.emptyArray;
74050                 var isOverload = failedSignatureDeclarations.length > 1;
74051                 var implDecl = isOverload ? ts.find(failedSignatureDeclarations, function (d) { return ts.isFunctionLikeDeclaration(d) && ts.nodeIsPresent(d.body); }) : undefined;
74052                 if (implDecl) {
74053                     var candidate = getSignatureFromDeclaration(implDecl);
74054                     var isSingleNonGenericCandidate_1 = !candidate.typeParameters;
74055                     if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate_1)) {
74056                         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));
74057                     }
74058                 }
74059                 candidatesForArgumentError = oldCandidatesForArgumentError;
74060                 candidateForArgumentArityError = oldCandidateForArgumentArityError;
74061                 candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
74062             }
74063             function chooseOverload(candidates, relation, isSingleNonGenericCandidate, signatureHelpTrailingComma) {
74064                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
74065                 candidatesForArgumentError = undefined;
74066                 candidateForArgumentArityError = undefined;
74067                 candidateForTypeArgumentError = undefined;
74068                 if (isSingleNonGenericCandidate) {
74069                     var candidate = candidates[0];
74070                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
74071                         return undefined;
74072                     }
74073                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
74074                         candidatesForArgumentError = [candidate];
74075                         return undefined;
74076                     }
74077                     return candidate;
74078                 }
74079                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
74080                     var candidate = candidates[candidateIndex];
74081                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
74082                         continue;
74083                     }
74084                     var checkCandidate = void 0;
74085                     var inferenceContext = void 0;
74086                     if (candidate.typeParameters) {
74087                         var typeArgumentTypes = void 0;
74088                         if (ts.some(typeArguments)) {
74089                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
74090                             if (!typeArgumentTypes) {
74091                                 candidateForTypeArgumentError = candidate;
74092                                 continue;
74093                             }
74094                         }
74095                         else {
74096                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
74097                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
74098                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
74099                         }
74100                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
74101                         // If the original signature has a generic rest type, instantiation may produce a
74102                         // signature with different arity and we need to perform another arity check.
74103                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
74104                             candidateForArgumentArityError = checkCandidate;
74105                             continue;
74106                         }
74107                     }
74108                     else {
74109                         checkCandidate = candidate;
74110                     }
74111                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
74112                         // Give preference to error candidates that have no rest parameters (as they are more specific)
74113                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
74114                         continue;
74115                     }
74116                     if (argCheckMode) {
74117                         // If one or more context sensitive arguments were excluded, we start including
74118                         // them now (and keeping do so for any subsequent candidates) and perform a second
74119                         // round of type inference and applicability checking for this particular candidate.
74120                         argCheckMode = 0 /* Normal */;
74121                         if (inferenceContext) {
74122                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
74123                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
74124                             // If the original signature has a generic rest type, instantiation may produce a
74125                             // signature with different arity and we need to perform another arity check.
74126                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
74127                                 candidateForArgumentArityError = checkCandidate;
74128                                 continue;
74129                             }
74130                         }
74131                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
74132                             // Give preference to error candidates that have no rest parameters (as they are more specific)
74133                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
74134                             continue;
74135                         }
74136                     }
74137                     candidates[candidateIndex] = checkCandidate;
74138                     return checkCandidate;
74139                 }
74140                 return undefined;
74141             }
74142         }
74143         // No signature was applicable. We have already reported the errors for the invalid signature.
74144         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
74145             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
74146             checkNodeDeferred(node);
74147             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
74148             // Don't do this if there is a `candidatesOutArray`,
74149             // because then we want the chosen best candidate to be one of the overloads, not a combination.
74150             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
74151                 ? pickLongestCandidateSignature(node, candidates, args)
74152                 : createUnionOfSignaturesForOverloadFailure(candidates);
74153         }
74154         function createUnionOfSignaturesForOverloadFailure(candidates) {
74155             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
74156             var thisParameter;
74157             if (thisParameters.length) {
74158                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
74159             }
74160             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
74161             var parameters = [];
74162             var _loop_25 = function (i) {
74163                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
74164                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
74165                     i < s.parameters.length ? s.parameters[i] : undefined; });
74166                 ts.Debug.assert(symbols.length !== 0);
74167                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
74168             };
74169             for (var i = 0; i < maxNonRestParam; i++) {
74170                 _loop_25(i);
74171             }
74172             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
74173             var flags = 0 /* None */;
74174             if (restParameterSymbols.length !== 0) {
74175                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
74176                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
74177                 flags |= 1 /* HasRestParameter */;
74178             }
74179             if (candidates.some(signatureHasLiteralTypes)) {
74180                 flags |= 2 /* HasLiteralTypes */;
74181             }
74182             return createSignature(candidates[0].declaration, 
74183             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
74184             thisParameter, parameters, 
74185             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
74186             /*typePredicate*/ undefined, minArgumentCount, flags);
74187         }
74188         function getNumNonRestParameters(signature) {
74189             var numParams = signature.parameters.length;
74190             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
74191         }
74192         function createCombinedSymbolFromTypes(sources, types) {
74193             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
74194         }
74195         function createCombinedSymbolForOverloadFailure(sources, type) {
74196             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
74197             return createSymbolWithType(ts.first(sources), type);
74198         }
74199         function pickLongestCandidateSignature(node, candidates, args) {
74200             // Pick the longest signature. This way we can get a contextual type for cases like:
74201             //     declare function f(a: { xa: number; xb: number; }, b: number);
74202             //     f({ |
74203             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
74204             //     declare function f<T>(k: keyof T);
74205             //     f<Foo>("
74206             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
74207             var candidate = candidates[bestIndex];
74208             var typeParameters = candidate.typeParameters;
74209             if (!typeParameters) {
74210                 return candidate;
74211             }
74212             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
74213             var instantiated = typeArgumentNodes
74214                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
74215                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
74216             candidates[bestIndex] = instantiated;
74217             return instantiated;
74218         }
74219         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
74220             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
74221             while (typeArguments.length > typeParameters.length) {
74222                 typeArguments.pop();
74223             }
74224             while (typeArguments.length < typeParameters.length) {
74225                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
74226             }
74227             return typeArguments;
74228         }
74229         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
74230             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
74231             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
74232             return createSignatureInstantiation(candidate, typeArgumentTypes);
74233         }
74234         function getLongestCandidateIndex(candidates, argsCount) {
74235             var maxParamsIndex = -1;
74236             var maxParams = -1;
74237             for (var i = 0; i < candidates.length; i++) {
74238                 var candidate = candidates[i];
74239                 var paramCount = getParameterCount(candidate);
74240                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
74241                     return i;
74242                 }
74243                 if (paramCount > maxParams) {
74244                     maxParams = paramCount;
74245                     maxParamsIndex = i;
74246                 }
74247             }
74248             return maxParamsIndex;
74249         }
74250         function resolveCallExpression(node, candidatesOutArray, checkMode) {
74251             if (node.expression.kind === 106 /* SuperKeyword */) {
74252                 var superType = checkSuperExpression(node.expression);
74253                 if (isTypeAny(superType)) {
74254                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
74255                         var arg = _a[_i];
74256                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
74257                     }
74258                     return anySignature;
74259                 }
74260                 if (!isErrorType(superType)) {
74261                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
74262                     // with the type arguments specified in the extends clause.
74263                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
74264                     if (baseTypeNode) {
74265                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
74266                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
74267                     }
74268                 }
74269                 return resolveUntypedCall(node);
74270             }
74271             var callChainFlags;
74272             var funcType = checkExpression(node.expression);
74273             if (ts.isCallChain(node)) {
74274                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
74275                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
74276                     ts.isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ :
74277                         8 /* IsInnerCallChain */;
74278                 funcType = nonOptionalType;
74279             }
74280             else {
74281                 callChainFlags = 0 /* None */;
74282             }
74283             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
74284             if (funcType === silentNeverType) {
74285                 return silentNeverSignature;
74286             }
74287             var apparentType = getApparentType(funcType);
74288             if (isErrorType(apparentType)) {
74289                 // Another error has already been reported
74290                 return resolveErrorCall(node);
74291             }
74292             // Technically, this signatures list may be incomplete. We are taking the apparent type,
74293             // but we are not including call signatures that may have been added to the Object or
74294             // Function interface, since they have none by default. This is a bit of a leap of faith
74295             // that the user will not add any.
74296             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
74297             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
74298             // TS 1.0 Spec: 4.12
74299             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
74300             // types are provided for the argument expressions, and the result is always of type Any.
74301             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
74302                 // The unknownType indicates that an error already occurred (and was reported).  No
74303                 // need to report another error in this case.
74304                 if (!isErrorType(funcType) && node.typeArguments) {
74305                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
74306                 }
74307                 return resolveUntypedCall(node);
74308             }
74309             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
74310             // TypeScript employs overload resolution in typed function calls in order to support functions
74311             // with multiple call signatures.
74312             if (!callSignatures.length) {
74313                 if (numConstructSignatures) {
74314                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
74315                 }
74316                 else {
74317                     var relatedInformation = void 0;
74318                     if (node.arguments.length === 1) {
74319                         var text = ts.getSourceFileOfNode(node).text;
74320                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
74321                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
74322                         }
74323                     }
74324                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
74325                 }
74326                 return resolveErrorCall(node);
74327             }
74328             // When a call to a generic function is an argument to an outer call to a generic function for which
74329             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
74330             // its contextual type to its return type, deferring the inner call processing allows the best possible
74331             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
74332             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
74333             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
74334             // If no type arguments are specified in the inner call and at least one call signature is generic and
74335             // returns a function type, we choose to defer processing. This narrowly permits function composition
74336             // operators to flow inferences through return types, but otherwise processes calls right away. We
74337             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
74338             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
74339             // from which we never make inferences).
74340             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
74341                 skippedGenericFunction(node, checkMode);
74342                 return resolvingSignature;
74343             }
74344             // If the function is explicitly marked with `@class`, then it must be constructed.
74345             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
74346                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
74347                 return resolveErrorCall(node);
74348             }
74349             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
74350         }
74351         function isGenericFunctionReturningFunction(signature) {
74352             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
74353         }
74354         /**
74355          * TS 1.0 spec: 4.12
74356          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
74357          * but is a subtype of the Function interface, the call is an untyped function call.
74358          */
74359         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
74360             // We exclude union types because we may have a union of function types that happen to have no common signatures.
74361             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
74362                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType);
74363         }
74364         function resolveNewExpression(node, candidatesOutArray, checkMode) {
74365             if (node.arguments && languageVersion < 1 /* ES5 */) {
74366                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
74367                 if (spreadIndex >= 0) {
74368                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
74369                 }
74370             }
74371             var expressionType = checkNonNullExpression(node.expression);
74372             if (expressionType === silentNeverType) {
74373                 return silentNeverSignature;
74374             }
74375             // If expressionType's apparent type(section 3.8.1) is an object type with one or
74376             // more construct signatures, the expression is processed in the same manner as a
74377             // function call, but using the construct signatures as the initial set of candidate
74378             // signatures for overload resolution. The result type of the function call becomes
74379             // the result type of the operation.
74380             expressionType = getApparentType(expressionType);
74381             if (isErrorType(expressionType)) {
74382                 // Another error has already been reported
74383                 return resolveErrorCall(node);
74384             }
74385             // TS 1.0 spec: 4.11
74386             // If expressionType is of type Any, Args can be any argument
74387             // list and the result of the operation is of type Any.
74388             if (isTypeAny(expressionType)) {
74389                 if (node.typeArguments) {
74390                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
74391                 }
74392                 return resolveUntypedCall(node);
74393             }
74394             // Technically, this signatures list may be incomplete. We are taking the apparent type,
74395             // but we are not including construct signatures that may have been added to the Object or
74396             // Function interface, since they have none by default. This is a bit of a leap of faith
74397             // that the user will not add any.
74398             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
74399             if (constructSignatures.length) {
74400                 if (!isConstructorAccessible(node, constructSignatures[0])) {
74401                     return resolveErrorCall(node);
74402                 }
74403                 // If the expression is a class of abstract type, or an abstract construct signature,
74404                 // then it cannot be instantiated.
74405                 // In the case of a merged class-module or class-interface declaration,
74406                 // only the class declaration node will have the Abstract flag set.
74407                 if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; })) {
74408                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
74409                     return resolveErrorCall(node);
74410                 }
74411                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
74412                 if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
74413                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
74414                     return resolveErrorCall(node);
74415                 }
74416                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
74417             }
74418             // If expressionType's apparent type is an object type with no construct signatures but
74419             // one or more call signatures, the expression is processed as a function call. A compile-time
74420             // error occurs if the result of the function call is not Void. The type of the result of the
74421             // operation is Any. It is an error to have a Void this type.
74422             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
74423             if (callSignatures.length) {
74424                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
74425                 if (!noImplicitAny) {
74426                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
74427                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
74428                     }
74429                     if (getThisTypeOfSignature(signature) === voidType) {
74430                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
74431                     }
74432                 }
74433                 return signature;
74434             }
74435             invocationError(node.expression, expressionType, 1 /* Construct */);
74436             return resolveErrorCall(node);
74437         }
74438         function typeHasProtectedAccessibleBase(target, type) {
74439             var baseTypes = getBaseTypes(type);
74440             if (!ts.length(baseTypes)) {
74441                 return false;
74442             }
74443             var firstBase = baseTypes[0];
74444             if (firstBase.flags & 2097152 /* Intersection */) {
74445                 var types = firstBase.types;
74446                 var mixinFlags = findMixins(types);
74447                 var i = 0;
74448                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
74449                     var intersectionMember = _a[_i];
74450                     // We want to ignore mixin ctors
74451                     if (!mixinFlags[i]) {
74452                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
74453                             if (intersectionMember.symbol === target) {
74454                                 return true;
74455                             }
74456                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
74457                                 return true;
74458                             }
74459                         }
74460                     }
74461                     i++;
74462                 }
74463                 return false;
74464             }
74465             if (firstBase.symbol === target) {
74466                 return true;
74467             }
74468             return typeHasProtectedAccessibleBase(target, firstBase);
74469         }
74470         function isConstructorAccessible(node, signature) {
74471             if (!signature || !signature.declaration) {
74472                 return true;
74473             }
74474             var declaration = signature.declaration;
74475             var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
74476             // (1) Public constructors and (2) constructor functions are always accessible.
74477             if (!modifiers || declaration.kind !== 170 /* Constructor */) {
74478                 return true;
74479             }
74480             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
74481             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
74482             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
74483             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
74484                 var containingClass = ts.getContainingClass(node);
74485                 if (containingClass && modifiers & 16 /* Protected */) {
74486                     var containingType = getTypeOfNode(containingClass);
74487                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
74488                         return true;
74489                     }
74490                 }
74491                 if (modifiers & 8 /* Private */) {
74492                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
74493                 }
74494                 if (modifiers & 16 /* Protected */) {
74495                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
74496                 }
74497                 return false;
74498             }
74499             return true;
74500         }
74501         function invocationErrorDetails(errorTarget, apparentType, kind) {
74502             var errorInfo;
74503             var isCall = kind === 0 /* Call */;
74504             var awaitedType = getAwaitedType(apparentType);
74505             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
74506             if (apparentType.flags & 1048576 /* Union */) {
74507                 var types = apparentType.types;
74508                 var hasSignatures = false;
74509                 for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
74510                     var constituent = types_20[_i];
74511                     var signatures = getSignaturesOfType(constituent, kind);
74512                     if (signatures.length !== 0) {
74513                         hasSignatures = true;
74514                         if (errorInfo) {
74515                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
74516                             break;
74517                         }
74518                     }
74519                     else {
74520                         // Error on the first non callable constituent only
74521                         if (!errorInfo) {
74522                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
74523                                 ts.Diagnostics.Type_0_has_no_call_signatures :
74524                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
74525                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
74526                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
74527                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
74528                         }
74529                         if (hasSignatures) {
74530                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
74531                             break;
74532                         }
74533                     }
74534                 }
74535                 if (!hasSignatures) {
74536                     errorInfo = ts.chainDiagnosticMessages(
74537                     /* detials */ undefined, isCall ?
74538                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
74539                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
74540                 }
74541                 if (!errorInfo) {
74542                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
74543                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
74544                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
74545                 }
74546             }
74547             else {
74548                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
74549                     ts.Diagnostics.Type_0_has_no_call_signatures :
74550                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
74551             }
74552             var headMessage = isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable;
74553             // Diagnose get accessors incorrectly called as functions
74554             if (ts.isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
74555                 var resolvedSymbol = getNodeLinks(errorTarget).resolvedSymbol;
74556                 if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
74557                     headMessage = ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
74558                 }
74559             }
74560             return {
74561                 messageChain: ts.chainDiagnosticMessages(errorInfo, headMessage),
74562                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
74563             };
74564         }
74565         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
74566             var _a = invocationErrorDetails(errorTarget, apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
74567             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
74568             if (relatedInfo) {
74569                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
74570             }
74571             if (ts.isCallExpression(errorTarget.parent)) {
74572                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_8 = _b.length;
74573                 diagnostic.start = start;
74574                 diagnostic.length = length_8;
74575             }
74576             diagnostics.add(diagnostic);
74577             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
74578         }
74579         function invocationErrorRecovery(apparentType, kind, diagnostic) {
74580             if (!apparentType.symbol) {
74581                 return;
74582             }
74583             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
74584             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
74585             //  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
74586             if (importNode && !ts.isImportCall(importNode)) {
74587                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
74588                 if (!sigs || !sigs.length)
74589                     return;
74590                 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));
74591             }
74592         }
74593         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
74594             var tagType = checkExpression(node.tag);
74595             var apparentType = getApparentType(tagType);
74596             if (isErrorType(apparentType)) {
74597                 // Another error has already been reported
74598                 return resolveErrorCall(node);
74599             }
74600             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
74601             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
74602             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
74603                 return resolveUntypedCall(node);
74604             }
74605             if (!callSignatures.length) {
74606                 if (ts.isArrayLiteralExpression(node.parent)) {
74607                     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);
74608                     diagnostics.add(diagnostic);
74609                     return resolveErrorCall(node);
74610                 }
74611                 invocationError(node.tag, apparentType, 0 /* Call */);
74612                 return resolveErrorCall(node);
74613             }
74614             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
74615         }
74616         /**
74617          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
74618          */
74619         function getDiagnosticHeadMessageForDecoratorResolution(node) {
74620             switch (node.parent.kind) {
74621                 case 256 /* ClassDeclaration */:
74622                 case 225 /* ClassExpression */:
74623                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
74624                 case 163 /* Parameter */:
74625                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
74626                 case 166 /* PropertyDeclaration */:
74627                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
74628                 case 168 /* MethodDeclaration */:
74629                 case 171 /* GetAccessor */:
74630                 case 172 /* SetAccessor */:
74631                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
74632                 default:
74633                     return ts.Debug.fail();
74634             }
74635         }
74636         /**
74637          * Resolves a decorator as if it were a call expression.
74638          */
74639         function resolveDecorator(node, candidatesOutArray, checkMode) {
74640             var funcType = checkExpression(node.expression);
74641             var apparentType = getApparentType(funcType);
74642             if (isErrorType(apparentType)) {
74643                 return resolveErrorCall(node);
74644             }
74645             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
74646             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
74647             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
74648                 return resolveUntypedCall(node);
74649             }
74650             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
74651                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
74652                 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);
74653                 return resolveErrorCall(node);
74654             }
74655             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
74656             if (!callSignatures.length) {
74657                 var errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
74658                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
74659                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
74660                 if (errorDetails.relatedMessage) {
74661                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
74662                 }
74663                 diagnostics.add(diag);
74664                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
74665                 return resolveErrorCall(node);
74666             }
74667             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
74668         }
74669         function createSignatureForJSXIntrinsic(node, result) {
74670             var namespace = getJsxNamespaceAt(node);
74671             var exports = namespace && getExportsOfSymbol(namespace);
74672             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
74673             // file would probably be preferable.
74674             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
74675             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
74676             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(130 /* AnyKeyword */));
74677             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
74678             parameterSymbol.type = result;
74679             return createSignature(declaration, 
74680             /*typeParameters*/ undefined, 
74681             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
74682             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
74683         }
74684         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
74685             if (isJsxIntrinsicIdentifier(node.tagName)) {
74686                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
74687                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
74688                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
74689                 if (ts.length(node.typeArguments)) {
74690                     ts.forEach(node.typeArguments, checkSourceElement);
74691                     diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), node.typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, 0, ts.length(node.typeArguments)));
74692                 }
74693                 return fakeSignature;
74694             }
74695             var exprTypes = checkExpression(node.tagName);
74696             var apparentType = getApparentType(exprTypes);
74697             if (isErrorType(apparentType)) {
74698                 return resolveErrorCall(node);
74699             }
74700             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
74701             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
74702                 return resolveUntypedCall(node);
74703             }
74704             if (signatures.length === 0) {
74705                 // We found no signatures at all, which is an error
74706                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
74707                 return resolveErrorCall(node);
74708             }
74709             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
74710         }
74711         /**
74712          * Sometimes, we have a decorator that could accept zero arguments,
74713          * but is receiving too many arguments as part of the decorator invocation.
74714          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
74715          */
74716         function isPotentiallyUncalledDecorator(decorator, signatures) {
74717             return signatures.length && ts.every(signatures, function (signature) {
74718                 return signature.minArgumentCount === 0 &&
74719                     !signatureHasRestParameter(signature) &&
74720                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
74721             });
74722         }
74723         function resolveSignature(node, candidatesOutArray, checkMode) {
74724             switch (node.kind) {
74725                 case 207 /* CallExpression */:
74726                     return resolveCallExpression(node, candidatesOutArray, checkMode);
74727                 case 208 /* NewExpression */:
74728                     return resolveNewExpression(node, candidatesOutArray, checkMode);
74729                 case 209 /* TaggedTemplateExpression */:
74730                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
74731                 case 164 /* Decorator */:
74732                     return resolveDecorator(node, candidatesOutArray, checkMode);
74733                 case 279 /* JsxOpeningElement */:
74734                 case 278 /* JsxSelfClosingElement */:
74735                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
74736             }
74737             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
74738         }
74739         /**
74740          * Resolve a signature of a given call-like expression.
74741          * @param node a call-like expression to try resolve a signature for
74742          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
74743          *                           the function will fill it up with appropriate candidate signatures
74744          * @return a signature of the call-like expression or undefined if one can't be found
74745          */
74746         function getResolvedSignature(node, candidatesOutArray, checkMode) {
74747             var links = getNodeLinks(node);
74748             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
74749             // However, it is possible that either candidatesOutArray was not passed in the first time,
74750             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
74751             // to correctly fill the candidatesOutArray.
74752             var cached = links.resolvedSignature;
74753             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
74754                 return cached;
74755             }
74756             links.resolvedSignature = resolvingSignature;
74757             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
74758             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
74759             // resolution should be deferred.
74760             if (result !== resolvingSignature) {
74761                 // If signature resolution originated in control flow type analysis (for example to compute the
74762                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
74763                 // types from the control flow analysis.
74764                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
74765             }
74766             return result;
74767         }
74768         /**
74769          * Indicates whether a declaration can be treated as a constructor in a JavaScript
74770          * file.
74771          */
74772         function isJSConstructor(node) {
74773             var _a;
74774             if (!node || !ts.isInJSFile(node)) {
74775                 return false;
74776             }
74777             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
74778                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
74779                     undefined;
74780             if (func) {
74781                 // If the node has a @class tag, treat it like a constructor.
74782                 if (ts.getJSDocClassTag(node))
74783                     return true;
74784                 // If the symbol of the node has members, treat it like a constructor.
74785                 var symbol = getSymbolOfNode(func);
74786                 return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size);
74787             }
74788             return false;
74789         }
74790         function mergeJSSymbols(target, source) {
74791             var _a, _b;
74792             if (source) {
74793                 var links = getSymbolLinks(source);
74794                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
74795                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
74796                     inferred.exports = inferred.exports || ts.createSymbolTable();
74797                     inferred.members = inferred.members || ts.createSymbolTable();
74798                     inferred.flags |= source.flags & 32 /* Class */;
74799                     if ((_a = source.exports) === null || _a === void 0 ? void 0 : _a.size) {
74800                         mergeSymbolTable(inferred.exports, source.exports);
74801                     }
74802                     if ((_b = source.members) === null || _b === void 0 ? void 0 : _b.size) {
74803                         mergeSymbolTable(inferred.members, source.members);
74804                     }
74805                     (links.inferredClassSymbol || (links.inferredClassSymbol = new ts.Map())).set(getSymbolId(inferred), inferred);
74806                     return inferred;
74807                 }
74808                 return links.inferredClassSymbol.get(getSymbolId(target));
74809             }
74810         }
74811         function getAssignedClassSymbol(decl) {
74812             var _a;
74813             var assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ true);
74814             var prototype = (_a = assignmentSymbol === null || assignmentSymbol === void 0 ? void 0 : assignmentSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("prototype");
74815             var init = (prototype === null || prototype === void 0 ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration);
74816             return init ? getSymbolOfNode(init) : undefined;
74817         }
74818         function getSymbolOfExpando(node, allowDeclaration) {
74819             if (!node.parent) {
74820                 return undefined;
74821             }
74822             var name;
74823             var decl;
74824             if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
74825                 if (!ts.isInJSFile(node) && !(ts.isVarConst(node.parent) && ts.isFunctionLikeDeclaration(node))) {
74826                     return undefined;
74827                 }
74828                 name = node.parent.name;
74829                 decl = node.parent;
74830             }
74831             else if (ts.isBinaryExpression(node.parent)) {
74832                 var parentNode = node.parent;
74833                 var parentNodeOperator = node.parent.operatorToken.kind;
74834                 if (parentNodeOperator === 63 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
74835                     name = parentNode.left;
74836                     decl = name;
74837                 }
74838                 else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
74839                     if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
74840                         name = parentNode.parent.name;
74841                         decl = parentNode.parent;
74842                     }
74843                     else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 63 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) {
74844                         name = parentNode.parent.left;
74845                         decl = name;
74846                     }
74847                     if (!name || !ts.isBindableStaticNameExpression(name) || !ts.isSameEntityName(name, parentNode.left)) {
74848                         return undefined;
74849                     }
74850                 }
74851             }
74852             else if (allowDeclaration && ts.isFunctionDeclaration(node)) {
74853                 name = node.name;
74854                 decl = node;
74855             }
74856             if (!decl || !name || (!allowDeclaration && !ts.getExpandoInitializer(node, ts.isPrototypeAccess(name)))) {
74857                 return undefined;
74858             }
74859             return getSymbolOfNode(decl);
74860         }
74861         function getAssignedJSPrototype(node) {
74862             if (!node.parent) {
74863                 return false;
74864             }
74865             var parent = node.parent;
74866             while (parent && parent.kind === 205 /* PropertyAccessExpression */) {
74867                 parent = parent.parent;
74868             }
74869             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 63 /* EqualsToken */) {
74870                 var right = ts.getInitializerOfBinaryExpression(parent);
74871                 return ts.isObjectLiteralExpression(right) && right;
74872             }
74873         }
74874         /**
74875          * Syntactically and semantically checks a call or new expression.
74876          * @param node The call/new expression to be checked.
74877          * @returns On success, the expression's signature's return type. On failure, anyType.
74878          */
74879         function checkCallExpression(node, checkMode) {
74880             var _a;
74881             if (!checkGrammarTypeArguments(node, node.typeArguments))
74882                 checkGrammarArguments(node.arguments);
74883             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
74884             if (signature === resolvingSignature) {
74885                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
74886                 // returns a function type. We defer checking and return nonInferrableType.
74887                 return nonInferrableType;
74888             }
74889             checkDeprecatedSignature(signature, node);
74890             if (node.expression.kind === 106 /* SuperKeyword */) {
74891                 return voidType;
74892             }
74893             if (node.kind === 208 /* NewExpression */) {
74894                 var declaration = signature.declaration;
74895                 if (declaration &&
74896                     declaration.kind !== 170 /* Constructor */ &&
74897                     declaration.kind !== 174 /* ConstructSignature */ &&
74898                     declaration.kind !== 179 /* ConstructorType */ &&
74899                     !ts.isJSDocConstructSignature(declaration) &&
74900                     !isJSConstructor(declaration)) {
74901                     // When resolved signature is a call signature (and not a construct signature) the result type is any
74902                     if (noImplicitAny) {
74903                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
74904                     }
74905                     return anyType;
74906                 }
74907             }
74908             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
74909             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
74910                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
74911             }
74912             var returnType = getReturnTypeOfSignature(signature);
74913             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
74914             // as a fresh unique symbol literal type.
74915             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
74916                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
74917             }
74918             if (node.kind === 207 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 237 /* ExpressionStatement */ &&
74919                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
74920                 if (!ts.isDottedName(node.expression)) {
74921                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
74922                 }
74923                 else if (!getEffectsSignature(node)) {
74924                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
74925                     getTypeOfDottedName(node.expression, diagnostic);
74926                 }
74927             }
74928             if (ts.isInJSFile(node)) {
74929                 var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false);
74930                 if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) {
74931                     var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, ts.emptyArray);
74932                     jsAssignmentType.objectFlags |= 8192 /* JSLiteral */;
74933                     return getIntersectionType([returnType, jsAssignmentType]);
74934                 }
74935             }
74936             return returnType;
74937         }
74938         function checkDeprecatedSignature(signature, node) {
74939             if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
74940                 var suggestionNode = getDeprecatedSuggestionNode(node);
74941                 var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node));
74942                 addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature));
74943             }
74944         }
74945         function getDeprecatedSuggestionNode(node) {
74946             node = ts.skipParentheses(node);
74947             switch (node.kind) {
74948                 case 207 /* CallExpression */:
74949                 case 164 /* Decorator */:
74950                 case 208 /* NewExpression */:
74951                     return getDeprecatedSuggestionNode(node.expression);
74952                 case 209 /* TaggedTemplateExpression */:
74953                     return getDeprecatedSuggestionNode(node.tag);
74954                 case 279 /* JsxOpeningElement */:
74955                 case 278 /* JsxSelfClosingElement */:
74956                     return getDeprecatedSuggestionNode(node.tagName);
74957                 case 206 /* ElementAccessExpression */:
74958                     return node.argumentExpression;
74959                 case 205 /* PropertyAccessExpression */:
74960                     return node.name;
74961                 case 177 /* TypeReference */:
74962                     var typeReference = node;
74963                     return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
74964                 default:
74965                     return node;
74966             }
74967         }
74968         function isSymbolOrSymbolForCall(node) {
74969             if (!ts.isCallExpression(node))
74970                 return false;
74971             var left = node.expression;
74972             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
74973                 left = left.expression;
74974             }
74975             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
74976                 return false;
74977             }
74978             // make sure `Symbol` is the global symbol
74979             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
74980             if (!globalESSymbol) {
74981                 return false;
74982             }
74983             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
74984         }
74985         function checkImportCallExpression(node) {
74986             // Check grammar of dynamic import
74987             if (!checkGrammarArguments(node.arguments))
74988                 checkGrammarImportCallExpression(node);
74989             if (node.arguments.length === 0) {
74990                 return createPromiseReturnType(node, anyType);
74991             }
74992             var specifier = node.arguments[0];
74993             var specifierType = checkExpressionCached(specifier);
74994             var optionsType = node.arguments.length > 1 ? checkExpressionCached(node.arguments[1]) : undefined;
74995             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
74996             for (var i = 2; i < node.arguments.length; ++i) {
74997                 checkExpressionCached(node.arguments[i]);
74998             }
74999             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
75000                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
75001             }
75002             if (optionsType) {
75003                 var importCallOptionsType = getGlobalImportCallOptionsType(/*reportErrors*/ true);
75004                 if (importCallOptionsType !== emptyObjectType) {
75005                     checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, 32768 /* Undefined */), node.arguments[1]);
75006                 }
75007             }
75008             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
75009             var moduleSymbol = resolveExternalModuleName(node, specifier);
75010             if (moduleSymbol) {
75011                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
75012                 if (esModuleSymbol) {
75013                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) ||
75014                         getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier));
75015                 }
75016             }
75017             return createPromiseReturnType(node, anyType);
75018         }
75019         function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) {
75020             var memberTable = ts.createSymbolTable();
75021             var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
75022             newSymbol.parent = originalSymbol;
75023             newSymbol.nameType = getStringLiteralType("default");
75024             newSymbol.target = resolveSymbol(symbol);
75025             memberTable.set("default" /* Default */, newSymbol);
75026             return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray);
75027         }
75028         function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) {
75029             var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier);
75030             if (hasDefaultOnly && type && !isErrorType(type)) {
75031                 var synthType = type;
75032                 if (!synthType.defaultOnlyType) {
75033                     var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol);
75034                     synthType.defaultOnlyType = type_4;
75035                 }
75036                 return synthType.defaultOnlyType;
75037             }
75038             return undefined;
75039         }
75040         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) {
75041             var _a;
75042             if (allowSyntheticDefaultImports && type && !isErrorType(type)) {
75043                 var synthType = type;
75044                 if (!synthType.syntheticType) {
75045                     var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile);
75046                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier);
75047                     if (hasSyntheticDefault) {
75048                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
75049                         var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol);
75050                         anonymousSymbol.type = defaultContainingObject;
75051                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
75052                     }
75053                     else {
75054                         synthType.syntheticType = type;
75055                     }
75056                 }
75057                 return synthType.syntheticType;
75058             }
75059             return type;
75060         }
75061         function isCommonJsRequire(node) {
75062             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
75063                 return false;
75064             }
75065             // Make sure require is not a local function
75066             if (!ts.isIdentifier(node.expression))
75067                 return ts.Debug.fail();
75068             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
75069             if (resolvedRequire === requireSymbol) {
75070                 return true;
75071             }
75072             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
75073             if (resolvedRequire.flags & 2097152 /* Alias */) {
75074                 return false;
75075             }
75076             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
75077                 ? 255 /* FunctionDeclaration */
75078                 : resolvedRequire.flags & 3 /* Variable */
75079                     ? 253 /* VariableDeclaration */
75080                     : 0 /* Unknown */;
75081             if (targetDeclarationKind !== 0 /* Unknown */) {
75082                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
75083                 // function/variable declaration should be ambient
75084                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
75085             }
75086             return false;
75087         }
75088         function checkTaggedTemplateExpression(node) {
75089             if (!checkGrammarTaggedTemplateChain(node))
75090                 checkGrammarTypeArguments(node, node.typeArguments);
75091             if (languageVersion < 2 /* ES2015 */) {
75092                 checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */);
75093             }
75094             var signature = getResolvedSignature(node);
75095             checkDeprecatedSignature(signature, node);
75096             return getReturnTypeOfSignature(signature);
75097         }
75098         function checkAssertion(node) {
75099             if (node.kind === 210 /* TypeAssertionExpression */) {
75100                 var file = ts.getSourceFileOfNode(node);
75101                 if (file && ts.fileExtensionIsOneOf(file.fileName, [".cts" /* Cts */, ".mts" /* Mts */])) {
75102                     grammarErrorOnNode(node, ts.Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead);
75103                 }
75104             }
75105             return checkAssertionWorker(node, node.type, node.expression);
75106         }
75107         function isValidConstAssertionArgument(node) {
75108             switch (node.kind) {
75109                 case 10 /* StringLiteral */:
75110                 case 14 /* NoSubstitutionTemplateLiteral */:
75111                 case 8 /* NumericLiteral */:
75112                 case 9 /* BigIntLiteral */:
75113                 case 110 /* TrueKeyword */:
75114                 case 95 /* FalseKeyword */:
75115                 case 203 /* ArrayLiteralExpression */:
75116                 case 204 /* ObjectLiteralExpression */:
75117                 case 222 /* TemplateExpression */:
75118                     return true;
75119                 case 211 /* ParenthesizedExpression */:
75120                     return isValidConstAssertionArgument(node.expression);
75121                 case 218 /* PrefixUnaryExpression */:
75122                     var op = node.operator;
75123                     var arg = node.operand;
75124                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
75125                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
75126                 case 205 /* PropertyAccessExpression */:
75127                 case 206 /* ElementAccessExpression */:
75128                     var expr = node.expression;
75129                     var symbol = getTypeOfNode(expr).symbol;
75130                     if (symbol && symbol.flags & 2097152 /* Alias */) {
75131                         symbol = resolveAlias(symbol);
75132                     }
75133                     return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
75134             }
75135             return false;
75136         }
75137         function checkAssertionWorker(errNode, type, expression, checkMode) {
75138             var exprType = checkExpression(expression, checkMode);
75139             if (ts.isConstTypeReference(type)) {
75140                 if (!isValidConstAssertionArgument(expression)) {
75141                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
75142                 }
75143                 return getRegularTypeOfLiteralType(exprType);
75144             }
75145             checkSourceElement(type);
75146             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
75147             var targetType = getTypeFromTypeNode(type);
75148             if (produceDiagnostics && !isErrorType(targetType)) {
75149                 var widenedType = getWidenedType(exprType);
75150                 if (!isTypeComparableTo(targetType, widenedType)) {
75151                     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);
75152                 }
75153             }
75154             return targetType;
75155         }
75156         function checkNonNullChain(node) {
75157             var leftType = checkExpression(node.expression);
75158             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
75159             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
75160         }
75161         function checkNonNullAssertion(node) {
75162             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
75163                 getNonNullableType(checkExpression(node.expression));
75164         }
75165         function checkMetaProperty(node) {
75166             checkGrammarMetaProperty(node);
75167             if (node.keywordToken === 103 /* NewKeyword */) {
75168                 return checkNewTargetMetaProperty(node);
75169             }
75170             if (node.keywordToken === 100 /* ImportKeyword */) {
75171                 return checkImportMetaProperty(node);
75172             }
75173             return ts.Debug.assertNever(node.keywordToken);
75174         }
75175         function checkMetaPropertyKeyword(node) {
75176             switch (node.keywordToken) {
75177                 case 100 /* ImportKeyword */:
75178                     return getGlobalImportMetaExpressionType();
75179                 case 103 /* NewKeyword */:
75180                     var type = checkNewTargetMetaProperty(node);
75181                     return isErrorType(type) ? errorType : createNewTargetExpressionType(type);
75182                 default:
75183                     ts.Debug.assertNever(node.keywordToken);
75184             }
75185         }
75186         function checkNewTargetMetaProperty(node) {
75187             var container = ts.getNewTargetContainer(node);
75188             if (!container) {
75189                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
75190                 return errorType;
75191             }
75192             else if (container.kind === 170 /* Constructor */) {
75193                 var symbol = getSymbolOfNode(container.parent);
75194                 return getTypeOfSymbol(symbol);
75195             }
75196             else {
75197                 var symbol = getSymbolOfNode(container);
75198                 return getTypeOfSymbol(symbol);
75199             }
75200         }
75201         function checkImportMetaProperty(node) {
75202             if (moduleKind === ts.ModuleKind.Node12 || moduleKind === ts.ModuleKind.NodeNext) {
75203                 if (ts.getSourceFileOfNode(node).impliedNodeFormat !== ts.ModuleKind.ESNext) {
75204                     error(node, ts.Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output);
75205                 }
75206             }
75207             else if (moduleKind < ts.ModuleKind.ES2020 && moduleKind !== ts.ModuleKind.System) {
75208                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node12_or_nodenext);
75209             }
75210             var file = ts.getSourceFileOfNode(node);
75211             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
75212             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
75213         }
75214         function getTypeOfParameter(symbol) {
75215             var type = getTypeOfSymbol(symbol);
75216             if (strictNullChecks) {
75217                 var declaration = symbol.valueDeclaration;
75218                 if (declaration && ts.hasInitializer(declaration)) {
75219                     return getOptionalType(type);
75220                 }
75221             }
75222             return type;
75223         }
75224         function getTupleElementLabel(d) {
75225             ts.Debug.assert(ts.isIdentifier(d.name)); // Parameter declarations could be binding patterns, but we only allow identifier names
75226             return d.name.escapedText;
75227         }
75228         function getParameterNameAtPosition(signature, pos, overrideRestType) {
75229             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75230             if (pos < paramCount) {
75231                 return signature.parameters[pos].escapedName;
75232             }
75233             var restParameter = signature.parameters[paramCount] || unknownSymbol;
75234             var restType = overrideRestType || getTypeOfSymbol(restParameter);
75235             if (isTupleType(restType)) {
75236                 var associatedNames = restType.target.labeledElementDeclarations;
75237                 var index = pos - paramCount;
75238                 return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index;
75239             }
75240             return restParameter.escapedName;
75241         }
75242         function getParameterIdentifierNameAtPosition(signature, pos) {
75243             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75244             if (pos < paramCount) {
75245                 var param = signature.parameters[pos];
75246                 return isParameterDeclarationWithIdentifierName(param) ? [param.escapedName, false] : undefined;
75247             }
75248             var restParameter = signature.parameters[paramCount] || unknownSymbol;
75249             if (!isParameterDeclarationWithIdentifierName(restParameter)) {
75250                 return undefined;
75251             }
75252             var restType = getTypeOfSymbol(restParameter);
75253             if (isTupleType(restType)) {
75254                 var associatedNames = restType.target.labeledElementDeclarations;
75255                 var index = pos - paramCount;
75256                 var associatedName = associatedNames === null || associatedNames === void 0 ? void 0 : associatedNames[index];
75257                 var isRestTupleElement = !!(associatedName === null || associatedName === void 0 ? void 0 : associatedName.dotDotDotToken);
75258                 return associatedName ? [
75259                     getTupleElementLabel(associatedName),
75260                     isRestTupleElement
75261                 ] : undefined;
75262             }
75263             if (pos === paramCount) {
75264                 return [restParameter.escapedName, true];
75265             }
75266             return undefined;
75267         }
75268         function isParameterDeclarationWithIdentifierName(symbol) {
75269             return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isIdentifier(symbol.valueDeclaration.name);
75270         }
75271         function isValidDeclarationForTupleLabel(d) {
75272             return d.kind === 196 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name));
75273         }
75274         function getNameableDeclarationAtPosition(signature, pos) {
75275             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75276             if (pos < paramCount) {
75277                 var decl = signature.parameters[pos].valueDeclaration;
75278                 return decl && isValidDeclarationForTupleLabel(decl) ? decl : undefined;
75279             }
75280             var restParameter = signature.parameters[paramCount] || unknownSymbol;
75281             var restType = getTypeOfSymbol(restParameter);
75282             if (isTupleType(restType)) {
75283                 var associatedNames = restType.target.labeledElementDeclarations;
75284                 var index = pos - paramCount;
75285                 return associatedNames && associatedNames[index];
75286             }
75287             return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : undefined;
75288         }
75289         function getTypeAtPosition(signature, pos) {
75290             return tryGetTypeAtPosition(signature, pos) || anyType;
75291         }
75292         function tryGetTypeAtPosition(signature, pos) {
75293             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75294             if (pos < paramCount) {
75295                 return getTypeOfParameter(signature.parameters[pos]);
75296             }
75297             if (signatureHasRestParameter(signature)) {
75298                 // We want to return the value undefined for an out of bounds parameter position,
75299                 // so we need to check bounds here before calling getIndexedAccessType (which
75300                 // otherwise would return the type 'undefined').
75301                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
75302                 var index = pos - paramCount;
75303                 if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) {
75304                     return getIndexedAccessType(restType, getNumberLiteralType(index));
75305                 }
75306             }
75307             return undefined;
75308         }
75309         function getRestTypeAtPosition(source, pos) {
75310             var parameterCount = getParameterCount(source);
75311             var minArgumentCount = getMinArgumentCount(source);
75312             var restType = getEffectiveRestType(source);
75313             if (restType && pos >= parameterCount - 1) {
75314                 return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
75315             }
75316             var types = [];
75317             var flags = [];
75318             var names = [];
75319             for (var i = pos; i < parameterCount; i++) {
75320                 if (!restType || i < parameterCount - 1) {
75321                     types.push(getTypeAtPosition(source, i));
75322                     flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
75323                 }
75324                 else {
75325                     types.push(restType);
75326                     flags.push(8 /* Variadic */);
75327                 }
75328                 var name = getNameableDeclarationAtPosition(source, i);
75329                 if (name) {
75330                     names.push(name);
75331                 }
75332             }
75333             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
75334         }
75335         // Return the number of parameters in a signature. The rest parameter, if present, counts as one
75336         // parameter. For example, the parameter count of (x: number, y: number, ...z: string[]) is 3 and
75337         // the parameter count of (x: number, ...args: [number, ...string[], boolean])) is also 3. In the
75338         // latter example, the effective rest type is [...string[], boolean].
75339         function getParameterCount(signature) {
75340             var length = signature.parameters.length;
75341             if (signatureHasRestParameter(signature)) {
75342                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
75343                 if (isTupleType(restType)) {
75344                     return length + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1);
75345                 }
75346             }
75347             return length;
75348         }
75349         function getMinArgumentCount(signature, flags) {
75350             var strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
75351             var voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
75352             if (voidIsNonOptional || signature.resolvedMinArgumentCount === undefined) {
75353                 var minArgumentCount = void 0;
75354                 if (signatureHasRestParameter(signature)) {
75355                     var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
75356                     if (isTupleType(restType)) {
75357                         var firstOptionalIndex = ts.findIndex(restType.target.elementFlags, function (f) { return !(f & 1 /* Required */); });
75358                         var requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
75359                         if (requiredCount > 0) {
75360                             minArgumentCount = signature.parameters.length - 1 + requiredCount;
75361                         }
75362                     }
75363                 }
75364                 if (minArgumentCount === undefined) {
75365                     if (!strongArityForUntypedJS && signature.flags & 32 /* IsUntypedSignatureInJSFile */) {
75366                         return 0;
75367                     }
75368                     minArgumentCount = signature.minArgumentCount;
75369                 }
75370                 if (voidIsNonOptional) {
75371                     return minArgumentCount;
75372                 }
75373                 for (var i = minArgumentCount - 1; i >= 0; i--) {
75374                     var type = getTypeAtPosition(signature, i);
75375                     if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
75376                         break;
75377                     }
75378                     minArgumentCount = i;
75379                 }
75380                 signature.resolvedMinArgumentCount = minArgumentCount;
75381             }
75382             return signature.resolvedMinArgumentCount;
75383         }
75384         function hasEffectiveRestParameter(signature) {
75385             if (signatureHasRestParameter(signature)) {
75386                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
75387                 return !isTupleType(restType) || restType.target.hasRestElement;
75388             }
75389             return false;
75390         }
75391         function getEffectiveRestType(signature) {
75392             if (signatureHasRestParameter(signature)) {
75393                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
75394                 if (!isTupleType(restType)) {
75395                     return restType;
75396                 }
75397                 if (restType.target.hasRestElement) {
75398                     return sliceTupleType(restType, restType.target.fixedLength);
75399                 }
75400             }
75401             return undefined;
75402         }
75403         function getNonArrayRestType(signature) {
75404             var restType = getEffectiveRestType(signature);
75405             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
75406         }
75407         function getTypeOfFirstParameterOfSignature(signature) {
75408             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
75409         }
75410         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
75411             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
75412         }
75413         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
75414             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75415             for (var i = 0; i < len; i++) {
75416                 var declaration = signature.parameters[i].valueDeclaration;
75417                 if (declaration.type) {
75418                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
75419                     if (typeNode) {
75420                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
75421                     }
75422                 }
75423             }
75424             var restType = getEffectiveRestType(context);
75425             if (restType && restType.flags & 262144 /* TypeParameter */) {
75426                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
75427                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
75428                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
75429                 assignContextualParameterTypes(signature, instantiatedContext);
75430                 // We then infer from a tuple type representing the parameters that correspond to the contextual
75431                 // rest parameter.
75432                 var restPos = getParameterCount(context) - 1;
75433                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
75434             }
75435         }
75436         function assignContextualParameterTypes(signature, context) {
75437             if (context.typeParameters) {
75438                 if (!signature.typeParameters) {
75439                     signature.typeParameters = context.typeParameters;
75440                 }
75441                 else {
75442                     return; // This signature has already has a contextual inference performed and cached on it!
75443                 }
75444             }
75445             if (context.thisParameter) {
75446                 var parameter = signature.thisParameter;
75447                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
75448                     if (!parameter) {
75449                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
75450                     }
75451                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
75452                 }
75453             }
75454             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
75455             for (var i = 0; i < len; i++) {
75456                 var parameter = signature.parameters[i];
75457                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
75458                     var contextualParameterType = tryGetTypeAtPosition(context, i);
75459                     assignParameterType(parameter, contextualParameterType);
75460                 }
75461             }
75462             if (signatureHasRestParameter(signature)) {
75463                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
75464                 var parameter = ts.last(signature.parameters);
75465                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
75466                     var contextualParameterType = getRestTypeAtPosition(context, len);
75467                     assignParameterType(parameter, contextualParameterType);
75468                 }
75469             }
75470         }
75471         function assignNonContextualParameterTypes(signature) {
75472             if (signature.thisParameter) {
75473                 assignParameterType(signature.thisParameter);
75474             }
75475             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
75476                 var parameter = _a[_i];
75477                 assignParameterType(parameter);
75478             }
75479         }
75480         function assignParameterType(parameter, type) {
75481             var links = getSymbolLinks(parameter);
75482             if (!links.type) {
75483                 var declaration = parameter.valueDeclaration;
75484                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
75485                 if (declaration.name.kind !== 79 /* Identifier */) {
75486                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
75487                     if (links.type === unknownType) {
75488                         links.type = getTypeFromBindingPattern(declaration.name);
75489                     }
75490                     assignBindingElementTypes(declaration.name);
75491                 }
75492             }
75493         }
75494         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
75495         // the destructured type into the contained binding elements.
75496         function assignBindingElementTypes(pattern) {
75497             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
75498                 var element = _a[_i];
75499                 if (!ts.isOmittedExpression(element)) {
75500                     if (element.name.kind === 79 /* Identifier */) {
75501                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
75502                     }
75503                     else {
75504                         assignBindingElementTypes(element.name);
75505                     }
75506                 }
75507             }
75508         }
75509         function createPromiseType(promisedType) {
75510             // creates a `Promise<T>` type where `T` is the promisedType argument
75511             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
75512             if (globalPromiseType !== emptyGenericType) {
75513                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
75514                 // Unwrap an `Awaited<T>` to `T` to improve inference.
75515                 promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
75516                 return createTypeReference(globalPromiseType, [promisedType]);
75517             }
75518             return unknownType;
75519         }
75520         function createPromiseLikeType(promisedType) {
75521             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
75522             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
75523             if (globalPromiseLikeType !== emptyGenericType) {
75524                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
75525                 // Unwrap an `Awaited<T>` to `T` to improve inference.
75526                 promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
75527                 return createTypeReference(globalPromiseLikeType, [promisedType]);
75528             }
75529             return unknownType;
75530         }
75531         function createPromiseReturnType(func, promisedType) {
75532             var promiseType = createPromiseType(promisedType);
75533             if (promiseType === unknownType) {
75534                 error(func, ts.isImportCall(func) ?
75535                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
75536                     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);
75537                 return errorType;
75538             }
75539             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
75540                 error(func, ts.isImportCall(func) ?
75541                     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 :
75542                     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);
75543             }
75544             return promiseType;
75545         }
75546         function createNewTargetExpressionType(targetType) {
75547             // Create a synthetic type `NewTargetExpression { target: TargetType; }`
75548             var symbol = createSymbol(0 /* None */, "NewTargetExpression");
75549             var targetPropertySymbol = createSymbol(4 /* Property */, "target", 8 /* Readonly */);
75550             targetPropertySymbol.parent = symbol;
75551             targetPropertySymbol.type = targetType;
75552             var members = ts.createSymbolTable([targetPropertySymbol]);
75553             symbol.members = members;
75554             return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, ts.emptyArray);
75555         }
75556         function getReturnTypeFromBody(func, checkMode) {
75557             if (!func.body) {
75558                 return errorType;
75559             }
75560             var functionFlags = ts.getFunctionFlags(func);
75561             var isAsync = (functionFlags & 2 /* Async */) !== 0;
75562             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
75563             var returnType;
75564             var yieldType;
75565             var nextType;
75566             var fallbackReturnType = voidType;
75567             if (func.body.kind !== 234 /* Block */) { // Async or normal arrow function
75568                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
75569                 if (isAsync) {
75570                     // From within an async function you can return either a non-promise value or a promise. Any
75571                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
75572                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
75573                     // the native Promise<T> type later in this function.
75574                     returnType = unwrapAwaitedType(checkAwaitedType(returnType, /*withAlias*/ false, /*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));
75575                 }
75576             }
75577             else if (isGenerator) { // Generator or AsyncGenerator function
75578                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
75579                 if (!returnTypes) {
75580                     fallbackReturnType = neverType;
75581                 }
75582                 else if (returnTypes.length > 0) {
75583                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
75584                 }
75585                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
75586                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
75587                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
75588             }
75589             else { // Async or normal function
75590                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
75591                 if (!types) {
75592                     // For an async function, the return type will not be never, but rather a Promise for never.
75593                     return functionFlags & 2 /* Async */
75594                         ? createPromiseReturnType(func, neverType) // Async function
75595                         : neverType; // Normal function
75596                 }
75597                 if (types.length === 0) {
75598                     // For an async function, the return type will not be void, but rather a Promise for void.
75599                     return functionFlags & 2 /* Async */
75600                         ? createPromiseReturnType(func, voidType) // Async function
75601                         : voidType; // Normal function
75602                 }
75603                 // Return a union of the return expression types.
75604                 returnType = getUnionType(types, 2 /* Subtype */);
75605             }
75606             if (returnType || yieldType || nextType) {
75607                 if (yieldType)
75608                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
75609                 if (returnType)
75610                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
75611                 if (nextType)
75612                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
75613                 if (returnType && isUnitType(returnType) ||
75614                     yieldType && isUnitType(yieldType) ||
75615                     nextType && isUnitType(nextType)) {
75616                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
75617                     var contextualType = !contextualSignature ? undefined :
75618                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
75619                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
75620                     if (isGenerator) {
75621                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
75622                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
75623                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
75624                     }
75625                     else {
75626                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
75627                     }
75628                 }
75629                 if (yieldType)
75630                     yieldType = getWidenedType(yieldType);
75631                 if (returnType)
75632                     returnType = getWidenedType(returnType);
75633                 if (nextType)
75634                     nextType = getWidenedType(nextType);
75635             }
75636             if (isGenerator) {
75637                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
75638             }
75639             else {
75640                 // From within an async function you can return either a non-promise value or a promise. Any
75641                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
75642                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
75643                 return isAsync
75644                     ? createPromiseType(returnType || fallbackReturnType)
75645                     : returnType || fallbackReturnType;
75646             }
75647         }
75648         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
75649             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
75650             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
75651             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
75652             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
75653             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
75654             if (globalGeneratorType === emptyGenericType) {
75655                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
75656                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
75657                 // nextType.
75658                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
75659                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
75660                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
75661                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
75662                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
75663                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
75664                     if (globalType !== emptyGenericType) {
75665                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
75666                     }
75667                     // The global IterableIterator type doesn't exist, so report an error
75668                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
75669                     return emptyObjectType;
75670                 }
75671                 // The global Generator type doesn't exist, so report an error
75672                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
75673                 return emptyObjectType;
75674             }
75675             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
75676         }
75677         function checkAndAggregateYieldOperandTypes(func, checkMode) {
75678             var yieldTypes = [];
75679             var nextTypes = [];
75680             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
75681             ts.forEachYieldExpression(func.body, function (yieldExpression) {
75682                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
75683                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
75684                 var nextType;
75685                 if (yieldExpression.asteriskToken) {
75686                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
75687                     nextType = iterationTypes && iterationTypes.nextType;
75688                 }
75689                 else {
75690                     nextType = getContextualType(yieldExpression);
75691                 }
75692                 if (nextType)
75693                     ts.pushIfUnique(nextTypes, nextType);
75694             });
75695             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
75696         }
75697         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
75698             var errorNode = node.expression || node;
75699             // A `yield*` expression effectively yields everything that its operand yields
75700             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
75701             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
75702                 ? 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
75703                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
75704         }
75705         /**
75706          * Collect the TypeFacts learned from a typeof switch with
75707          * total clauses `witnesses`, and the active clause ranging
75708          * from `start` to `end`. Parameter `hasDefault` denotes
75709          * whether the active clause contains a default clause.
75710          */
75711         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
75712             var facts = 0 /* None */;
75713             // When in the default we only collect inequality facts
75714             // because default is 'in theory' a set of infinite
75715             // equalities.
75716             if (hasDefault) {
75717                 // Value is not equal to any types after the active clause.
75718                 for (var i = end; i < witnesses.length; i++) {
75719                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
75720                 }
75721                 // Remove inequalities for types that appear in the
75722                 // active clause because they appear before other
75723                 // types collected so far.
75724                 for (var i = start; i < end; i++) {
75725                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
75726                 }
75727                 // Add inequalities for types before the active clause unconditionally.
75728                 for (var i = 0; i < start; i++) {
75729                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
75730                 }
75731             }
75732             // When in an active clause without default the set of
75733             // equalities is finite.
75734             else {
75735                 // Add equalities for all types in the active clause.
75736                 for (var i = start; i < end; i++) {
75737                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
75738                 }
75739                 // Remove equalities for types that appear before the
75740                 // active clause.
75741                 for (var i = 0; i < start; i++) {
75742                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
75743                 }
75744             }
75745             return facts;
75746         }
75747         function isExhaustiveSwitchStatement(node) {
75748             var links = getNodeLinks(node);
75749             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
75750         }
75751         function computeExhaustiveSwitchStatement(node) {
75752             if (node.expression.kind === 215 /* TypeOfExpression */) {
75753                 var operandType = getTypeOfExpression(node.expression.expression);
75754                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
75755                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
75756                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
75757                 var type_5 = getBaseConstraintOfType(operandType) || operandType;
75758                 // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
75759                 if (type_5.flags & 3 /* AnyOrUnknown */) {
75760                     return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
75761                 }
75762                 return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
75763             }
75764             var type = getTypeOfExpression(node.expression);
75765             if (!isLiteralType(type)) {
75766                 return false;
75767             }
75768             var switchTypes = getSwitchClauseTypes(node);
75769             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
75770                 return false;
75771             }
75772             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
75773         }
75774         function functionHasImplicitReturn(func) {
75775             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
75776         }
75777         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
75778         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
75779             var functionFlags = ts.getFunctionFlags(func);
75780             var aggregatedTypes = [];
75781             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
75782             var hasReturnOfTypeNever = false;
75783             ts.forEachReturnStatement(func.body, function (returnStatement) {
75784                 var expr = returnStatement.expression;
75785                 if (expr) {
75786                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
75787                     if (functionFlags & 2 /* Async */) {
75788                         // From within an async function you can return either a non-promise value or a promise. Any
75789                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
75790                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
75791                         // the native Promise<T> type by the caller.
75792                         type = unwrapAwaitedType(checkAwaitedType(type, /*withAlias*/ false, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member));
75793                     }
75794                     if (type.flags & 131072 /* Never */) {
75795                         hasReturnOfTypeNever = true;
75796                     }
75797                     ts.pushIfUnique(aggregatedTypes, type);
75798                 }
75799                 else {
75800                     hasReturnWithNoExpression = true;
75801                 }
75802             });
75803             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
75804                 return undefined;
75805             }
75806             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
75807                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
75808                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
75809                 ts.pushIfUnique(aggregatedTypes, undefinedType);
75810             }
75811             return aggregatedTypes;
75812         }
75813         function mayReturnNever(func) {
75814             switch (func.kind) {
75815                 case 212 /* FunctionExpression */:
75816                 case 213 /* ArrowFunction */:
75817                     return true;
75818                 case 168 /* MethodDeclaration */:
75819                     return func.parent.kind === 204 /* ObjectLiteralExpression */;
75820                 default:
75821                     return false;
75822             }
75823         }
75824         /**
75825          * TypeScript Specification 1.0 (6.3) - July 2014
75826          *   An explicitly typed function whose return type isn't the Void type,
75827          *   the Any type, or a union type containing the Void or Any type as a constituent
75828          *   must have at least one return statement somewhere in its body.
75829          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
75830          *
75831          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
75832          */
75833         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
75834             if (!produceDiagnostics) {
75835                 return;
75836             }
75837             var functionFlags = ts.getFunctionFlags(func);
75838             var type = returnType && unwrapReturnType(returnType, functionFlags);
75839             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
75840             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
75841                 return;
75842             }
75843             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
75844             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
75845             if (func.kind === 167 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 234 /* Block */ || !functionHasImplicitReturn(func)) {
75846                 return;
75847             }
75848             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
75849             var errorNode = ts.getEffectiveReturnTypeNode(func) || func;
75850             if (type && type.flags & 131072 /* Never */) {
75851                 error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
75852             }
75853             else if (type && !hasExplicitReturn) {
75854                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
75855                 // this function does not conform to the specification.
75856                 error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
75857             }
75858             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
75859                 error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
75860             }
75861             else if (compilerOptions.noImplicitReturns) {
75862                 if (!type) {
75863                     // If return type annotation is omitted check if function has any explicit return statements.
75864                     // If it does not have any - its inferred return type is void - don't do any checks.
75865                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
75866                     if (!hasExplicitReturn) {
75867                         return;
75868                     }
75869                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
75870                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
75871                         return;
75872                     }
75873                 }
75874                 error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value);
75875             }
75876         }
75877         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
75878             ts.Debug.assert(node.kind !== 168 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
75879             checkNodeDeferred(node);
75880             if (ts.isFunctionExpression(node)) {
75881                 checkCollisionsForDeclarationName(node, node.name);
75882             }
75883             // The identityMapper object is used to indicate that function expressions are wildcards
75884             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
75885                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
75886                 if (!ts.getEffectiveReturnTypeNode(node) && !ts.hasContextSensitiveParameters(node)) {
75887                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
75888                     var contextualSignature = getContextualSignature(node);
75889                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
75890                         var links = getNodeLinks(node);
75891                         if (links.contextFreeType) {
75892                             return links.contextFreeType;
75893                         }
75894                         var returnType = getReturnTypeFromBody(node, checkMode);
75895                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
75896                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, ts.emptyArray);
75897                         returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
75898                         return links.contextFreeType = returnOnlyType;
75899                     }
75900                 }
75901                 return anyFunctionType;
75902             }
75903             // Grammar checking
75904             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
75905             if (!hasGrammarError && node.kind === 212 /* FunctionExpression */) {
75906                 checkGrammarForGenerator(node);
75907             }
75908             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
75909             return getTypeOfSymbol(getSymbolOfNode(node));
75910         }
75911         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
75912             var links = getNodeLinks(node);
75913             // Check if function expression is contextually typed and assign parameter types if so.
75914             if (!(links.flags & 1024 /* ContextChecked */)) {
75915                 var contextualSignature = getContextualSignature(node);
75916                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
75917                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
75918                 // already assigned contextual types.
75919                 if (!(links.flags & 1024 /* ContextChecked */)) {
75920                     links.flags |= 1024 /* ContextChecked */;
75921                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
75922                     if (!signature) {
75923                         return;
75924                     }
75925                     if (isContextSensitive(node)) {
75926                         if (contextualSignature) {
75927                             var inferenceContext = getInferenceContext(node);
75928                             if (checkMode && checkMode & 2 /* Inferential */) {
75929                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
75930                             }
75931                             var instantiatedContextualSignature = inferenceContext ?
75932                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
75933                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
75934                         }
75935                         else {
75936                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
75937                             assignNonContextualParameterTypes(signature);
75938                         }
75939                     }
75940                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
75941                         var returnType = getReturnTypeFromBody(node, checkMode);
75942                         if (!signature.resolvedReturnType) {
75943                             signature.resolvedReturnType = returnType;
75944                         }
75945                     }
75946                     checkSignatureDeclaration(node);
75947                 }
75948             }
75949         }
75950         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
75951             ts.Debug.assert(node.kind !== 168 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
75952             var functionFlags = ts.getFunctionFlags(node);
75953             var returnType = getReturnTypeFromAnnotation(node);
75954             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
75955             if (node.body) {
75956                 if (!ts.getEffectiveReturnTypeNode(node)) {
75957                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
75958                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
75959                     // of a function. Because checking of function expression bodies is deferred, there was never an
75960                     // appropriate time to do this during the main walk of the file (see the comment at the top of
75961                     // checkFunctionExpressionBodies). So it must be done now.
75962                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
75963                 }
75964                 if (node.body.kind === 234 /* Block */) {
75965                     checkSourceElement(node.body);
75966                 }
75967                 else {
75968                     // From within an async function you can return either a non-promise value or a promise. Any
75969                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
75970                     // should not be checking assignability of a promise to the return type. Instead, we need to
75971                     // check assignability of the awaited type of the expression body against the promised type of
75972                     // its return type annotation.
75973                     var exprType = checkExpression(node.body);
75974                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
75975                     if (returnOrPromisedType) {
75976                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
75977                             var awaitedType = checkAwaitedType(exprType, /*withAlias*/ false, 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);
75978                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
75979                         }
75980                         else { // Normal function
75981                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
75982                         }
75983                     }
75984                 }
75985             }
75986         }
75987         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
75988             if (isAwaitValid === void 0) { isAwaitValid = false; }
75989             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
75990                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
75991                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
75992                 return false;
75993             }
75994             return true;
75995         }
75996         function isReadonlyAssignmentDeclaration(d) {
75997             if (!ts.isCallExpression(d)) {
75998                 return false;
75999             }
76000             if (!ts.isBindableObjectDefinePropertyCall(d)) {
76001                 return false;
76002             }
76003             var objectLitType = checkExpressionCached(d.arguments[2]);
76004             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
76005             if (valueType) {
76006                 var writableProp = getPropertyOfType(objectLitType, "writable");
76007                 var writableType = writableProp && getTypeOfSymbol(writableProp);
76008                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
76009                     return true;
76010                 }
76011                 // We include this definition whereupon we walk back and check the type at the declaration because
76012                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
76013                 // argument types, should the type be contextualized by the call itself.
76014                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
76015                     var initializer = writableProp.valueDeclaration.initializer;
76016                     var rawOriginalType = checkExpression(initializer);
76017                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
76018                         return true;
76019                     }
76020                 }
76021                 return false;
76022             }
76023             var setProp = getPropertyOfType(objectLitType, "set");
76024             return !setProp;
76025         }
76026         function isReadonlySymbol(symbol) {
76027             // The following symbols are considered read-only:
76028             // Properties with a 'readonly' modifier
76029             // Variables declared with 'const'
76030             // Get accessors without matching set accessors
76031             // Enum members
76032             // Object.defineProperty assignments with writable false or no setter
76033             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
76034             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
76035                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
76036                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
76037                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
76038                 symbol.flags & 8 /* EnumMember */ ||
76039                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
76040         }
76041         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
76042             var _a, _b;
76043             if (assignmentKind === 0 /* None */) {
76044                 // no assigment means it doesn't matter whether the entity is readonly
76045                 return false;
76046             }
76047             if (isReadonlySymbol(symbol)) {
76048                 // Allow assignments to readonly properties within constructors of the same class declaration.
76049                 if (symbol.flags & 4 /* Property */ &&
76050                     ts.isAccessExpression(expr) &&
76051                     expr.expression.kind === 108 /* ThisKeyword */) {
76052                     // Look for if this is the constructor for the class that `symbol` is a property of.
76053                     var ctor = ts.getContainingFunction(expr);
76054                     if (!(ctor && (ctor.kind === 170 /* Constructor */ || isJSConstructor(ctor)))) {
76055                         return true;
76056                     }
76057                     if (symbol.valueDeclaration) {
76058                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
76059                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
76060                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
76061                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
76062                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
76063                         var isWriteableSymbol = isLocalPropertyDeclaration
76064                             || isLocalParameterProperty
76065                             || isLocalThisPropertyAssignment
76066                             || isLocalThisPropertyAssignmentConstructorFunction;
76067                         return !isWriteableSymbol;
76068                     }
76069                 }
76070                 return true;
76071             }
76072             if (ts.isAccessExpression(expr)) {
76073                 // references through namespace import should be readonly
76074                 var node = ts.skipParentheses(expr.expression);
76075                 if (node.kind === 79 /* Identifier */) {
76076                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
76077                     if (symbol_2.flags & 2097152 /* Alias */) {
76078                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
76079                         return !!declaration && declaration.kind === 267 /* NamespaceImport */;
76080                     }
76081                 }
76082             }
76083             return false;
76084         }
76085         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
76086             // References are combinations of identifiers, parentheses, and property accesses.
76087             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
76088             if (node.kind !== 79 /* Identifier */ && !ts.isAccessExpression(node)) {
76089                 error(expr, invalidReferenceMessage);
76090                 return false;
76091             }
76092             if (node.flags & 32 /* OptionalChain */) {
76093                 error(expr, invalidOptionalChainMessage);
76094                 return false;
76095             }
76096             return true;
76097         }
76098         function checkDeleteExpression(node) {
76099             checkExpression(node.expression);
76100             var expr = ts.skipParentheses(node.expression);
76101             if (!ts.isAccessExpression(expr)) {
76102                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
76103                 return booleanType;
76104             }
76105             if (ts.isPropertyAccessExpression(expr) && ts.isPrivateIdentifier(expr.name)) {
76106                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
76107             }
76108             var links = getNodeLinks(expr);
76109             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
76110             if (symbol) {
76111                 if (isReadonlySymbol(symbol)) {
76112                     error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
76113                 }
76114                 checkDeleteExpressionMustBeOptional(expr, symbol);
76115             }
76116             return booleanType;
76117         }
76118         function checkDeleteExpressionMustBeOptional(expr, symbol) {
76119             var type = getTypeOfSymbol(symbol);
76120             if (strictNullChecks &&
76121                 !(type.flags & (3 /* AnyOrUnknown */ | 131072 /* Never */)) &&
76122                 !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : getFalsyFlags(type) & 32768 /* Undefined */)) {
76123                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
76124             }
76125         }
76126         function checkTypeOfExpression(node) {
76127             checkExpression(node.expression);
76128             return typeofType;
76129         }
76130         function checkVoidExpression(node) {
76131             checkExpression(node.expression);
76132             return undefinedWideningType;
76133         }
76134         function checkAwaitExpression(node) {
76135             // Grammar checking
76136             if (produceDiagnostics) {
76137                 var container = ts.getContainingFunctionOrClassStaticBlock(node);
76138                 if (container && ts.isClassStaticBlockDeclaration(container)) {
76139                     error(node, ts.Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block);
76140                 }
76141                 else if (!(node.flags & 32768 /* AwaitContext */)) {
76142                     if (ts.isInTopLevelContext(node)) {
76143                         var sourceFile = ts.getSourceFileOfNode(node);
76144                         if (!hasParseDiagnostics(sourceFile)) {
76145                             var span = void 0;
76146                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
76147                                 if (!span)
76148                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
76149                                 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);
76150                                 diagnostics.add(diagnostic);
76151                             }
76152                             if ((moduleKind !== ts.ModuleKind.ES2022 && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System && !(moduleKind === ts.ModuleKind.NodeNext && ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.ESNext)) || languageVersion < 4 /* ES2017 */) {
76153                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
76154                                 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_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher);
76155                                 diagnostics.add(diagnostic);
76156                             }
76157                         }
76158                     }
76159                     else {
76160                         // use of 'await' in non-async function
76161                         var sourceFile = ts.getSourceFileOfNode(node);
76162                         if (!hasParseDiagnostics(sourceFile)) {
76163                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
76164                             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);
76165                             if (container && container.kind !== 170 /* Constructor */ && (ts.getFunctionFlags(container) & 2 /* Async */) === 0) {
76166                                 var relatedInfo = ts.createDiagnosticForNode(container, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
76167                                 ts.addRelatedInfo(diagnostic, relatedInfo);
76168                             }
76169                             diagnostics.add(diagnostic);
76170                         }
76171                     }
76172                 }
76173                 if (isInParameterInitializerBeforeContainingFunction(node)) {
76174                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
76175                 }
76176             }
76177             var operandType = checkExpression(node.expression);
76178             var awaitedType = checkAwaitedType(operandType, /*withAlias*/ true, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
76179             if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & 3 /* AnyOrUnknown */)) {
76180                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
76181             }
76182             return awaitedType;
76183         }
76184         function checkPrefixUnaryExpression(node) {
76185             var operandType = checkExpression(node.operand);
76186             if (operandType === silentNeverType) {
76187                 return silentNeverType;
76188             }
76189             switch (node.operand.kind) {
76190                 case 8 /* NumericLiteral */:
76191                     switch (node.operator) {
76192                         case 40 /* MinusToken */:
76193                             return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text));
76194                         case 39 /* PlusToken */:
76195                             return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text));
76196                     }
76197                     break;
76198                 case 9 /* BigIntLiteral */:
76199                     if (node.operator === 40 /* MinusToken */) {
76200                         return getFreshTypeOfLiteralType(getBigIntLiteralType({
76201                             negative: true,
76202                             base10Value: ts.parsePseudoBigInt(node.operand.text)
76203                         }));
76204                     }
76205             }
76206             switch (node.operator) {
76207                 case 39 /* PlusToken */:
76208                 case 40 /* MinusToken */:
76209                 case 54 /* TildeToken */:
76210                     checkNonNullType(operandType, node.operand);
76211                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
76212                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
76213                     }
76214                     if (node.operator === 39 /* PlusToken */) {
76215                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
76216                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
76217                         }
76218                         return numberType;
76219                     }
76220                     return getUnaryResultType(operandType);
76221                 case 53 /* ExclamationToken */:
76222                     checkTruthinessExpression(node.operand);
76223                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
76224                     return facts === 4194304 /* Truthy */ ? falseType :
76225                         facts === 8388608 /* Falsy */ ? trueType :
76226                             booleanType;
76227                 case 45 /* PlusPlusToken */:
76228                 case 46 /* MinusMinusToken */:
76229                     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);
76230                     if (ok) {
76231                         // run check only if former checks succeeded to avoid reporting cascading errors
76232                         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);
76233                     }
76234                     return getUnaryResultType(operandType);
76235             }
76236             return errorType;
76237         }
76238         function checkPostfixUnaryExpression(node) {
76239             var operandType = checkExpression(node.operand);
76240             if (operandType === silentNeverType) {
76241                 return silentNeverType;
76242             }
76243             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);
76244             if (ok) {
76245                 // run check only if former checks succeeded to avoid reporting cascading errors
76246                 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);
76247             }
76248             return getUnaryResultType(operandType);
76249         }
76250         function getUnaryResultType(operandType) {
76251             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
76252                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
76253                     ? numberOrBigIntType
76254                     : bigintType;
76255             }
76256             // If it's not a bigint type, implicit coercion will result in a number
76257             return numberType;
76258         }
76259         // Return true if type might be of the given kind. A union or intersection type might be of a given
76260         // kind if at least one constituent type is of the given kind.
76261         function maybeTypeOfKind(type, kind) {
76262             if (type.flags & kind) {
76263                 return true;
76264             }
76265             if (type.flags & 3145728 /* UnionOrIntersection */) {
76266                 var types = type.types;
76267                 for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
76268                     var t = types_21[_i];
76269                     if (maybeTypeOfKind(t, kind)) {
76270                         return true;
76271                     }
76272                 }
76273             }
76274             return false;
76275         }
76276         function isTypeAssignableToKind(source, kind, strict) {
76277             if (source.flags & kind) {
76278                 return true;
76279             }
76280             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
76281                 return false;
76282             }
76283             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
76284                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
76285                 !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
76286                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
76287                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
76288                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
76289                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
76290                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
76291                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
76292                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
76293         }
76294         function allTypesAssignableToKind(source, kind, strict) {
76295             return source.flags & 1048576 /* Union */ ?
76296                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
76297                 isTypeAssignableToKind(source, kind, strict);
76298         }
76299         function isConstEnumObjectType(type) {
76300             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
76301         }
76302         function isConstEnumSymbol(symbol) {
76303             return (symbol.flags & 128 /* ConstEnum */) !== 0;
76304         }
76305         function checkInstanceOfExpression(left, right, leftType, rightType) {
76306             if (leftType === silentNeverType || rightType === silentNeverType) {
76307                 return silentNeverType;
76308             }
76309             // TypeScript 1.0 spec (April 2014): 4.15.4
76310             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
76311             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
76312             // The result is always of the Boolean primitive type.
76313             // NOTE: do not raise error if leftType is unknown as related error was already reported
76314             if (!isTypeAny(leftType) &&
76315                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
76316                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
76317             }
76318             // NOTE: do not raise error if right is unknown as related error was already reported
76319             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
76320                 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);
76321             }
76322             return booleanType;
76323         }
76324         function checkInExpression(left, right, leftType, rightType) {
76325             if (leftType === silentNeverType || rightType === silentNeverType) {
76326                 return silentNeverType;
76327             }
76328             if (ts.isPrivateIdentifier(left)) {
76329                 if (languageVersion < 99 /* ESNext */) {
76330                     checkExternalEmitHelpers(left, 2097152 /* ClassPrivateFieldIn */);
76331                 }
76332                 // Unlike in 'checkPrivateIdentifierExpression' we now have access to the RHS type
76333                 // which provides us with the opportunity to emit more detailed errors
76334                 if (!getNodeLinks(left).resolvedSymbol && ts.getContainingClass(left)) {
76335                     var isUncheckedJS = isUncheckedJSSuggestion(left, rightType.symbol, /*excludeClasses*/ true);
76336                     reportNonexistentProperty(left, rightType, isUncheckedJS);
76337                 }
76338             }
76339             else {
76340                 leftType = checkNonNullType(leftType, left);
76341                 // TypeScript 1.0 spec (April 2014): 4.15.5
76342                 // Require the left operand to be of type Any, the String primitive type, or the Number primitive type.
76343                 if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
76344                     isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) {
76345                     error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or_symbol);
76346                 }
76347             }
76348             rightType = checkNonNullType(rightType, right);
76349             // TypeScript 1.0 spec (April 2014): 4.15.5
76350             // The in operator requires the right operand to be
76351             //
76352             //   1. assignable to the non-primitive type,
76353             //   2. an unconstrained type parameter,
76354             //   3. a union or intersection including one or more type parameters, whose constituents are all assignable to the
76355             //      the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the
76356             //      non-primitive type, or
76357             //   4. a type parameter whose constraint is
76358             //      i. an object type,
76359             //     ii. the non-primitive type, or
76360             //    iii. a union or intersection with at least one constituent assignable to an object or non-primitive type.
76361             //
76362             // The divergent behavior for type parameters and unions containing type parameters is a workaround for type
76363             // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance
76364             // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error
76365             // unless *all* instantiations would result in an error.
76366             //
76367             // The result is always of the Boolean primitive type.
76368             var rightTypeConstraint = getConstraintOfType(rightType);
76369             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
76370                 rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
76371                     !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) {
76372                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive);
76373             }
76374             return booleanType;
76375         }
76376         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
76377             var properties = node.properties;
76378             if (strictNullChecks && properties.length === 0) {
76379                 return checkNonNullType(sourceType, node);
76380             }
76381             for (var i = 0; i < properties.length; i++) {
76382                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
76383             }
76384             return sourceType;
76385         }
76386         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
76387         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
76388             if (rightIsThis === void 0) { rightIsThis = false; }
76389             var properties = node.properties;
76390             var property = properties[propertyIndex];
76391             if (property.kind === 294 /* PropertyAssignment */ || property.kind === 295 /* ShorthandPropertyAssignment */) {
76392                 var name = property.name;
76393                 var exprType = getLiteralTypeFromPropertyName(name);
76394                 if (isTypeUsableAsPropertyName(exprType)) {
76395                     var text = getPropertyNameFromType(exprType);
76396                     var prop = getPropertyOfType(objectLiteralType, text);
76397                     if (prop) {
76398                         markPropertyAsReferenced(prop, property, rightIsThis);
76399                         checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop);
76400                     }
76401                 }
76402                 var elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */, name);
76403                 var type = getFlowTypeOfDestructuring(property, elementType);
76404                 return checkDestructuringAssignment(property.kind === 295 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
76405             }
76406             else if (property.kind === 296 /* SpreadAssignment */) {
76407                 if (propertyIndex < properties.length - 1) {
76408                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
76409                 }
76410                 else {
76411                     if (languageVersion < 99 /* ESNext */) {
76412                         checkExternalEmitHelpers(property, 4 /* Rest */);
76413                     }
76414                     var nonRestNames = [];
76415                     if (allProperties) {
76416                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
76417                             var otherProperty = allProperties_1[_i];
76418                             if (!ts.isSpreadAssignment(otherProperty)) {
76419                                 nonRestNames.push(otherProperty.name);
76420                             }
76421                         }
76422                     }
76423                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
76424                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
76425                     return checkDestructuringAssignment(property.expression, type);
76426                 }
76427             }
76428             else {
76429                 error(property, ts.Diagnostics.Property_assignment_expected);
76430             }
76431         }
76432         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
76433             var elements = node.elements;
76434             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
76435                 checkExternalEmitHelpers(node, 512 /* Read */);
76436             }
76437             // This elementType will be used if the specific property corresponding to this index is not
76438             // present (aka the tuple element property). This call also checks that the parentType is in
76439             // fact an iterable or array (depending on target language).
76440             var possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
76441             var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType;
76442             for (var i = 0; i < elements.length; i++) {
76443                 var type = possiblyOutOfBoundsType;
76444                 if (node.elements[i].kind === 224 /* SpreadElement */) {
76445                     type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
76446                 }
76447                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
76448             }
76449             return sourceType;
76450         }
76451         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
76452             var elements = node.elements;
76453             var element = elements[elementIndex];
76454             if (element.kind !== 226 /* OmittedExpression */) {
76455                 if (element.kind !== 224 /* SpreadElement */) {
76456                     var indexType = getNumberLiteralType(elementIndex);
76457                     if (isArrayLikeType(sourceType)) {
76458                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
76459                         // when the element is a SyntaxKind.ElementAccessExpression.
76460                         var accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* NoTupleBoundsCheck */ : 0);
76461                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType;
76462                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
76463                         var type = getFlowTypeOfDestructuring(element, assignedType);
76464                         return checkDestructuringAssignment(element, type, checkMode);
76465                     }
76466                     return checkDestructuringAssignment(element, elementType, checkMode);
76467                 }
76468                 if (elementIndex < elements.length - 1) {
76469                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
76470                 }
76471                 else {
76472                     var restExpression = element.expression;
76473                     if (restExpression.kind === 220 /* BinaryExpression */ && restExpression.operatorToken.kind === 63 /* EqualsToken */) {
76474                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
76475                     }
76476                     else {
76477                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
76478                         var type = everyType(sourceType, isTupleType) ?
76479                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
76480                             createArrayType(elementType);
76481                         return checkDestructuringAssignment(restExpression, type, checkMode);
76482                     }
76483                 }
76484             }
76485             return undefined;
76486         }
76487         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
76488             var target;
76489             if (exprOrAssignment.kind === 295 /* ShorthandPropertyAssignment */) {
76490                 var prop = exprOrAssignment;
76491                 if (prop.objectAssignmentInitializer) {
76492                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
76493                     // undefined from the final type.
76494                     if (strictNullChecks &&
76495                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
76496                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
76497                     }
76498                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
76499                 }
76500                 target = exprOrAssignment.name;
76501             }
76502             else {
76503                 target = exprOrAssignment;
76504             }
76505             if (target.kind === 220 /* BinaryExpression */ && target.operatorToken.kind === 63 /* EqualsToken */) {
76506                 checkBinaryExpression(target, checkMode);
76507                 target = target.left;
76508             }
76509             if (target.kind === 204 /* ObjectLiteralExpression */) {
76510                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
76511             }
76512             if (target.kind === 203 /* ArrayLiteralExpression */) {
76513                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
76514             }
76515             return checkReferenceAssignment(target, sourceType, checkMode);
76516         }
76517         function checkReferenceAssignment(target, sourceType, checkMode) {
76518             var targetType = checkExpression(target, checkMode);
76519             var error = target.parent.kind === 296 /* SpreadAssignment */ ?
76520                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
76521                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
76522             var optionalError = target.parent.kind === 296 /* SpreadAssignment */ ?
76523                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
76524                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
76525             if (checkReferenceExpression(target, error, optionalError)) {
76526                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
76527             }
76528             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
76529                 checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */);
76530             }
76531             return sourceType;
76532         }
76533         /**
76534          * This is a *shallow* check: An expression is side-effect-free if the
76535          * evaluation of the expression *itself* cannot produce side effects.
76536          * For example, x++ / 3 is side-effect free because the / operator
76537          * does not have side effects.
76538          * The intent is to "smell test" an expression for correctness in positions where
76539          * its value is discarded (e.g. the left side of the comma operator).
76540          */
76541         function isSideEffectFree(node) {
76542             node = ts.skipParentheses(node);
76543             switch (node.kind) {
76544                 case 79 /* Identifier */:
76545                 case 10 /* StringLiteral */:
76546                 case 13 /* RegularExpressionLiteral */:
76547                 case 209 /* TaggedTemplateExpression */:
76548                 case 222 /* TemplateExpression */:
76549                 case 14 /* NoSubstitutionTemplateLiteral */:
76550                 case 8 /* NumericLiteral */:
76551                 case 9 /* BigIntLiteral */:
76552                 case 110 /* TrueKeyword */:
76553                 case 95 /* FalseKeyword */:
76554                 case 104 /* NullKeyword */:
76555                 case 152 /* UndefinedKeyword */:
76556                 case 212 /* FunctionExpression */:
76557                 case 225 /* ClassExpression */:
76558                 case 213 /* ArrowFunction */:
76559                 case 203 /* ArrayLiteralExpression */:
76560                 case 204 /* ObjectLiteralExpression */:
76561                 case 215 /* TypeOfExpression */:
76562                 case 229 /* NonNullExpression */:
76563                 case 278 /* JsxSelfClosingElement */:
76564                 case 277 /* JsxElement */:
76565                     return true;
76566                 case 221 /* ConditionalExpression */:
76567                     return isSideEffectFree(node.whenTrue) &&
76568                         isSideEffectFree(node.whenFalse);
76569                 case 220 /* BinaryExpression */:
76570                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
76571                         return false;
76572                     }
76573                     return isSideEffectFree(node.left) &&
76574                         isSideEffectFree(node.right);
76575                 case 218 /* PrefixUnaryExpression */:
76576                 case 219 /* PostfixUnaryExpression */:
76577                     // Unary operators ~, !, +, and - have no side effects.
76578                     // The rest do.
76579                     switch (node.operator) {
76580                         case 53 /* ExclamationToken */:
76581                         case 39 /* PlusToken */:
76582                         case 40 /* MinusToken */:
76583                         case 54 /* TildeToken */:
76584                             return true;
76585                     }
76586                     return false;
76587                 // Some forms listed here for clarity
76588                 case 216 /* VoidExpression */: // Explicit opt-out
76589                 case 210 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
76590                 case 228 /* AsExpression */: // Not SEF, but can produce useful type warnings
76591                 default:
76592                     return false;
76593             }
76594         }
76595         function isTypeEqualityComparableTo(source, target) {
76596             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
76597         }
76598         function createCheckBinaryExpression() {
76599             var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState);
76600             return function (node, checkMode) {
76601                 var result = trampoline(node, checkMode);
76602                 ts.Debug.assertIsDefined(result);
76603                 return result;
76604             };
76605             function onEnter(node, state, checkMode) {
76606                 if (state) {
76607                     state.stackIndex++;
76608                     state.skip = false;
76609                     setLeftType(state, /*type*/ undefined);
76610                     setLastResult(state, /*type*/ undefined);
76611                 }
76612                 else {
76613                     state = {
76614                         checkMode: checkMode,
76615                         skip: false,
76616                         stackIndex: 0,
76617                         typeStack: [undefined, undefined],
76618                     };
76619                 }
76620                 if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
76621                     state.skip = true;
76622                     setLastResult(state, checkExpression(node.right, checkMode));
76623                     return state;
76624                 }
76625                 checkGrammarNullishCoalesceWithLogicalExpression(node);
76626                 var operator = node.operatorToken.kind;
76627                 if (operator === 63 /* EqualsToken */ && (node.left.kind === 204 /* ObjectLiteralExpression */ || node.left.kind === 203 /* ArrayLiteralExpression */)) {
76628                     state.skip = true;
76629                     setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 108 /* ThisKeyword */));
76630                     return state;
76631                 }
76632                 return state;
76633             }
76634             function onLeft(left, state, _node) {
76635                 if (!state.skip) {
76636                     return maybeCheckExpression(state, left);
76637                 }
76638             }
76639             function onOperator(operatorToken, state, node) {
76640                 if (!state.skip) {
76641                     var leftType = getLastResult(state);
76642                     ts.Debug.assertIsDefined(leftType);
76643                     setLeftType(state, leftType);
76644                     setLastResult(state, /*type*/ undefined);
76645                     var operator = operatorToken.kind;
76646                     if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
76647                         if (operator === 55 /* AmpersandAmpersandToken */) {
76648                             var parent = ts.walkUpParenthesizedExpressions(node.parent);
76649                             checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined);
76650                         }
76651                         checkTruthinessOfType(leftType, node.left);
76652                     }
76653                 }
76654             }
76655             function onRight(right, state, _node) {
76656                 if (!state.skip) {
76657                     return maybeCheckExpression(state, right);
76658                 }
76659             }
76660             function onExit(node, state) {
76661                 var result;
76662                 if (state.skip) {
76663                     result = getLastResult(state);
76664                 }
76665                 else {
76666                     var leftType = getLeftType(state);
76667                     ts.Debug.assertIsDefined(leftType);
76668                     var rightType = getLastResult(state);
76669                     ts.Debug.assertIsDefined(rightType);
76670                     result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node);
76671                 }
76672                 state.skip = false;
76673                 setLeftType(state, /*type*/ undefined);
76674                 setLastResult(state, /*type*/ undefined);
76675                 state.stackIndex--;
76676                 return result;
76677             }
76678             function foldState(state, result, _side) {
76679                 setLastResult(state, result);
76680                 return state;
76681             }
76682             function maybeCheckExpression(state, node) {
76683                 if (ts.isBinaryExpression(node)) {
76684                     return node;
76685                 }
76686                 setLastResult(state, checkExpression(node, state.checkMode));
76687             }
76688             function getLeftType(state) {
76689                 return state.typeStack[state.stackIndex];
76690             }
76691             function setLeftType(state, type) {
76692                 state.typeStack[state.stackIndex] = type;
76693             }
76694             function getLastResult(state) {
76695                 return state.typeStack[state.stackIndex + 1];
76696             }
76697             function setLastResult(state, type) {
76698                 // To reduce overhead, reuse the next stack entry to store the
76699                 // last result. This avoids the overhead of an additional property
76700                 // on `WorkArea` and reuses empty stack entries as we walk back up
76701                 // the stack.
76702                 state.typeStack[state.stackIndex + 1] = type;
76703             }
76704         }
76705         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
76706             var left = node.left, operatorToken = node.operatorToken, right = node.right;
76707             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
76708                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
76709                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
76710                 }
76711                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
76712                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
76713                 }
76714             }
76715         }
76716         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
76717         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
76718         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
76719             var operator = operatorToken.kind;
76720             if (operator === 63 /* EqualsToken */ && (left.kind === 204 /* ObjectLiteralExpression */ || left.kind === 203 /* ArrayLiteralExpression */)) {
76721                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 108 /* ThisKeyword */);
76722             }
76723             var leftType;
76724             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
76725                 leftType = checkTruthinessExpression(left, checkMode);
76726             }
76727             else {
76728                 leftType = checkExpression(left, checkMode);
76729             }
76730             var rightType = checkExpression(right, checkMode);
76731             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
76732         }
76733         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
76734             var operator = operatorToken.kind;
76735             switch (operator) {
76736                 case 41 /* AsteriskToken */:
76737                 case 42 /* AsteriskAsteriskToken */:
76738                 case 66 /* AsteriskEqualsToken */:
76739                 case 67 /* AsteriskAsteriskEqualsToken */:
76740                 case 43 /* SlashToken */:
76741                 case 68 /* SlashEqualsToken */:
76742                 case 44 /* PercentToken */:
76743                 case 69 /* PercentEqualsToken */:
76744                 case 40 /* MinusToken */:
76745                 case 65 /* MinusEqualsToken */:
76746                 case 47 /* LessThanLessThanToken */:
76747                 case 70 /* LessThanLessThanEqualsToken */:
76748                 case 48 /* GreaterThanGreaterThanToken */:
76749                 case 71 /* GreaterThanGreaterThanEqualsToken */:
76750                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
76751                 case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
76752                 case 51 /* BarToken */:
76753                 case 74 /* BarEqualsToken */:
76754                 case 52 /* CaretToken */:
76755                 case 78 /* CaretEqualsToken */:
76756                 case 50 /* AmpersandToken */:
76757                 case 73 /* AmpersandEqualsToken */:
76758                     if (leftType === silentNeverType || rightType === silentNeverType) {
76759                         return silentNeverType;
76760                     }
76761                     leftType = checkNonNullType(leftType, left);
76762                     rightType = checkNonNullType(rightType, right);
76763                     var suggestedOperator = void 0;
76764                     // if a user tries to apply a bitwise operator to 2 boolean operands
76765                     // try and return them a helpful suggestion
76766                     if ((leftType.flags & 528 /* BooleanLike */) &&
76767                         (rightType.flags & 528 /* BooleanLike */) &&
76768                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
76769                         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));
76770                         return numberType;
76771                     }
76772                     else {
76773                         // otherwise just check each operand separately and report errors as normal
76774                         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);
76775                         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);
76776                         var resultType_1;
76777                         // If both are any or unknown, allow operation; assume it will resolve to number
76778                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
76779                             // Or, if neither could be bigint, implicit coercion results in a number result
76780                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
76781                             resultType_1 = numberType;
76782                         }
76783                         // At least one is assignable to bigint, so check that both are
76784                         else if (bothAreBigIntLike(leftType, rightType)) {
76785                             switch (operator) {
76786                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
76787                                 case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
76788                                     reportOperatorError();
76789                                     break;
76790                                 case 42 /* AsteriskAsteriskToken */:
76791                                 case 67 /* AsteriskAsteriskEqualsToken */:
76792                                     if (languageVersion < 3 /* ES2016 */) {
76793                                         error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
76794                                     }
76795                             }
76796                             resultType_1 = bigintType;
76797                         }
76798                         // Exactly one of leftType/rightType is assignable to bigint
76799                         else {
76800                             reportOperatorError(bothAreBigIntLike);
76801                             resultType_1 = errorType;
76802                         }
76803                         if (leftOk && rightOk) {
76804                             checkAssignmentOperator(resultType_1);
76805                         }
76806                         return resultType_1;
76807                     }
76808                 case 39 /* PlusToken */:
76809                 case 64 /* PlusEqualsToken */:
76810                     if (leftType === silentNeverType || rightType === silentNeverType) {
76811                         return silentNeverType;
76812                     }
76813                     if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
76814                         leftType = checkNonNullType(leftType, left);
76815                         rightType = checkNonNullType(rightType, right);
76816                     }
76817                     var resultType = void 0;
76818                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
76819                         // Operands of an enum type are treated as having the primitive type Number.
76820                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
76821                         resultType = numberType;
76822                     }
76823                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
76824                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
76825                         resultType = bigintType;
76826                     }
76827                     else if (isTypeAssignableToKind(leftType, 402653316 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 402653316 /* StringLike */, /*strict*/ true)) {
76828                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
76829                         resultType = stringType;
76830                     }
76831                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
76832                         // Otherwise, the result is of type Any.
76833                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
76834                         resultType = isErrorType(leftType) || isErrorType(rightType) ? errorType : anyType;
76835                     }
76836                     // Symbols are not allowed at all in arithmetic expressions
76837                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
76838                         return resultType;
76839                     }
76840                     if (!resultType) {
76841                         // Types that have a reasonably good chance of being a valid operand type.
76842                         // If both types have an awaited type of one of these, we'll assume the user
76843                         // might be missing an await without doing an exhaustive check that inserting
76844                         // await(s) will actually be a completely valid binary expression.
76845                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
76846                         reportOperatorError(function (left, right) {
76847                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
76848                                 isTypeAssignableToKind(right, closeEnoughKind_1);
76849                         });
76850                         return anyType;
76851                     }
76852                     if (operator === 64 /* PlusEqualsToken */) {
76853                         checkAssignmentOperator(resultType);
76854                     }
76855                     return resultType;
76856                 case 29 /* LessThanToken */:
76857                 case 31 /* GreaterThanToken */:
76858                 case 32 /* LessThanEqualsToken */:
76859                 case 33 /* GreaterThanEqualsToken */:
76860                     if (checkForDisallowedESSymbolOperand(operator)) {
76861                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
76862                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
76863                         reportOperatorErrorUnless(function (left, right) {
76864                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
76865                         });
76866                     }
76867                     return booleanType;
76868                 case 34 /* EqualsEqualsToken */:
76869                 case 35 /* ExclamationEqualsToken */:
76870                 case 36 /* EqualsEqualsEqualsToken */:
76871                 case 37 /* ExclamationEqualsEqualsToken */:
76872                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
76873                     return booleanType;
76874                 case 102 /* InstanceOfKeyword */:
76875                     return checkInstanceOfExpression(left, right, leftType, rightType);
76876                 case 101 /* InKeyword */:
76877                     return checkInExpression(left, right, leftType, rightType);
76878                 case 55 /* AmpersandAmpersandToken */:
76879                 case 76 /* AmpersandAmpersandEqualsToken */: {
76880                     var resultType_2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ?
76881                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
76882                         leftType;
76883                     if (operator === 76 /* AmpersandAmpersandEqualsToken */) {
76884                         checkAssignmentOperator(rightType);
76885                     }
76886                     return resultType_2;
76887                 }
76888                 case 56 /* BarBarToken */:
76889                 case 75 /* BarBarEqualsToken */: {
76890                     var resultType_3 = getTypeFacts(leftType) & 8388608 /* Falsy */ ?
76891                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
76892                         leftType;
76893                     if (operator === 75 /* BarBarEqualsToken */) {
76894                         checkAssignmentOperator(rightType);
76895                     }
76896                     return resultType_3;
76897                 }
76898                 case 60 /* QuestionQuestionToken */:
76899                 case 77 /* QuestionQuestionEqualsToken */: {
76900                     var resultType_4 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
76901                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
76902                         leftType;
76903                     if (operator === 77 /* QuestionQuestionEqualsToken */) {
76904                         checkAssignmentOperator(rightType);
76905                     }
76906                     return resultType_4;
76907                 }
76908                 case 63 /* EqualsToken */:
76909                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
76910                     checkAssignmentDeclaration(declKind, rightType);
76911                     if (isAssignmentDeclaration(declKind)) {
76912                         if (!(rightType.flags & 524288 /* Object */) ||
76913                             declKind !== 2 /* ModuleExports */ &&
76914                                 declKind !== 6 /* Prototype */ &&
76915                                 !isEmptyObjectType(rightType) &&
76916                                 !isFunctionObjectType(rightType) &&
76917                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
76918                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
76919                             checkAssignmentOperator(rightType);
76920                         }
76921                         return leftType;
76922                     }
76923                     else {
76924                         checkAssignmentOperator(rightType);
76925                         return getRegularTypeOfObjectLiteral(rightType);
76926                     }
76927                 case 27 /* CommaToken */:
76928                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
76929                         var sf = ts.getSourceFileOfNode(left);
76930                         var sourceText = sf.text;
76931                         var start_3 = ts.skipTrivia(sourceText, left.pos);
76932                         var isInDiag2657 = sf.parseDiagnostics.some(function (diag) {
76933                             if (diag.code !== ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code)
76934                                 return false;
76935                             return ts.textSpanContainsPosition(diag, start_3);
76936                         });
76937                         if (!isInDiag2657)
76938                             error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
76939                     }
76940                     return rightType;
76941                 default:
76942                     return ts.Debug.fail();
76943             }
76944             function bothAreBigIntLike(left, right) {
76945                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
76946             }
76947             function checkAssignmentDeclaration(kind, rightType) {
76948                 if (kind === 2 /* ModuleExports */) {
76949                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
76950                         var prop = _a[_i];
76951                         var propType = getTypeOfSymbol(prop);
76952                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
76953                             var name = prop.escapedName;
76954                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
76955                             if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) {
76956                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
76957                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
76958                             }
76959                         }
76960                     }
76961                 }
76962             }
76963             function isEvalNode(node) {
76964                 return node.kind === 79 /* Identifier */ && node.escapedText === "eval";
76965             }
76966             // Return true if there was no error, false if there was an error.
76967             function checkForDisallowedESSymbolOperand(operator) {
76968                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
76969                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
76970                         undefined;
76971                 if (offendingSymbolOperand) {
76972                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
76973                     return false;
76974                 }
76975                 return true;
76976             }
76977             function getSuggestedBooleanOperator(operator) {
76978                 switch (operator) {
76979                     case 51 /* BarToken */:
76980                     case 74 /* BarEqualsToken */:
76981                         return 56 /* BarBarToken */;
76982                     case 52 /* CaretToken */:
76983                     case 78 /* CaretEqualsToken */:
76984                         return 37 /* ExclamationEqualsEqualsToken */;
76985                     case 50 /* AmpersandToken */:
76986                     case 73 /* AmpersandEqualsToken */:
76987                         return 55 /* AmpersandAmpersandToken */;
76988                     default:
76989                         return undefined;
76990                 }
76991             }
76992             function checkAssignmentOperator(valueType) {
76993                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
76994                     // TypeScript 1.0 spec (April 2014): 4.17
76995                     // An assignment of the form
76996                     //    VarExpr = ValueExpr
76997                     // requires VarExpr to be classified as a reference
76998                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
76999                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
77000                     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)
77001                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
77002                         var headMessage = void 0;
77003                         if (exactOptionalPropertyTypes && ts.isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, 32768 /* Undefined */)) {
77004                             var target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText);
77005                             if (isExactOptionalPropertyMismatch(valueType, target)) {
77006                                 headMessage = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target;
77007                             }
77008                         }
77009                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
77010                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right, headMessage);
77011                     }
77012                 }
77013             }
77014             function isAssignmentDeclaration(kind) {
77015                 var _a;
77016                 switch (kind) {
77017                     case 2 /* ModuleExports */:
77018                         return true;
77019                     case 1 /* ExportsProperty */:
77020                     case 5 /* Property */:
77021                     case 6 /* Prototype */:
77022                     case 3 /* PrototypeProperty */:
77023                     case 4 /* ThisProperty */:
77024                         var symbol = getSymbolOfNode(left);
77025                         var init = ts.getAssignedExpandoInitializer(right);
77026                         return !!init && ts.isObjectLiteralExpression(init) &&
77027                             !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
77028                     default:
77029                         return false;
77030                 }
77031             }
77032             /**
77033              * Returns true if an error is reported
77034              */
77035             function reportOperatorErrorUnless(typesAreCompatible) {
77036                 if (!typesAreCompatible(leftType, rightType)) {
77037                     reportOperatorError(typesAreCompatible);
77038                     return true;
77039                 }
77040                 return false;
77041             }
77042             function reportOperatorError(isRelated) {
77043                 var _a;
77044                 var wouldWorkWithAwait = false;
77045                 var errNode = errorNode || operatorToken;
77046                 if (isRelated) {
77047                     var awaitedLeftType = getAwaitedTypeNoAlias(leftType);
77048                     var awaitedRightType = getAwaitedTypeNoAlias(rightType);
77049                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
77050                         && !!(awaitedLeftType && awaitedRightType)
77051                         && isRelated(awaitedLeftType, awaitedRightType);
77052                 }
77053                 var effectiveLeft = leftType;
77054                 var effectiveRight = rightType;
77055                 if (!wouldWorkWithAwait && isRelated) {
77056                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
77057                 }
77058                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
77059                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
77060                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
77061                 }
77062             }
77063             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
77064                 var typeName;
77065                 switch (operatorToken.kind) {
77066                     case 36 /* EqualsEqualsEqualsToken */:
77067                     case 34 /* EqualsEqualsToken */:
77068                         typeName = "false";
77069                         break;
77070                     case 37 /* ExclamationEqualsEqualsToken */:
77071                     case 35 /* ExclamationEqualsToken */:
77072                         typeName = "true";
77073                 }
77074                 if (typeName) {
77075                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
77076                 }
77077                 return undefined;
77078             }
77079         }
77080         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
77081             var effectiveLeft = leftType;
77082             var effectiveRight = rightType;
77083             var leftBase = getBaseTypeOfLiteralType(leftType);
77084             var rightBase = getBaseTypeOfLiteralType(rightType);
77085             if (!isRelated(leftBase, rightBase)) {
77086                 effectiveLeft = leftBase;
77087                 effectiveRight = rightBase;
77088             }
77089             return [effectiveLeft, effectiveRight];
77090         }
77091         function checkYieldExpression(node) {
77092             // Grammar checking
77093             if (produceDiagnostics) {
77094                 if (!(node.flags & 8192 /* YieldContext */)) {
77095                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
77096                 }
77097                 if (isInParameterInitializerBeforeContainingFunction(node)) {
77098                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
77099                 }
77100             }
77101             var func = ts.getContainingFunction(node);
77102             if (!func)
77103                 return anyType;
77104             var functionFlags = ts.getFunctionFlags(func);
77105             if (!(functionFlags & 1 /* Generator */)) {
77106                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
77107                 return anyType;
77108             }
77109             var isAsync = (functionFlags & 2 /* Async */) !== 0;
77110             if (node.asteriskToken) {
77111                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
77112                 // and __asyncValues helpers
77113                 if (isAsync && languageVersion < 99 /* ESNext */) {
77114                     checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
77115                 }
77116                 // Generator functions prior to ES2015 require the __values helper
77117                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
77118                     checkExternalEmitHelpers(node, 256 /* Values */);
77119                 }
77120             }
77121             // There is no point in doing an assignability check if the function
77122             // has no explicit return type because the return type is directly computed
77123             // from the yield expressions.
77124             var returnType = getReturnTypeFromAnnotation(func);
77125             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
77126             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
77127             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
77128             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
77129             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
77130             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
77131             if (returnType && yieldedType) {
77132                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
77133             }
77134             if (node.asteriskToken) {
77135                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
77136                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
77137                     || anyType;
77138             }
77139             else if (returnType) {
77140                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
77141                     || anyType;
77142             }
77143             var type = getContextualIterationType(2 /* Next */, func);
77144             if (!type) {
77145                 type = anyType;
77146                 if (produceDiagnostics && noImplicitAny && !ts.expressionResultIsUnused(node)) {
77147                     var contextualType = getContextualType(node);
77148                     if (!contextualType || isTypeAny(contextualType)) {
77149                         error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation);
77150                     }
77151                 }
77152             }
77153             return type;
77154         }
77155         function checkConditionalExpression(node, checkMode) {
77156             var type = checkTruthinessExpression(node.condition);
77157             checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue);
77158             var type1 = checkExpression(node.whenTrue, checkMode);
77159             var type2 = checkExpression(node.whenFalse, checkMode);
77160             return getUnionType([type1, type2], 2 /* Subtype */);
77161         }
77162         function isTemplateLiteralContext(node) {
77163             var parent = node.parent;
77164             return ts.isParenthesizedExpression(parent) && isTemplateLiteralContext(parent) ||
77165                 ts.isElementAccessExpression(parent) && parent.argumentExpression === node;
77166         }
77167         function checkTemplateExpression(node) {
77168             var texts = [node.head.text];
77169             var types = [];
77170             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
77171                 var span = _a[_i];
77172                 var type = checkExpression(span.expression);
77173                 if (maybeTypeOfKind(type, 12288 /* ESSymbolLike */)) {
77174                     error(span.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
77175                 }
77176                 texts.push(span.literal.text);
77177                 types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
77178             }
77179             return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType;
77180         }
77181         function isTemplateLiteralContextualType(type) {
77182             return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) ||
77183                 type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */));
77184         }
77185         function getContextNode(node) {
77186             if (node.kind === 285 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
77187                 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)
77188             }
77189             return node;
77190         }
77191         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
77192             var context = getContextNode(node);
77193             var saveContextualType = context.contextualType;
77194             var saveInferenceContext = context.inferenceContext;
77195             try {
77196                 context.contextualType = contextualType;
77197                 context.inferenceContext = inferenceContext;
77198                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
77199                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
77200                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
77201                 // here would be to not mark contextually typed literals as fresh in the first place.
77202                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
77203                     getRegularTypeOfLiteralType(type) : type;
77204                 return result;
77205             }
77206             finally {
77207                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
77208                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
77209                 // may hold onto the checker that created it.
77210                 context.contextualType = saveContextualType;
77211                 context.inferenceContext = saveInferenceContext;
77212             }
77213         }
77214         function checkExpressionCached(node, checkMode) {
77215             var links = getNodeLinks(node);
77216             if (!links.resolvedType) {
77217                 if (checkMode && checkMode !== 0 /* Normal */) {
77218                     return checkExpression(node, checkMode);
77219                 }
77220                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
77221                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
77222                 // to the top of the stack ensures all transient types are computed from a known point.
77223                 var saveFlowLoopStart = flowLoopStart;
77224                 var saveFlowTypeCache = flowTypeCache;
77225                 flowLoopStart = flowLoopCount;
77226                 flowTypeCache = undefined;
77227                 links.resolvedType = checkExpression(node, checkMode);
77228                 flowTypeCache = saveFlowTypeCache;
77229                 flowLoopStart = saveFlowLoopStart;
77230             }
77231             return links.resolvedType;
77232         }
77233         function isTypeAssertion(node) {
77234             node = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true);
77235             return node.kind === 210 /* TypeAssertionExpression */ ||
77236                 node.kind === 228 /* AsExpression */ ||
77237                 ts.isJSDocTypeAssertion(node);
77238         }
77239         function checkDeclarationInitializer(declaration, contextualType) {
77240             var initializer = ts.getEffectiveInitializer(declaration);
77241             var type = getQuickTypeOfExpression(initializer) ||
77242                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
77243             return ts.isParameter(declaration) && declaration.name.kind === 201 /* ArrayBindingPattern */ &&
77244                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
77245                 padTupleType(type, declaration.name) : type;
77246         }
77247         function padTupleType(type, pattern) {
77248             var patternElements = pattern.elements;
77249             var elementTypes = getTypeArguments(type).slice();
77250             var elementFlags = type.target.elementFlags.slice();
77251             for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) {
77252                 var e = patternElements[i];
77253                 if (i < patternElements.length - 1 || !(e.kind === 202 /* BindingElement */ && e.dotDotDotToken)) {
77254                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
77255                     elementFlags.push(2 /* Optional */);
77256                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
77257                         reportImplicitAny(e, anyType);
77258                     }
77259                 }
77260             }
77261             return createTupleType(elementTypes, elementFlags, type.target.readonly);
77262         }
77263         function widenTypeInferredFromInitializer(declaration, type) {
77264             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
77265             if (ts.isInJSFile(declaration)) {
77266                 if (isEmptyLiteralType(widened)) {
77267                     reportImplicitAny(declaration, anyType);
77268                     return anyType;
77269                 }
77270                 else if (isEmptyArrayLiteralType(widened)) {
77271                     reportImplicitAny(declaration, anyArrayType);
77272                     return anyArrayType;
77273                 }
77274             }
77275             return widened;
77276         }
77277         function isLiteralOfContextualType(candidateType, contextualType) {
77278             if (contextualType) {
77279                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
77280                     var types = contextualType.types;
77281                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
77282                 }
77283                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
77284                     // If the contextual type is a type variable constrained to a primitive type, consider
77285                     // this a literal context for literals of that primitive type. For example, given a
77286                     // type parameter 'T extends string', infer string literal types for T.
77287                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
77288                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
77289                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
77290                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
77291                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
77292                         isLiteralOfContextualType(candidateType, constraint);
77293                 }
77294                 // If the contextual type is a literal of a particular primitive type, we consider this a
77295                 // literal context for all literals of that primitive type.
77296                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
77297                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
77298                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
77299                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
77300                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
77301             }
77302             return false;
77303         }
77304         function isConstContext(node) {
77305             var parent = node.parent;
77306             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
77307                 ts.isJSDocTypeAssertion(parent) && ts.isConstTypeReference(ts.getJSDocTypeAssertionType(parent)) ||
77308                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
77309                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isTemplateSpan(parent)) && isConstContext(parent.parent);
77310         }
77311         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
77312             var type = checkExpression(node, checkMode, forceTuple);
77313             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
77314                 isTypeAssertion(node) ? type :
77315                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
77316         }
77317         function checkPropertyAssignment(node, checkMode) {
77318             // Do not use hasDynamicName here, because that returns false for well known symbols.
77319             // We want to perform checkComputedPropertyName for all computed properties, including
77320             // well known symbols.
77321             if (node.name.kind === 161 /* ComputedPropertyName */) {
77322                 checkComputedPropertyName(node.name);
77323             }
77324             return checkExpressionForMutableLocation(node.initializer, checkMode);
77325         }
77326         function checkObjectLiteralMethod(node, checkMode) {
77327             // Grammar checking
77328             checkGrammarMethod(node);
77329             // Do not use hasDynamicName here, because that returns false for well known symbols.
77330             // We want to perform checkComputedPropertyName for all computed properties, including
77331             // well known symbols.
77332             if (node.name.kind === 161 /* ComputedPropertyName */) {
77333                 checkComputedPropertyName(node.name);
77334             }
77335             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
77336             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
77337         }
77338         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
77339             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
77340                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
77341                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
77342                 var signature = callSignature || constructSignature;
77343                 if (signature && signature.typeParameters) {
77344                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
77345                     if (contextualType) {
77346                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
77347                         if (contextualSignature && !contextualSignature.typeParameters) {
77348                             if (checkMode & 8 /* SkipGenericFunctions */) {
77349                                 skippedGenericFunction(node, checkMode);
77350                                 return anyFunctionType;
77351                             }
77352                             var context = getInferenceContext(node);
77353                             // We have an expression that is an argument of a generic function for which we are performing
77354                             // type argument inference. The expression is of a function type with a single generic call
77355                             // signature and a contextual function type with a single non-generic call signature. Now check
77356                             // if the outer function returns a function type with a single non-generic call signature and
77357                             // if some of the outer function type parameters have no inferences so far. If so, we can
77358                             // potentially add inferred type parameters to the outer function return type.
77359                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
77360                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
77361                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
77362                                 // Instantiate the signature with its own type parameters as type arguments, possibly
77363                                 // renaming the type parameters to ensure they have unique names.
77364                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
77365                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
77366                                 // Infer from the parameters of the instantiated signature to the parameters of the
77367                                 // contextual signature starting with an empty set of inference candidates.
77368                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
77369                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
77370                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
77371                                 });
77372                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
77373                                     // We have inference candidates, indicating that one or more type parameters are referenced
77374                                     // in the parameter types of the contextual signature. Now also infer from the return type.
77375                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
77376                                         inferTypes(inferences_3, source, target);
77377                                     });
77378                                     // If the type parameters for which we produced candidates do not have any inferences yet,
77379                                     // we adopt the new inference candidates and add the type parameters of the expression type
77380                                     // to the set of inferred type parameters for the outer function return type.
77381                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
77382                                         mergeInferences(context.inferences, inferences_3);
77383                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
77384                                         return getOrCreateTypeFromSignature(instantiatedSignature);
77385                                     }
77386                                 }
77387                             }
77388                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
77389                         }
77390                     }
77391                 }
77392             }
77393             return type;
77394         }
77395         function skippedGenericFunction(node, checkMode) {
77396             if (checkMode & 2 /* Inferential */) {
77397                 // We have skipped a generic function during inferential typing. Obtain the inference context and
77398                 // indicate this has occurred such that we know a second pass of inference is be needed.
77399                 var context = getInferenceContext(node);
77400                 context.flags |= 4 /* SkippedGenericFunction */;
77401             }
77402         }
77403         function hasInferenceCandidates(info) {
77404             return !!(info.candidates || info.contraCandidates);
77405         }
77406         function hasOverlappingInferences(a, b) {
77407             for (var i = 0; i < a.length; i++) {
77408                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
77409                     return true;
77410                 }
77411             }
77412             return false;
77413         }
77414         function mergeInferences(target, source) {
77415             for (var i = 0; i < target.length; i++) {
77416                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
77417                     target[i] = source[i];
77418                 }
77419             }
77420         }
77421         function getUniqueTypeParameters(context, typeParameters) {
77422             var result = [];
77423             var oldTypeParameters;
77424             var newTypeParameters;
77425             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
77426                 var tp = typeParameters_2[_i];
77427                 var name = tp.symbol.escapedName;
77428                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
77429                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
77430                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
77431                     var newTypeParameter = createTypeParameter(symbol);
77432                     newTypeParameter.target = tp;
77433                     oldTypeParameters = ts.append(oldTypeParameters, tp);
77434                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
77435                     result.push(newTypeParameter);
77436                 }
77437                 else {
77438                     result.push(tp);
77439                 }
77440             }
77441             if (newTypeParameters) {
77442                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
77443                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
77444                     var tp = newTypeParameters_1[_a];
77445                     tp.mapper = mapper;
77446                 }
77447             }
77448             return result;
77449         }
77450         function hasTypeParameterByName(typeParameters, name) {
77451             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
77452         }
77453         function getUniqueTypeParameterName(typeParameters, baseName) {
77454             var len = baseName.length;
77455             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
77456                 len--;
77457             var s = baseName.slice(0, len);
77458             for (var index = 1; true; index++) {
77459                 var augmentedName = s + index;
77460                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
77461                     return augmentedName;
77462                 }
77463             }
77464         }
77465         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
77466             var signature = getSingleCallSignature(funcType);
77467             if (signature && !signature.typeParameters) {
77468                 return getReturnTypeOfSignature(signature);
77469             }
77470         }
77471         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
77472             var funcType = checkExpression(expr.expression);
77473             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
77474             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
77475             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
77476         }
77477         /**
77478          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
77479          * with computing the type and may not fully check all contained sub-expressions for errors.
77480          */
77481         function getTypeOfExpression(node) {
77482             // Don't bother caching types that require no flow analysis and are quick to compute.
77483             var quickType = getQuickTypeOfExpression(node);
77484             if (quickType) {
77485                 return quickType;
77486             }
77487             // If a type has been cached for the node, return it.
77488             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
77489                 var cachedType = flowTypeCache[getNodeId(node)];
77490                 if (cachedType) {
77491                     return cachedType;
77492                 }
77493             }
77494             var startInvocationCount = flowInvocationCount;
77495             var type = checkExpression(node);
77496             // If control flow analysis was required to determine the type, it is worth caching.
77497             if (flowInvocationCount !== startInvocationCount) {
77498                 var cache = flowTypeCache || (flowTypeCache = []);
77499                 cache[getNodeId(node)] = type;
77500                 ts.setNodeFlags(node, node.flags | 67108864 /* TypeCached */);
77501             }
77502             return type;
77503         }
77504         function getQuickTypeOfExpression(node) {
77505             var expr = ts.skipParentheses(node, /*excludeJSDocTypeAssertions*/ true);
77506             if (ts.isJSDocTypeAssertion(expr)) {
77507                 var type = ts.getJSDocTypeAssertionType(expr);
77508                 if (!ts.isConstTypeReference(type)) {
77509                     return getTypeFromTypeNode(type);
77510                 }
77511             }
77512             expr = ts.skipParentheses(node);
77513             // Optimize for the common case of a call to a function with a single non-generic call
77514             // signature where we can just fetch the return type without checking the arguments.
77515             if (ts.isCallExpression(expr) && expr.expression.kind !== 106 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
77516                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
77517                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
77518                 if (type) {
77519                     return type;
77520                 }
77521             }
77522             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
77523                 return getTypeFromTypeNode(expr.type);
77524             }
77525             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
77526                 node.kind === 110 /* TrueKeyword */ || node.kind === 95 /* FalseKeyword */) {
77527                 return checkExpression(node);
77528             }
77529             return undefined;
77530         }
77531         /**
77532          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
77533          * with computing the type and may not fully check all contained sub-expressions for errors.
77534          * It is intended for uses where you know there is no contextual type,
77535          * and requesting the contextual type might cause a circularity or other bad behaviour.
77536          * It sets the contextual type of the node to any before calling getTypeOfExpression.
77537          */
77538         function getContextFreeTypeOfExpression(node) {
77539             var links = getNodeLinks(node);
77540             if (links.contextFreeType) {
77541                 return links.contextFreeType;
77542             }
77543             var saveContextualType = node.contextualType;
77544             node.contextualType = anyType;
77545             try {
77546                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
77547                 return type;
77548             }
77549             finally {
77550                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
77551                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
77552                 // may hold onto the checker that created it.
77553                 node.contextualType = saveContextualType;
77554             }
77555         }
77556         function checkExpression(node, checkMode, forceTuple) {
77557             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
77558             var saveCurrentNode = currentNode;
77559             currentNode = node;
77560             instantiationCount = 0;
77561             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
77562             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
77563             if (isConstEnumObjectType(type)) {
77564                 checkConstEnumAccess(node, type);
77565             }
77566             currentNode = saveCurrentNode;
77567             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
77568             return type;
77569         }
77570         function checkConstEnumAccess(node, type) {
77571             // enum object type for const enums are only permitted in:
77572             // - 'left' in property access
77573             // - 'object' in indexed access
77574             // - target in rhs of import statement
77575             var ok = (node.parent.kind === 205 /* PropertyAccessExpression */ && node.parent.expression === node) ||
77576                 (node.parent.kind === 206 /* ElementAccessExpression */ && node.parent.expression === node) ||
77577                 ((node.kind === 79 /* Identifier */ || node.kind === 160 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
77578                     (node.parent.kind === 180 /* TypeQuery */ && node.parent.exprName === node)) ||
77579                 (node.parent.kind === 274 /* ExportSpecifier */); // We allow reexporting const enums
77580             if (!ok) {
77581                 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);
77582             }
77583             if (compilerOptions.isolatedModules) {
77584                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
77585                 var constEnumDeclaration = type.symbol.valueDeclaration;
77586                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
77587                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
77588                 }
77589             }
77590         }
77591         function checkParenthesizedExpression(node, checkMode) {
77592             if (ts.hasJSDocNodes(node) && ts.isJSDocTypeAssertion(node)) {
77593                 var type = ts.getJSDocTypeAssertionType(node);
77594                 return checkAssertionWorker(type, type, node.expression, checkMode);
77595             }
77596             return checkExpression(node.expression, checkMode);
77597         }
77598         function checkExpressionWorker(node, checkMode, forceTuple) {
77599             var kind = node.kind;
77600             if (cancellationToken) {
77601                 // Only bother checking on a few construct kinds.  We don't want to be excessively
77602                 // hitting the cancellation token on every node we check.
77603                 switch (kind) {
77604                     case 225 /* ClassExpression */:
77605                     case 212 /* FunctionExpression */:
77606                     case 213 /* ArrowFunction */:
77607                         cancellationToken.throwIfCancellationRequested();
77608                 }
77609             }
77610             switch (kind) {
77611                 case 79 /* Identifier */:
77612                     return checkIdentifier(node, checkMode);
77613                 case 80 /* PrivateIdentifier */:
77614                     return checkPrivateIdentifierExpression(node);
77615                 case 108 /* ThisKeyword */:
77616                     return checkThisExpression(node);
77617                 case 106 /* SuperKeyword */:
77618                     return checkSuperExpression(node);
77619                 case 104 /* NullKeyword */:
77620                     return nullWideningType;
77621                 case 14 /* NoSubstitutionTemplateLiteral */:
77622                 case 10 /* StringLiteral */:
77623                     return getFreshTypeOfLiteralType(getStringLiteralType(node.text));
77624                 case 8 /* NumericLiteral */:
77625                     checkGrammarNumericLiteral(node);
77626                     return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text));
77627                 case 9 /* BigIntLiteral */:
77628                     checkGrammarBigIntLiteral(node);
77629                     return getFreshTypeOfLiteralType(getBigIntLiteralType({
77630                         negative: false,
77631                         base10Value: ts.parsePseudoBigInt(node.text)
77632                     }));
77633                 case 110 /* TrueKeyword */:
77634                     return trueType;
77635                 case 95 /* FalseKeyword */:
77636                     return falseType;
77637                 case 222 /* TemplateExpression */:
77638                     return checkTemplateExpression(node);
77639                 case 13 /* RegularExpressionLiteral */:
77640                     return globalRegExpType;
77641                 case 203 /* ArrayLiteralExpression */:
77642                     return checkArrayLiteral(node, checkMode, forceTuple);
77643                 case 204 /* ObjectLiteralExpression */:
77644                     return checkObjectLiteral(node, checkMode);
77645                 case 205 /* PropertyAccessExpression */:
77646                     return checkPropertyAccessExpression(node, checkMode);
77647                 case 160 /* QualifiedName */:
77648                     return checkQualifiedName(node, checkMode);
77649                 case 206 /* ElementAccessExpression */:
77650                     return checkIndexedAccess(node, checkMode);
77651                 case 207 /* CallExpression */:
77652                     if (node.expression.kind === 100 /* ImportKeyword */) {
77653                         return checkImportCallExpression(node);
77654                     }
77655                 // falls through
77656                 case 208 /* NewExpression */:
77657                     return checkCallExpression(node, checkMode);
77658                 case 209 /* TaggedTemplateExpression */:
77659                     return checkTaggedTemplateExpression(node);
77660                 case 211 /* ParenthesizedExpression */:
77661                     return checkParenthesizedExpression(node, checkMode);
77662                 case 225 /* ClassExpression */:
77663                     return checkClassExpression(node);
77664                 case 212 /* FunctionExpression */:
77665                 case 213 /* ArrowFunction */:
77666                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
77667                 case 215 /* TypeOfExpression */:
77668                     return checkTypeOfExpression(node);
77669                 case 210 /* TypeAssertionExpression */:
77670                 case 228 /* AsExpression */:
77671                     return checkAssertion(node);
77672                 case 229 /* NonNullExpression */:
77673                     return checkNonNullAssertion(node);
77674                 case 230 /* MetaProperty */:
77675                     return checkMetaProperty(node);
77676                 case 214 /* DeleteExpression */:
77677                     return checkDeleteExpression(node);
77678                 case 216 /* VoidExpression */:
77679                     return checkVoidExpression(node);
77680                 case 217 /* AwaitExpression */:
77681                     return checkAwaitExpression(node);
77682                 case 218 /* PrefixUnaryExpression */:
77683                     return checkPrefixUnaryExpression(node);
77684                 case 219 /* PostfixUnaryExpression */:
77685                     return checkPostfixUnaryExpression(node);
77686                 case 220 /* BinaryExpression */:
77687                     return checkBinaryExpression(node, checkMode);
77688                 case 221 /* ConditionalExpression */:
77689                     return checkConditionalExpression(node, checkMode);
77690                 case 224 /* SpreadElement */:
77691                     return checkSpreadExpression(node, checkMode);
77692                 case 226 /* OmittedExpression */:
77693                     return undefinedWideningType;
77694                 case 223 /* YieldExpression */:
77695                     return checkYieldExpression(node);
77696                 case 231 /* SyntheticExpression */:
77697                     return checkSyntheticExpression(node);
77698                 case 287 /* JsxExpression */:
77699                     return checkJsxExpression(node, checkMode);
77700                 case 277 /* JsxElement */:
77701                     return checkJsxElement(node, checkMode);
77702                 case 278 /* JsxSelfClosingElement */:
77703                     return checkJsxSelfClosingElement(node, checkMode);
77704                 case 281 /* JsxFragment */:
77705                     return checkJsxFragment(node);
77706                 case 285 /* JsxAttributes */:
77707                     return checkJsxAttributes(node, checkMode);
77708                 case 279 /* JsxOpeningElement */:
77709                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
77710             }
77711             return errorType;
77712         }
77713         // DECLARATION AND STATEMENT TYPE CHECKING
77714         function checkTypeParameter(node) {
77715             // Grammar Checking
77716             if (node.expression) {
77717                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
77718             }
77719             checkSourceElement(node.constraint);
77720             checkSourceElement(node.default);
77721             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
77722             // Resolve base constraint to reveal circularity errors
77723             getBaseConstraintOfType(typeParameter);
77724             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
77725                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
77726             }
77727             var constraintType = getConstraintOfTypeParameter(typeParameter);
77728             var defaultType = getDefaultFromTypeParameter(typeParameter);
77729             if (constraintType && defaultType) {
77730                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
77731             }
77732             if (produceDiagnostics) {
77733                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
77734             }
77735         }
77736         function checkParameter(node) {
77737             // Grammar checking
77738             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
77739             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
77740             // or if its FunctionBody is strict code(11.1.5).
77741             checkGrammarDecoratorsAndModifiers(node);
77742             checkVariableLikeDeclaration(node);
77743             var func = ts.getContainingFunction(node);
77744             if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) {
77745                 if (!(func.kind === 170 /* Constructor */ && ts.nodeIsPresent(func.body))) {
77746                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
77747                 }
77748                 if (func.kind === 170 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
77749                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
77750                 }
77751             }
77752             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
77753                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
77754             }
77755             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
77756                 if (func.parameters.indexOf(node) !== 0) {
77757                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
77758                 }
77759                 if (func.kind === 170 /* Constructor */ || func.kind === 174 /* ConstructSignature */ || func.kind === 179 /* ConstructorType */) {
77760                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
77761                 }
77762                 if (func.kind === 213 /* ArrowFunction */) {
77763                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
77764                 }
77765                 if (func.kind === 171 /* GetAccessor */ || func.kind === 172 /* SetAccessor */) {
77766                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
77767                 }
77768             }
77769             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
77770             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
77771             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
77772                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
77773             }
77774         }
77775         function checkTypePredicate(node) {
77776             var parent = getTypePredicateParent(node);
77777             if (!parent) {
77778                 // The parent must not be valid.
77779                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
77780                 return;
77781             }
77782             var signature = getSignatureFromDeclaration(parent);
77783             var typePredicate = getTypePredicateOfSignature(signature);
77784             if (!typePredicate) {
77785                 return;
77786             }
77787             checkSourceElement(node.type);
77788             var parameterName = node.parameterName;
77789             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
77790                 getTypeFromThisTypeNode(parameterName);
77791             }
77792             else {
77793                 if (typePredicate.parameterIndex >= 0) {
77794                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
77795                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
77796                     }
77797                     else {
77798                         if (typePredicate.type) {
77799                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
77800                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
77801                             /*headMessage*/ undefined, leadingError);
77802                         }
77803                     }
77804                 }
77805                 else if (parameterName) {
77806                     var hasReportedError = false;
77807                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
77808                         var name = _a[_i].name;
77809                         if (ts.isBindingPattern(name) &&
77810                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
77811                             hasReportedError = true;
77812                             break;
77813                         }
77814                     }
77815                     if (!hasReportedError) {
77816                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
77817                     }
77818                 }
77819             }
77820         }
77821         function getTypePredicateParent(node) {
77822             switch (node.parent.kind) {
77823                 case 213 /* ArrowFunction */:
77824                 case 173 /* CallSignature */:
77825                 case 255 /* FunctionDeclaration */:
77826                 case 212 /* FunctionExpression */:
77827                 case 178 /* FunctionType */:
77828                 case 168 /* MethodDeclaration */:
77829                 case 167 /* MethodSignature */:
77830                     var parent = node.parent;
77831                     if (node === parent.type) {
77832                         return parent;
77833                     }
77834             }
77835         }
77836         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
77837             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
77838                 var element = _a[_i];
77839                 if (ts.isOmittedExpression(element)) {
77840                     continue;
77841                 }
77842                 var name = element.name;
77843                 if (name.kind === 79 /* Identifier */ && name.escapedText === predicateVariableName) {
77844                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
77845                     return true;
77846                 }
77847                 else if (name.kind === 201 /* ArrayBindingPattern */ || name.kind === 200 /* ObjectBindingPattern */) {
77848                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
77849                         return true;
77850                     }
77851                 }
77852             }
77853         }
77854         function checkSignatureDeclaration(node) {
77855             // Grammar checking
77856             if (node.kind === 175 /* IndexSignature */) {
77857                 checkGrammarIndexSignature(node);
77858             }
77859             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
77860             else if (node.kind === 178 /* FunctionType */ || node.kind === 255 /* FunctionDeclaration */ || node.kind === 179 /* ConstructorType */ ||
77861                 node.kind === 173 /* CallSignature */ || node.kind === 170 /* Constructor */ ||
77862                 node.kind === 174 /* ConstructSignature */) {
77863                 checkGrammarFunctionLikeDeclaration(node);
77864             }
77865             var functionFlags = ts.getFunctionFlags(node);
77866             if (!(functionFlags & 4 /* Invalid */)) {
77867                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
77868                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
77869                     checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
77870                 }
77871                 // Async functions prior to ES2017 require the __awaiter helper
77872                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
77873                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
77874                 }
77875                 // Generator functions, Async functions, and Async Generator functions prior to
77876                 // ES2015 require the __generator helper
77877                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
77878                     checkExternalEmitHelpers(node, 128 /* Generator */);
77879                 }
77880             }
77881             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
77882             ts.forEach(node.parameters, checkParameter);
77883             // TODO(rbuckton): Should we start checking JSDoc types?
77884             if (node.type) {
77885                 checkSourceElement(node.type);
77886             }
77887             if (produceDiagnostics) {
77888                 checkCollisionWithArgumentsInGeneratedCode(node);
77889                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
77890                 if (noImplicitAny && !returnTypeNode) {
77891                     switch (node.kind) {
77892                         case 174 /* ConstructSignature */:
77893                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
77894                             break;
77895                         case 173 /* CallSignature */:
77896                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
77897                             break;
77898                     }
77899                 }
77900                 if (returnTypeNode) {
77901                     var functionFlags_1 = ts.getFunctionFlags(node);
77902                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
77903                         var returnType = getTypeFromTypeNode(returnTypeNode);
77904                         if (returnType === voidType) {
77905                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
77906                         }
77907                         else {
77908                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
77909                             // However, that would not catch the error in the following case.
77910                             //
77911                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
77912                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
77913                             //
77914                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
77915                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
77916                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
77917                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
77918                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
77919                         }
77920                     }
77921                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
77922                         checkAsyncFunctionReturnType(node, returnTypeNode);
77923                     }
77924                 }
77925                 if (node.kind !== 175 /* IndexSignature */ && node.kind !== 315 /* JSDocFunctionType */) {
77926                     registerForUnusedIdentifiersCheck(node);
77927                 }
77928             }
77929         }
77930         function checkClassForDuplicateDeclarations(node) {
77931             var instanceNames = new ts.Map();
77932             var staticNames = new ts.Map();
77933             // instance and static private identifiers share the same scope
77934             var privateIdentifiers = new ts.Map();
77935             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
77936                 var member = _a[_i];
77937                 if (member.kind === 170 /* Constructor */) {
77938                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
77939                         var param = _c[_b];
77940                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
77941                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
77942                         }
77943                     }
77944                 }
77945                 else {
77946                     var isStaticMember = ts.isStatic(member);
77947                     var name = member.name;
77948                     if (!name) {
77949                         continue;
77950                     }
77951                     var isPrivate = ts.isPrivateIdentifier(name);
77952                     var privateStaticFlags = isPrivate && isStaticMember ? 16 /* PrivateStatic */ : 0;
77953                     var names = isPrivate ? privateIdentifiers :
77954                         isStaticMember ? staticNames :
77955                             instanceNames;
77956                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
77957                     if (memberName) {
77958                         switch (member.kind) {
77959                             case 171 /* GetAccessor */:
77960                                 addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags);
77961                                 break;
77962                             case 172 /* SetAccessor */:
77963                                 addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags);
77964                                 break;
77965                             case 166 /* PropertyDeclaration */:
77966                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags);
77967                                 break;
77968                             case 168 /* MethodDeclaration */:
77969                                 addName(names, name, memberName, 8 /* Method */ | privateStaticFlags);
77970                                 break;
77971                         }
77972                     }
77973                 }
77974             }
77975             function addName(names, location, name, meaning) {
77976                 var prev = names.get(name);
77977                 if (prev) {
77978                     // For private identifiers, do not allow mixing of static and instance members with the same name
77979                     if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) {
77980                         error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location));
77981                     }
77982                     else {
77983                         var prevIsMethod = !!(prev & 8 /* Method */);
77984                         var isMethod = !!(meaning & 8 /* Method */);
77985                         if (prevIsMethod || isMethod) {
77986                             if (prevIsMethod !== isMethod) {
77987                                 error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
77988                             }
77989                             // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered
77990                         }
77991                         else if (prev & meaning & ~16 /* PrivateStatic */) {
77992                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
77993                         }
77994                         else {
77995                             names.set(name, prev | meaning);
77996                         }
77997                     }
77998                 }
77999                 else {
78000                     names.set(name, meaning);
78001                 }
78002             }
78003         }
78004         /**
78005          * Static members being set on a constructor function may conflict with built-in properties
78006          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
78007          * built-in properties. This check issues a transpile error when a class has a static
78008          * member with the same name as a non-writable built-in property.
78009          *
78010          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
78011          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
78012          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
78013          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
78014          */
78015         function checkClassForStaticPropertyNameConflicts(node) {
78016             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
78017                 var member = _a[_i];
78018                 var memberNameNode = member.name;
78019                 var isStaticMember = ts.isStatic(member);
78020                 if (isStaticMember && memberNameNode) {
78021                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
78022                     switch (memberName) {
78023                         case "name":
78024                         case "length":
78025                         case "caller":
78026                         case "arguments":
78027                         case "prototype":
78028                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
78029                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
78030                             error(memberNameNode, message, memberName, className);
78031                             break;
78032                     }
78033                 }
78034             }
78035         }
78036         function checkObjectTypeForDuplicateDeclarations(node) {
78037             var names = new ts.Map();
78038             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
78039                 var member = _a[_i];
78040                 if (member.kind === 165 /* PropertySignature */) {
78041                     var memberName = void 0;
78042                     var name = member.name;
78043                     switch (name.kind) {
78044                         case 10 /* StringLiteral */:
78045                         case 8 /* NumericLiteral */:
78046                             memberName = name.text;
78047                             break;
78048                         case 79 /* Identifier */:
78049                             memberName = ts.idText(name);
78050                             break;
78051                         default:
78052                             continue;
78053                     }
78054                     if (names.get(memberName)) {
78055                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
78056                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
78057                     }
78058                     else {
78059                         names.set(memberName, true);
78060                     }
78061                 }
78062             }
78063         }
78064         function checkTypeForDuplicateIndexSignatures(node) {
78065             if (node.kind === 257 /* InterfaceDeclaration */) {
78066                 var nodeSymbol = getSymbolOfNode(node);
78067                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
78068                 // to prevent this run check only for the first declaration of a given kind
78069                 if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
78070                     return;
78071                 }
78072             }
78073             // TypeScript 1.0 spec (April 2014)
78074             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
78075             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
78076             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
78077             if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) {
78078                 var indexSignatureMap_1 = new ts.Map();
78079                 var _loop_26 = function (declaration) {
78080                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
78081                         forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) {
78082                             var entry = indexSignatureMap_1.get(getTypeId(type));
78083                             if (entry) {
78084                                 entry.declarations.push(declaration);
78085                             }
78086                             else {
78087                                 indexSignatureMap_1.set(getTypeId(type), { type: type, declarations: [declaration] });
78088                             }
78089                         });
78090                     }
78091                 };
78092                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
78093                     var declaration = _a[_i];
78094                     _loop_26(declaration);
78095                 }
78096                 indexSignatureMap_1.forEach(function (entry) {
78097                     if (entry.declarations.length > 1) {
78098                         for (var _i = 0, _a = entry.declarations; _i < _a.length; _i++) {
78099                             var declaration = _a[_i];
78100                             error(declaration, ts.Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type));
78101                         }
78102                     }
78103                 });
78104             }
78105         }
78106         function checkPropertyDeclaration(node) {
78107             // Grammar checking
78108             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
78109                 checkGrammarComputedPropertyName(node.name);
78110             checkVariableLikeDeclaration(node);
78111             setNodeLinksForPrivateIdentifierScope(node);
78112             if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) {
78113                 error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag);
78114             }
78115             // property signatures already report "initializer not allowed in ambient context" elsewhere
78116             if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* PropertyDeclaration */ && node.initializer) {
78117                 error(node, ts.Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
78118             }
78119         }
78120         function checkPropertySignature(node) {
78121             if (ts.isPrivateIdentifier(node.name)) {
78122                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
78123             }
78124             return checkPropertyDeclaration(node);
78125         }
78126         function checkMethodDeclaration(node) {
78127             // Grammar checking
78128             if (!checkGrammarMethod(node))
78129                 checkGrammarComputedPropertyName(node.name);
78130             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
78131             checkFunctionOrMethodDeclaration(node);
78132             // method signatures already report "implementation not allowed in ambient context" elsewhere
78133             if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 168 /* MethodDeclaration */ && node.body) {
78134                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
78135             }
78136             // Private named methods are only allowed in class declarations
78137             if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) {
78138                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
78139             }
78140             setNodeLinksForPrivateIdentifierScope(node);
78141         }
78142         function setNodeLinksForPrivateIdentifierScope(node) {
78143             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
78144                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
78145                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
78146                 }
78147                 // If this is a private element in a class expression inside the body of a loop,
78148                 // then we must use a block-scoped binding to store the additional variables required
78149                 // to transform private elements.
78150                 if (ts.isClassExpression(node.parent)) {
78151                     var enclosingIterationStatement = getEnclosingIterationStatement(node.parent);
78152                     if (enclosingIterationStatement) {
78153                         getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */;
78154                         getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
78155                     }
78156                 }
78157             }
78158         }
78159         function checkClassStaticBlockDeclaration(node) {
78160             checkGrammarDecoratorsAndModifiers(node);
78161             ts.forEachChild(node, checkSourceElement);
78162         }
78163         function checkConstructorDeclaration(node) {
78164             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
78165             checkSignatureDeclaration(node);
78166             // Grammar check for checking only related to constructorDeclaration
78167             if (!checkGrammarConstructorTypeParameters(node))
78168                 checkGrammarConstructorTypeAnnotation(node);
78169             checkSourceElement(node.body);
78170             var symbol = getSymbolOfNode(node);
78171             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
78172             // Only type check the symbol once
78173             if (node === firstDeclaration) {
78174                 checkFunctionOrConstructorSymbol(symbol);
78175             }
78176             // exit early in the case of signature - super checks are not relevant to them
78177             if (ts.nodeIsMissing(node.body)) {
78178                 return;
78179             }
78180             if (!produceDiagnostics) {
78181                 return;
78182             }
78183             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
78184                 if (ts.isPrivateIdentifierClassElementDeclaration(n)) {
78185                     return true;
78186                 }
78187                 return n.kind === 166 /* PropertyDeclaration */ &&
78188                     !ts.isStatic(n) &&
78189                     !!n.initializer;
78190             }
78191             // TS 1.0 spec (April 2014): 8.3.2
78192             // Constructors of classes with no extends clause may not contain super calls, whereas
78193             // constructors of derived classes must contain at least one super call somewhere in their function body.
78194             var containingClassDecl = node.parent;
78195             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
78196                 captureLexicalThis(node.parent, containingClassDecl);
78197                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
78198                 var superCall = findFirstSuperCall(node.body);
78199                 if (superCall) {
78200                     if (classExtendsNull) {
78201                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
78202                     }
78203                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
78204                     // if both of the following are true:
78205                     // - The containing class is a derived class.
78206                     // - The constructor declares parameter properties
78207                     //   or the containing class declares instance member variables with initializers.
78208                     var superCallShouldBeFirst = (ts.getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) &&
78209                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
78210                             ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); }));
78211                     // Skip past any prologue directives to find the first statement
78212                     // to ensure that it was a super call.
78213                     if (superCallShouldBeFirst) {
78214                         var statements = node.body.statements;
78215                         var superCallStatement = void 0;
78216                         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
78217                             var statement = statements_4[_i];
78218                             if (statement.kind === 237 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
78219                                 superCallStatement = statement;
78220                                 break;
78221                             }
78222                             if (!ts.isPrologueDirective(statement)) {
78223                                 break;
78224                             }
78225                         }
78226                         if (!superCallStatement) {
78227                             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);
78228                         }
78229                     }
78230                 }
78231                 else if (!classExtendsNull) {
78232                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
78233                 }
78234             }
78235         }
78236         function checkAccessorDeclaration(node) {
78237             if (produceDiagnostics) {
78238                 // Grammar checking accessors
78239                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
78240                     checkGrammarComputedPropertyName(node.name);
78241                 checkDecorators(node);
78242                 checkSignatureDeclaration(node);
78243                 if (node.kind === 171 /* GetAccessor */) {
78244                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
78245                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
78246                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
78247                         }
78248                     }
78249                 }
78250                 // Do not use hasDynamicName here, because that returns false for well known symbols.
78251                 // We want to perform checkComputedPropertyName for all computed properties, including
78252                 // well known symbols.
78253                 if (node.name.kind === 161 /* ComputedPropertyName */) {
78254                     checkComputedPropertyName(node.name);
78255                 }
78256                 if (hasBindableName(node)) {
78257                     // TypeScript 1.0 spec (April 2014): 8.4.3
78258                     // Accessors for the same member name must specify the same accessibility.
78259                     var symbol = getSymbolOfNode(node);
78260                     var getter = ts.getDeclarationOfKind(symbol, 171 /* GetAccessor */);
78261                     var setter = ts.getDeclarationOfKind(symbol, 172 /* SetAccessor */);
78262                     if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) {
78263                         getNodeLinks(getter).flags |= 1 /* TypeChecked */;
78264                         var getterFlags = ts.getEffectiveModifierFlags(getter);
78265                         var setterFlags = ts.getEffectiveModifierFlags(setter);
78266                         if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) {
78267                             error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
78268                             error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
78269                         }
78270                         if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) ||
78271                             ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) {
78272                             error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
78273                             error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
78274                         }
78275                         var getterType = getAnnotatedAccessorType(getter);
78276                         var setterType = getAnnotatedAccessorType(setter);
78277                         if (getterType && setterType) {
78278                             checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type);
78279                         }
78280                     }
78281                 }
78282                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
78283                 if (node.kind === 171 /* GetAccessor */) {
78284                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
78285                 }
78286             }
78287             checkSourceElement(node.body);
78288             setNodeLinksForPrivateIdentifierScope(node);
78289         }
78290         function checkMissingDeclaration(node) {
78291             checkDecorators(node);
78292         }
78293         function getEffectiveTypeArguments(node, typeParameters) {
78294             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
78295         }
78296         function checkTypeArgumentConstraints(node, typeParameters) {
78297             var typeArguments;
78298             var mapper;
78299             var result = true;
78300             for (var i = 0; i < typeParameters.length; i++) {
78301                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
78302                 if (constraint) {
78303                     if (!typeArguments) {
78304                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
78305                         mapper = createTypeMapper(typeParameters, typeArguments);
78306                     }
78307                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
78308                 }
78309             }
78310             return result;
78311         }
78312         function getTypeParametersForTypeReference(node) {
78313             var type = getTypeFromTypeReference(node);
78314             if (!isErrorType(type)) {
78315                 var symbol = getNodeLinks(node).resolvedSymbol;
78316                 if (symbol) {
78317                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
78318                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
78319                 }
78320             }
78321             return undefined;
78322         }
78323         function checkTypeReferenceNode(node) {
78324             checkGrammarTypeArguments(node, node.typeArguments);
78325             if (node.kind === 177 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
78326                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
78327             }
78328             ts.forEach(node.typeArguments, checkSourceElement);
78329             var type = getTypeFromTypeReference(node);
78330             if (!isErrorType(type)) {
78331                 if (node.typeArguments && produceDiagnostics) {
78332                     var typeParameters = getTypeParametersForTypeReference(node);
78333                     if (typeParameters) {
78334                         checkTypeArgumentConstraints(node, typeParameters);
78335                     }
78336                 }
78337                 var symbol = getNodeLinks(node).resolvedSymbol;
78338                 if (symbol) {
78339                     if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
78340                         addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName);
78341                     }
78342                     if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
78343                         error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
78344                     }
78345                 }
78346             }
78347         }
78348         function getTypeArgumentConstraint(node) {
78349             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
78350             if (!typeReferenceNode)
78351                 return undefined;
78352             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode);
78353             if (!typeParameters)
78354                 return undefined;
78355             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
78356             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
78357         }
78358         function checkTypeQuery(node) {
78359             getTypeFromTypeQueryNode(node);
78360         }
78361         function checkTypeLiteral(node) {
78362             ts.forEach(node.members, checkSourceElement);
78363             if (produceDiagnostics) {
78364                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
78365                 checkIndexConstraints(type, type.symbol);
78366                 checkTypeForDuplicateIndexSignatures(node);
78367                 checkObjectTypeForDuplicateDeclarations(node);
78368             }
78369         }
78370         function checkArrayType(node) {
78371             checkSourceElement(node.elementType);
78372         }
78373         function checkTupleType(node) {
78374             var elementTypes = node.elements;
78375             var seenOptionalElement = false;
78376             var seenRestElement = false;
78377             var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
78378             for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) {
78379                 var e = elementTypes_1[_i];
78380                 if (e.kind !== 196 /* NamedTupleMember */ && hasNamedElement) {
78381                     grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
78382                     break;
78383                 }
78384                 var flags = getTupleElementFlags(e);
78385                 if (flags & 8 /* Variadic */) {
78386                     var type = getTypeFromTypeNode(e.type);
78387                     if (!isArrayLikeType(type)) {
78388                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
78389                         break;
78390                     }
78391                     if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) {
78392                         seenRestElement = true;
78393                     }
78394                 }
78395                 else if (flags & 4 /* Rest */) {
78396                     if (seenRestElement) {
78397                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_cannot_follow_another_rest_element);
78398                         break;
78399                     }
78400                     seenRestElement = true;
78401                 }
78402                 else if (flags & 2 /* Optional */) {
78403                     if (seenRestElement) {
78404                         grammarErrorOnNode(e, ts.Diagnostics.An_optional_element_cannot_follow_a_rest_element);
78405                         break;
78406                     }
78407                     seenOptionalElement = true;
78408                 }
78409                 else if (seenOptionalElement) {
78410                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
78411                     break;
78412                 }
78413             }
78414             ts.forEach(node.elements, checkSourceElement);
78415             getTypeFromTypeNode(node);
78416         }
78417         function checkUnionOrIntersectionType(node) {
78418             ts.forEach(node.types, checkSourceElement);
78419             getTypeFromTypeNode(node);
78420         }
78421         function checkIndexedAccessIndexType(type, accessNode) {
78422             if (!(type.flags & 8388608 /* IndexedAccess */)) {
78423                 return type;
78424             }
78425             // Check if the index type is assignable to 'keyof T' for the object type.
78426             var objectType = type.objectType;
78427             var indexType = type.indexType;
78428             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
78429                 if (accessNode.kind === 206 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
78430                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
78431                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
78432                 }
78433                 return type;
78434             }
78435             // Check if we're indexing with a numeric type and if either object or index types
78436             // is a generic type with a constraint that has a numeric index signature.
78437             var apparentObjectType = getApparentType(objectType);
78438             if (getIndexInfoOfType(apparentObjectType, numberType) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
78439                 return type;
78440             }
78441             if (isGenericObjectType(objectType)) {
78442                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
78443                 if (propertyName_1) {
78444                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
78445                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
78446                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
78447                         return errorType;
78448                     }
78449                 }
78450             }
78451             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
78452             return errorType;
78453         }
78454         function checkIndexedAccessType(node) {
78455             checkSourceElement(node.objectType);
78456             checkSourceElement(node.indexType);
78457             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
78458         }
78459         function checkMappedType(node) {
78460             checkGrammarMappedType(node);
78461             checkSourceElement(node.typeParameter);
78462             checkSourceElement(node.nameType);
78463             checkSourceElement(node.type);
78464             if (!node.type) {
78465                 reportImplicitAny(node, anyType);
78466             }
78467             var type = getTypeFromMappedTypeNode(node);
78468             var nameType = getNameTypeFromMappedType(type);
78469             if (nameType) {
78470                 checkTypeAssignableTo(nameType, keyofConstraintType, node.nameType);
78471             }
78472             else {
78473                 var constraintType = getConstraintTypeFromMappedType(type);
78474                 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
78475             }
78476         }
78477         function checkGrammarMappedType(node) {
78478             var _a;
78479             if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) {
78480                 return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
78481             }
78482         }
78483         function checkThisType(node) {
78484             getTypeFromThisTypeNode(node);
78485         }
78486         function checkTypeOperator(node) {
78487             checkGrammarTypeOperatorNode(node);
78488             checkSourceElement(node.type);
78489         }
78490         function checkConditionalType(node) {
78491             ts.forEachChild(node, checkSourceElement);
78492         }
78493         function checkInferType(node) {
78494             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 188 /* ConditionalType */ && n.parent.extendsType === n; })) {
78495                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
78496             }
78497             checkSourceElement(node.typeParameter);
78498             registerForUnusedIdentifiersCheck(node);
78499         }
78500         function checkTemplateLiteralType(node) {
78501             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
78502                 var span = _a[_i];
78503                 checkSourceElement(span.type);
78504                 var type = getTypeFromTypeNode(span.type);
78505                 checkTypeAssignableTo(type, templateConstraintType, span.type);
78506             }
78507             getTypeFromTypeNode(node);
78508         }
78509         function checkImportType(node) {
78510             checkSourceElement(node.argument);
78511             getTypeFromTypeNode(node);
78512         }
78513         function checkNamedTupleMember(node) {
78514             if (node.dotDotDotToken && node.questionToken) {
78515                 grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
78516             }
78517             if (node.type.kind === 184 /* OptionalType */) {
78518                 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);
78519             }
78520             if (node.type.kind === 185 /* RestType */) {
78521                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
78522             }
78523             checkSourceElement(node.type);
78524             getTypeFromTypeNode(node);
78525         }
78526         function isPrivateWithinAmbient(node) {
78527             return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
78528         }
78529         function getEffectiveDeclarationFlags(n, flagsToCheck) {
78530             var flags = ts.getCombinedModifierFlags(n);
78531             // children of classes (even ambient classes) should not be marked as ambient or export
78532             // because those flags have no useful semantics there.
78533             if (n.parent.kind !== 257 /* InterfaceDeclaration */ &&
78534                 n.parent.kind !== 256 /* ClassDeclaration */ &&
78535                 n.parent.kind !== 225 /* ClassExpression */ &&
78536                 n.flags & 8388608 /* Ambient */) {
78537                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
78538                     // It is nested in an ambient context, which means it is automatically exported
78539                     flags |= 1 /* Export */;
78540                 }
78541                 flags |= 2 /* Ambient */;
78542             }
78543             return flags & flagsToCheck;
78544         }
78545         function checkFunctionOrConstructorSymbol(symbol) {
78546             if (!produceDiagnostics) {
78547                 return;
78548             }
78549             function getCanonicalOverload(overloads, implementation) {
78550                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
78551                 // Error on all deviations from this canonical set of flags
78552                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
78553                 // report the errors on those. To achieve this, we will say that the implementation is
78554                 // the canonical signature only if it is in the same container as the first overload
78555                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
78556                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
78557             }
78558             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
78559                 // Error if some overloads have a flag that is not shared by all overloads. To find the
78560                 // deviations, we XOR someOverloadFlags with allOverloadFlags
78561                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
78562                 if (someButNotAllOverloadFlags !== 0) {
78563                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
78564                     ts.forEach(overloads, function (o) {
78565                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
78566                         if (deviation & 1 /* Export */) {
78567                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
78568                         }
78569                         else if (deviation & 2 /* Ambient */) {
78570                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
78571                         }
78572                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
78573                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
78574                         }
78575                         else if (deviation & 128 /* Abstract */) {
78576                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
78577                         }
78578                     });
78579                 }
78580             }
78581             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
78582                 if (someHaveQuestionToken !== allHaveQuestionToken) {
78583                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
78584                     ts.forEach(overloads, function (o) {
78585                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
78586                         if (deviation) {
78587                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
78588                         }
78589                     });
78590                 }
78591             }
78592             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
78593             var someNodeFlags = 0 /* None */;
78594             var allNodeFlags = flagsToCheck;
78595             var someHaveQuestionToken = false;
78596             var allHaveQuestionToken = true;
78597             var hasOverloads = false;
78598             var bodyDeclaration;
78599             var lastSeenNonAmbientDeclaration;
78600             var previousDeclaration;
78601             var declarations = symbol.declarations;
78602             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
78603             function reportImplementationExpectedError(node) {
78604                 if (node.name && ts.nodeIsMissing(node.name)) {
78605                     return;
78606                 }
78607                 var seen = false;
78608                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
78609                     if (seen) {
78610                         return c;
78611                     }
78612                     else {
78613                         seen = c === node;
78614                     }
78615                 });
78616                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
78617                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
78618                 if (subsequentNode && subsequentNode.pos === node.end) {
78619                     if (subsequentNode.kind === node.kind) {
78620                         var errorNode_1 = subsequentNode.name || subsequentNode;
78621                         var subsequentName = subsequentNode.name;
78622                         if (node.name && subsequentName && (
78623                         // both are private identifiers
78624                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
78625                             // Both are computed property names
78626                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
78627                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
78628                             // Both are literal property names that are the same.
78629                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
78630                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
78631                             var reportError = (node.kind === 168 /* MethodDeclaration */ || node.kind === 167 /* MethodSignature */) &&
78632                                 ts.isStatic(node) !== ts.isStatic(subsequentNode);
78633                             // we can get here in two cases
78634                             // 1. mixed static and instance class members
78635                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
78636                             // here we'll report error only for the first case since for second we should already report error in binder
78637                             if (reportError) {
78638                                 var diagnostic = ts.isStatic(node) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
78639                                 error(errorNode_1, diagnostic);
78640                             }
78641                             return;
78642                         }
78643                         if (ts.nodeIsPresent(subsequentNode.body)) {
78644                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
78645                             return;
78646                         }
78647                     }
78648                 }
78649                 var errorNode = node.name || node;
78650                 if (isConstructor) {
78651                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
78652                 }
78653                 else {
78654                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
78655                     // the node in question is abstract.
78656                     if (ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
78657                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
78658                     }
78659                     else {
78660                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
78661                     }
78662                 }
78663             }
78664             var duplicateFunctionDeclaration = false;
78665             var multipleConstructorImplementation = false;
78666             var hasNonAmbientClass = false;
78667             var functionDeclarations = [];
78668             if (declarations) {
78669                 for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
78670                     var current = declarations_4[_i];
78671                     var node = current;
78672                     var inAmbientContext = node.flags & 8388608 /* Ambient */;
78673                     var inAmbientContextOrInterface = node.parent && (node.parent.kind === 257 /* InterfaceDeclaration */ || node.parent.kind === 181 /* TypeLiteral */) || inAmbientContext;
78674                     if (inAmbientContextOrInterface) {
78675                         // check if declarations are consecutive only if they are non-ambient
78676                         // 1. ambient declarations can be interleaved
78677                         // i.e. this is legal
78678                         //     declare function foo();
78679                         //     declare function bar();
78680                         //     declare function foo();
78681                         // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
78682                         previousDeclaration = undefined;
78683                     }
78684                     if ((node.kind === 256 /* ClassDeclaration */ || node.kind === 225 /* ClassExpression */) && !inAmbientContext) {
78685                         hasNonAmbientClass = true;
78686                     }
78687                     if (node.kind === 255 /* FunctionDeclaration */ || node.kind === 168 /* MethodDeclaration */ || node.kind === 167 /* MethodSignature */ || node.kind === 170 /* Constructor */) {
78688                         functionDeclarations.push(node);
78689                         var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
78690                         someNodeFlags |= currentNodeFlags;
78691                         allNodeFlags &= currentNodeFlags;
78692                         someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
78693                         allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
78694                         var bodyIsPresent = ts.nodeIsPresent(node.body);
78695                         if (bodyIsPresent && bodyDeclaration) {
78696                             if (isConstructor) {
78697                                 multipleConstructorImplementation = true;
78698                             }
78699                             else {
78700                                 duplicateFunctionDeclaration = true;
78701                             }
78702                         }
78703                         else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
78704                             reportImplementationExpectedError(previousDeclaration);
78705                         }
78706                         if (bodyIsPresent) {
78707                             if (!bodyDeclaration) {
78708                                 bodyDeclaration = node;
78709                             }
78710                         }
78711                         else {
78712                             hasOverloads = true;
78713                         }
78714                         previousDeclaration = node;
78715                         if (!inAmbientContextOrInterface) {
78716                             lastSeenNonAmbientDeclaration = node;
78717                         }
78718                     }
78719                 }
78720             }
78721             if (multipleConstructorImplementation) {
78722                 ts.forEach(functionDeclarations, function (declaration) {
78723                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
78724                 });
78725             }
78726             if (duplicateFunctionDeclaration) {
78727                 ts.forEach(functionDeclarations, function (declaration) {
78728                     error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_function_implementation);
78729                 });
78730             }
78731             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */ && declarations) {
78732                 var relatedDiagnostics_1 = ts.filter(declarations, function (d) { return d.kind === 256 /* ClassDeclaration */; })
78733                     .map(function (d) { return ts.createDiagnosticForNode(d, ts.Diagnostics.Consider_adding_a_declare_modifier_to_this_class); });
78734                 ts.forEach(declarations, function (declaration) {
78735                     var diagnostic = declaration.kind === 256 /* ClassDeclaration */
78736                         ? ts.Diagnostics.Class_declaration_cannot_implement_overload_list_for_0
78737                         : declaration.kind === 255 /* FunctionDeclaration */
78738                             ? ts.Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient
78739                             : undefined;
78740                     if (diagnostic) {
78741                         ts.addRelatedInfo.apply(void 0, __spreadArray([error(ts.getNameOfDeclaration(declaration) || declaration, diagnostic, ts.symbolName(symbol))], relatedDiagnostics_1, false));
78742                     }
78743                 });
78744             }
78745             // Abstract methods can't have an implementation -- in particular, they don't need one.
78746             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
78747                 !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
78748                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
78749             }
78750             if (hasOverloads) {
78751                 if (declarations) {
78752                     checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
78753                     checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
78754                 }
78755                 if (bodyDeclaration) {
78756                     var signatures = getSignaturesOfSymbol(symbol);
78757                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
78758                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
78759                         var signature = signatures_10[_a];
78760                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
78761                             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));
78762                             break;
78763                         }
78764                     }
78765                 }
78766             }
78767         }
78768         function checkExportsOnMergedDeclarations(node) {
78769             if (!produceDiagnostics) {
78770                 return;
78771             }
78772             // if localSymbol is defined on node then node itself is exported - check is required
78773             var symbol = node.localSymbol;
78774             if (!symbol) {
78775                 // local symbol is undefined => this declaration is non-exported.
78776                 // however symbol might contain other declarations that are exported
78777                 symbol = getSymbolOfNode(node);
78778                 if (!symbol.exportSymbol) {
78779                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
78780                     return;
78781                 }
78782             }
78783             // run the check only for the first declaration in the list
78784             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
78785                 return;
78786             }
78787             var exportedDeclarationSpaces = 0 /* None */;
78788             var nonExportedDeclarationSpaces = 0 /* None */;
78789             var defaultExportedDeclarationSpaces = 0 /* None */;
78790             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
78791                 var d = _a[_i];
78792                 var declarationSpaces = getDeclarationSpaces(d);
78793                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
78794                 if (effectiveDeclarationFlags & 1 /* Export */) {
78795                     if (effectiveDeclarationFlags & 512 /* Default */) {
78796                         defaultExportedDeclarationSpaces |= declarationSpaces;
78797                     }
78798                     else {
78799                         exportedDeclarationSpaces |= declarationSpaces;
78800                     }
78801                 }
78802                 else {
78803                     nonExportedDeclarationSpaces |= declarationSpaces;
78804                 }
78805             }
78806             // Spaces for anything not declared a 'default export'.
78807             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
78808             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
78809             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
78810             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
78811                 // declaration spaces for exported and non-exported declarations intersect
78812                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
78813                     var d = _c[_b];
78814                     var declarationSpaces = getDeclarationSpaces(d);
78815                     var name = ts.getNameOfDeclaration(d);
78816                     // Only error on the declarations that contributed to the intersecting spaces.
78817                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
78818                         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));
78819                     }
78820                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
78821                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
78822                     }
78823                 }
78824             }
78825             function getDeclarationSpaces(decl) {
78826                 var d = decl;
78827                 switch (d.kind) {
78828                     case 257 /* InterfaceDeclaration */:
78829                     case 258 /* TypeAliasDeclaration */:
78830                     // A jsdoc typedef and callback are, by definition, type aliases.
78831                     // falls through
78832                     case 343 /* JSDocTypedefTag */:
78833                     case 336 /* JSDocCallbackTag */:
78834                     case 337 /* JSDocEnumTag */:
78835                         return 2 /* ExportType */;
78836                     case 260 /* ModuleDeclaration */:
78837                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
78838                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
78839                             : 4 /* ExportNamespace */;
78840                     case 256 /* ClassDeclaration */:
78841                     case 259 /* EnumDeclaration */:
78842                     case 297 /* EnumMember */:
78843                         return 2 /* ExportType */ | 1 /* ExportValue */;
78844                     case 303 /* SourceFile */:
78845                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
78846                     case 270 /* ExportAssignment */:
78847                     case 220 /* BinaryExpression */:
78848                         var node_2 = d;
78849                         var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right;
78850                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
78851                         if (!ts.isEntityNameExpression(expression)) {
78852                             return 1 /* ExportValue */;
78853                         }
78854                         d = expression;
78855                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
78856                     // falls through
78857                     case 264 /* ImportEqualsDeclaration */:
78858                     case 267 /* NamespaceImport */:
78859                     case 266 /* ImportClause */:
78860                         var result_11 = 0 /* None */;
78861                         var target = resolveAlias(getSymbolOfNode(d));
78862                         ts.forEach(target.declarations, function (d) {
78863                             result_11 |= getDeclarationSpaces(d);
78864                         });
78865                         return result_11;
78866                     case 253 /* VariableDeclaration */:
78867                     case 202 /* BindingElement */:
78868                     case 255 /* FunctionDeclaration */:
78869                     case 269 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
78870                     case 79 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
78871                         // Identifiers are used as declarations of assignment declarations whose parents may be
78872                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
78873                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
78874                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
78875                         // all of which are pretty much always values, or at least imply a value meaning.
78876                         // It may be apprpriate to treat these as aliases in the future.
78877                         return 1 /* ExportValue */;
78878                     default:
78879                         return ts.Debug.failBadSyntaxKind(d);
78880                 }
78881             }
78882         }
78883         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
78884             var promisedType = getPromisedTypeOfPromise(type, errorNode);
78885             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
78886         }
78887         /**
78888          * Gets the "promised type" of a promise.
78889          * @param type The type of the promise.
78890          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
78891          */
78892         function getPromisedTypeOfPromise(type, errorNode) {
78893             //
78894             //  { // type
78895             //      then( // thenFunction
78896             //          onfulfilled: ( // onfulfilledParameterType
78897             //              value: T // valueParameterType
78898             //          ) => any
78899             //      ): any;
78900             //  }
78901             //
78902             if (isTypeAny(type)) {
78903                 return undefined;
78904             }
78905             var typeAsPromise = type;
78906             if (typeAsPromise.promisedTypeOfPromise) {
78907                 return typeAsPromise.promisedTypeOfPromise;
78908             }
78909             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
78910                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
78911             }
78912             // primitives with a `{ then() }` won't be unwrapped/adopted.
78913             if (allTypesAssignableToKind(type, 131068 /* Primitive */ | 131072 /* Never */)) {
78914                 return undefined;
78915             }
78916             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
78917             if (isTypeAny(thenFunction)) {
78918                 return undefined;
78919             }
78920             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
78921             if (thenSignatures.length === 0) {
78922                 if (errorNode) {
78923                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
78924                 }
78925                 return undefined;
78926             }
78927             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
78928             if (isTypeAny(onfulfilledParameterType)) {
78929                 return undefined;
78930             }
78931             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
78932             if (onfulfilledParameterSignatures.length === 0) {
78933                 if (errorNode) {
78934                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
78935                 }
78936                 return undefined;
78937             }
78938             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
78939         }
78940         /**
78941          * Gets the "awaited type" of a type.
78942          * @param type The type to await.
78943          * @param withAlias When `true`, wraps the "awaited type" in `Awaited<T>` if needed.
78944          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
78945          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
78946          * The runtime behavior of the `await` keyword.
78947          */
78948         function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, arg0) {
78949             var awaitedType = withAlias ?
78950                 getAwaitedType(type, errorNode, diagnosticMessage, arg0) :
78951                 getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0);
78952             return awaitedType || errorType;
78953         }
78954         /**
78955          * Determines whether a type is an object with a callable `then` member.
78956          */
78957         function isThenableType(type) {
78958             if (allTypesAssignableToKind(type, 131068 /* Primitive */ | 131072 /* Never */)) {
78959                 // primitive types cannot be considered "thenable" since they are not objects.
78960                 return false;
78961             }
78962             var thenFunction = getTypeOfPropertyOfType(type, "then");
78963             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
78964         }
78965         function isAwaitedTypeInstantiation(type) {
78966             var _a;
78967             if (type.flags & 16777216 /* Conditional */) {
78968                 var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ false);
78969                 return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a = type.aliasTypeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1;
78970             }
78971             return false;
78972         }
78973         /**
78974          * For a generic `Awaited<T>`, gets `T`.
78975          */
78976         function unwrapAwaitedType(type) {
78977             return type.flags & 1048576 /* Union */ ? mapType(type, unwrapAwaitedType) :
78978                 isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] :
78979                     type;
78980         }
78981         function createAwaitedTypeIfNeeded(type) {
78982             // We wrap type `T` in `Awaited<T>` based on the following conditions:
78983             // - `T` is not already an `Awaited<U>`, and
78984             // - `T` is generic, and
78985             // - One of the following applies:
78986             //   - `T` has no base constraint, or
78987             //   - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or
78988             //   - The base constraint of `T` is an object type with a callable `then` method.
78989             if (isTypeAny(type)) {
78990                 return type;
78991             }
78992             // If this is already an `Awaited<T>`, just return it. This helps to avoid `Awaited<Awaited<T>>` in higher-order.
78993             if (isAwaitedTypeInstantiation(type)) {
78994                 return type;
78995             }
78996             // Only instantiate `Awaited<T>` if `T` contains possibly non-primitive types.
78997             if (isGenericObjectType(type)) {
78998                 var baseConstraint = getBaseConstraintOfType(type);
78999                 // Only instantiate `Awaited<T>` if `T` has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`,
79000                 // or is promise-like.
79001                 if (!baseConstraint || (baseConstraint.flags & 3 /* AnyOrUnknown */) || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint)) {
79002                     // Nothing to do if `Awaited<T>` doesn't exist
79003                     var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true);
79004                     if (awaitedSymbol) {
79005                         // Unwrap unions that may contain `Awaited<T>`, otherwise its possible to manufacture an `Awaited<Awaited<T> | U>` where
79006                         // an `Awaited<T | U>` would suffice.
79007                         return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]);
79008                     }
79009                 }
79010             }
79011             ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like.");
79012             return type;
79013         }
79014         /**
79015          * Gets the "awaited type" of a type.
79016          *
79017          * The "awaited type" of an expression is its "promised type" if the expression is a
79018          * Promise-like type; otherwise, it is the type of the expression. If the "promised
79019          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
79020          * non-promise type is found.
79021          *
79022          * This is used to reflect the runtime behavior of the `await` keyword.
79023          */
79024         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
79025             var awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0);
79026             return awaitedType && createAwaitedTypeIfNeeded(awaitedType);
79027         }
79028         /**
79029          * Gets the "awaited type" of a type without introducing an `Awaited<T>` wrapper.
79030          *
79031          * @see {@link getAwaitedType}
79032          */
79033         function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, arg0) {
79034             if (isTypeAny(type)) {
79035                 return type;
79036             }
79037             // If this is already an `Awaited<T>`, just return it. This avoids `Awaited<Awaited<T>>` in higher-order
79038             if (isAwaitedTypeInstantiation(type)) {
79039                 return type;
79040             }
79041             // If we've already cached an awaited type, return a possible `Awaited<T>` for it.
79042             var typeAsAwaitable = type;
79043             if (typeAsAwaitable.awaitedTypeOfType) {
79044                 return typeAsAwaitable.awaitedTypeOfType;
79045             }
79046             // For a union, get a union of the awaited types of each constituent.
79047             if (type.flags & 1048576 /* Union */) {
79048                 var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias;
79049                 return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper);
79050             }
79051             var promisedType = getPromisedTypeOfPromise(type);
79052             if (promisedType) {
79053                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
79054                     // Verify that we don't have a bad actor in the form of a promise whose
79055                     // promised type is the same as the promise type, or a mutually recursive
79056                     // promise. If so, we return undefined as we cannot guess the shape. If this
79057                     // were the actual case in the JavaScript, this Promise would never resolve.
79058                     //
79059                     // An example of a bad actor with a singly-recursive promise type might
79060                     // be:
79061                     //
79062                     //  interface BadPromise {
79063                     //      then(
79064                     //          onfulfilled: (value: BadPromise) => any,
79065                     //          onrejected: (error: any) => any): BadPromise;
79066                     //  }
79067                     //
79068                     // The above interface will pass the PromiseLike check, and return a
79069                     // promised type of `BadPromise`. Since this is a self reference, we
79070                     // don't want to keep recursing ad infinitum.
79071                     //
79072                     // An example of a bad actor in the form of a mutually-recursive
79073                     // promise type might be:
79074                     //
79075                     //  interface BadPromiseA {
79076                     //      then(
79077                     //          onfulfilled: (value: BadPromiseB) => any,
79078                     //          onrejected: (error: any) => any): BadPromiseB;
79079                     //  }
79080                     //
79081                     //  interface BadPromiseB {
79082                     //      then(
79083                     //          onfulfilled: (value: BadPromiseA) => any,
79084                     //          onrejected: (error: any) => any): BadPromiseA;
79085                     //  }
79086                     //
79087                     if (errorNode) {
79088                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
79089                     }
79090                     return undefined;
79091                 }
79092                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
79093                 // See the comments above for more information.
79094                 awaitedTypeStack.push(type.id);
79095                 var awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, arg0);
79096                 awaitedTypeStack.pop();
79097                 if (!awaitedType) {
79098                     return undefined;
79099                 }
79100                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
79101             }
79102             // The type was not a promise, so it could not be unwrapped any further.
79103             // As long as the type does not have a callable "then" property, it is
79104             // safe to return the type; otherwise, an error is reported and we return
79105             // undefined.
79106             //
79107             // An example of a non-promise "thenable" might be:
79108             //
79109             //  await { then(): void {} }
79110             //
79111             // The "thenable" does not match the minimal definition for a promise. When
79112             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
79113             // will never settle. We treat this as an error to help flag an early indicator
79114             // of a runtime problem. If the user wants to return this value from an async
79115             // function, they would need to wrap it in some other value. If they want it to
79116             // be treated as a promise, they can cast to <any>.
79117             if (isThenableType(type)) {
79118                 if (errorNode) {
79119                     ts.Debug.assertIsDefined(diagnosticMessage);
79120                     error(errorNode, diagnosticMessage, arg0);
79121                 }
79122                 return undefined;
79123             }
79124             return typeAsAwaitable.awaitedTypeOfType = type;
79125         }
79126         /**
79127          * Checks the return type of an async function to ensure it is a compatible
79128          * Promise implementation.
79129          *
79130          * This checks that an async function has a valid Promise-compatible return type.
79131          * An async function has a valid Promise-compatible return type if the resolved value
79132          * of the return type has a construct signature that takes in an `initializer` function
79133          * that in turn supplies a `resolve` function as one of its arguments and results in an
79134          * object with a callable `then` signature.
79135          *
79136          * @param node The signature to check
79137          */
79138         function checkAsyncFunctionReturnType(node, returnTypeNode) {
79139             // As part of our emit for an async function, we will need to emit the entity name of
79140             // the return type annotation as an expression. To meet the necessary runtime semantics
79141             // for __awaiter, we must also check that the type of the declaration (e.g. the static
79142             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
79143             //
79144             // An example might be (from lib.es6.d.ts):
79145             //
79146             //  interface Promise<T> { ... }
79147             //  interface PromiseConstructor {
79148             //      new <T>(...): Promise<T>;
79149             //  }
79150             //  declare var Promise: PromiseConstructor;
79151             //
79152             // When an async function declares a return type annotation of `Promise<T>`, we
79153             // need to get the type of the `Promise` variable declaration above, which would
79154             // be `PromiseConstructor`.
79155             //
79156             // The same case applies to a class:
79157             //
79158             //  declare class Promise<T> {
79159             //      constructor(...);
79160             //      then<U>(...): Promise<U>;
79161             //  }
79162             //
79163             var returnType = getTypeFromTypeNode(returnTypeNode);
79164             if (languageVersion >= 2 /* ES2015 */) {
79165                 if (isErrorType(returnType)) {
79166                     return;
79167                 }
79168                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
79169                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
79170                     // The promise type was not a valid type reference to the global promise type, so we
79171                     // report an error and return the unknown type.
79172                     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(getAwaitedTypeNoAlias(returnType) || voidType));
79173                     return;
79174                 }
79175             }
79176             else {
79177                 // Always mark the type node as referenced if it points to a value
79178                 markTypeNodeAsReferenced(returnTypeNode);
79179                 if (isErrorType(returnType)) {
79180                     return;
79181                 }
79182                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
79183                 if (promiseConstructorName === undefined) {
79184                     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));
79185                     return;
79186                 }
79187                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
79188                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
79189                 if (isErrorType(promiseConstructorType)) {
79190                     if (promiseConstructorName.kind === 79 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
79191                         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);
79192                     }
79193                     else {
79194                         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));
79195                     }
79196                     return;
79197                 }
79198                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
79199                 if (globalPromiseConstructorLikeType === emptyObjectType) {
79200                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
79201                     // compatibility with __awaiter.
79202                     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));
79203                     return;
79204                 }
79205                 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)) {
79206                     return;
79207                 }
79208                 // Verify there is no local declaration that could collide with the promise constructor.
79209                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
79210                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
79211                 if (collidingSymbol) {
79212                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
79213                     return;
79214                 }
79215             }
79216             checkAwaitedType(returnType, /*withAlias*/ false, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
79217         }
79218         /** Check a decorator */
79219         function checkDecorator(node) {
79220             var signature = getResolvedSignature(node);
79221             checkDeprecatedSignature(signature, node);
79222             var returnType = getReturnTypeOfSignature(signature);
79223             if (returnType.flags & 1 /* Any */) {
79224                 return;
79225             }
79226             var expectedReturnType;
79227             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
79228             var errorInfo;
79229             switch (node.parent.kind) {
79230                 case 256 /* ClassDeclaration */:
79231                     var classSymbol = getSymbolOfNode(node.parent);
79232                     var classConstructorType = getTypeOfSymbol(classSymbol);
79233                     expectedReturnType = getUnionType([classConstructorType, voidType]);
79234                     break;
79235                 case 163 /* Parameter */:
79236                     expectedReturnType = voidType;
79237                     errorInfo = ts.chainDiagnosticMessages(
79238                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
79239                     break;
79240                 case 166 /* PropertyDeclaration */:
79241                     expectedReturnType = voidType;
79242                     errorInfo = ts.chainDiagnosticMessages(
79243                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
79244                     break;
79245                 case 168 /* MethodDeclaration */:
79246                 case 171 /* GetAccessor */:
79247                 case 172 /* SetAccessor */:
79248                     var methodType = getTypeOfNode(node.parent);
79249                     var descriptorType = createTypedPropertyDescriptorType(methodType);
79250                     expectedReturnType = getUnionType([descriptorType, voidType]);
79251                     break;
79252                 default:
79253                     return ts.Debug.fail();
79254             }
79255             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
79256         }
79257         /**
79258          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
79259          * marked as referenced to prevent import elision.
79260          */
79261         function markTypeNodeAsReferenced(node) {
79262             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
79263         }
79264         function markEntityNameOrEntityExpressionAsReference(typeName) {
79265             if (!typeName)
79266                 return;
79267             var rootName = ts.getFirstIdentifier(typeName);
79268             var meaning = (typeName.kind === 79 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
79269             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isReference*/ true);
79270             if (rootSymbol
79271                 && rootSymbol.flags & 2097152 /* Alias */
79272                 && symbolIsValue(rootSymbol)
79273                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
79274                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
79275                 markAliasSymbolAsReferenced(rootSymbol);
79276             }
79277         }
79278         /**
79279          * This function marks the type used for metadata decorator as referenced if it is import
79280          * from external module.
79281          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
79282          * union and intersection type
79283          * @param node
79284          */
79285         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
79286             var entityName = getEntityNameForDecoratorMetadata(node);
79287             if (entityName && ts.isEntityName(entityName)) {
79288                 markEntityNameOrEntityExpressionAsReference(entityName);
79289             }
79290         }
79291         function getEntityNameForDecoratorMetadata(node) {
79292             if (node) {
79293                 switch (node.kind) {
79294                     case 187 /* IntersectionType */:
79295                     case 186 /* UnionType */:
79296                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
79297                     case 188 /* ConditionalType */:
79298                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
79299                     case 190 /* ParenthesizedType */:
79300                     case 196 /* NamedTupleMember */:
79301                         return getEntityNameForDecoratorMetadata(node.type);
79302                     case 177 /* TypeReference */:
79303                         return node.typeName;
79304                 }
79305             }
79306         }
79307         function getEntityNameForDecoratorMetadataFromTypeList(types) {
79308             var commonEntityName;
79309             for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
79310                 var typeNode = types_22[_i];
79311                 while (typeNode.kind === 190 /* ParenthesizedType */ || typeNode.kind === 196 /* NamedTupleMember */) {
79312                     typeNode = typeNode.type; // Skip parens if need be
79313                 }
79314                 if (typeNode.kind === 143 /* NeverKeyword */) {
79315                     continue; // Always elide `never` from the union/intersection if possible
79316                 }
79317                 if (!strictNullChecks && (typeNode.kind === 195 /* LiteralType */ && typeNode.literal.kind === 104 /* NullKeyword */ || typeNode.kind === 152 /* UndefinedKeyword */)) {
79318                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
79319                 }
79320                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
79321                 if (!individualEntityName) {
79322                     // Individual is something like string number
79323                     // So it would be serialized to either that type or object
79324                     // Safe to return here
79325                     return undefined;
79326                 }
79327                 if (commonEntityName) {
79328                     // Note this is in sync with the transformation that happens for type node.
79329                     // Keep this in sync with serializeUnionOrIntersectionType
79330                     // Verify if they refer to same entity and is identifier
79331                     // return undefined if they dont match because we would emit object
79332                     if (!ts.isIdentifier(commonEntityName) ||
79333                         !ts.isIdentifier(individualEntityName) ||
79334                         commonEntityName.escapedText !== individualEntityName.escapedText) {
79335                         return undefined;
79336                     }
79337                 }
79338                 else {
79339                     commonEntityName = individualEntityName;
79340                 }
79341             }
79342             return commonEntityName;
79343         }
79344         function getParameterTypeNodeForDecoratorCheck(node) {
79345             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
79346             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
79347         }
79348         /** Check the decorators of a node */
79349         function checkDecorators(node) {
79350             if (!node.decorators) {
79351                 return;
79352             }
79353             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
79354             // checkGrammarDecorators.
79355             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
79356                 return;
79357             }
79358             if (!compilerOptions.experimentalDecorators) {
79359                 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);
79360             }
79361             var firstDecorator = node.decorators[0];
79362             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
79363             if (node.kind === 163 /* Parameter */) {
79364                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
79365             }
79366             if (compilerOptions.emitDecoratorMetadata) {
79367                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
79368                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
79369                 switch (node.kind) {
79370                     case 256 /* ClassDeclaration */:
79371                         var constructor = ts.getFirstConstructorWithBody(node);
79372                         if (constructor) {
79373                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
79374                                 var parameter = _a[_i];
79375                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
79376                             }
79377                         }
79378                         break;
79379                     case 171 /* GetAccessor */:
79380                     case 172 /* SetAccessor */:
79381                         var otherKind = node.kind === 171 /* GetAccessor */ ? 172 /* SetAccessor */ : 171 /* GetAccessor */;
79382                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
79383                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
79384                         break;
79385                     case 168 /* MethodDeclaration */:
79386                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
79387                             var parameter = _c[_b];
79388                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
79389                         }
79390                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
79391                         break;
79392                     case 166 /* PropertyDeclaration */:
79393                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
79394                         break;
79395                     case 163 /* Parameter */:
79396                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
79397                         var containingSignature = node.parent;
79398                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
79399                             var parameter = _e[_d];
79400                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
79401                         }
79402                         break;
79403                 }
79404             }
79405             ts.forEach(node.decorators, checkDecorator);
79406         }
79407         function checkFunctionDeclaration(node) {
79408             if (produceDiagnostics) {
79409                 checkFunctionOrMethodDeclaration(node);
79410                 checkGrammarForGenerator(node);
79411                 checkCollisionsForDeclarationName(node, node.name);
79412             }
79413         }
79414         function checkJSDocTypeAliasTag(node) {
79415             if (!node.typeExpression) {
79416                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
79417                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
79418             }
79419             if (node.name) {
79420                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
79421             }
79422             checkSourceElement(node.typeExpression);
79423             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
79424         }
79425         function checkJSDocTemplateTag(node) {
79426             checkSourceElement(node.constraint);
79427             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
79428                 var tp = _a[_i];
79429                 checkSourceElement(tp);
79430             }
79431         }
79432         function checkJSDocTypeTag(node) {
79433             checkSourceElement(node.typeExpression);
79434         }
79435         function checkJSDocParameterTag(node) {
79436             checkSourceElement(node.typeExpression);
79437             if (!ts.getParameterSymbolFromJSDoc(node)) {
79438                 var decl = ts.getHostSignatureFromJSDoc(node);
79439                 // don't issue an error for invalid hosts -- just functions --
79440                 // and give a better error message when the host function mentions `arguments`
79441                 // but the tag doesn't have an array type
79442                 if (decl) {
79443                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
79444                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
79445                         return;
79446                     }
79447                     if (!containsArgumentsReference(decl)) {
79448                         if (ts.isQualifiedName(node.name)) {
79449                             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));
79450                         }
79451                         else {
79452                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
79453                         }
79454                     }
79455                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
79456                         node.typeExpression && node.typeExpression.type &&
79457                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
79458                         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 === 160 /* QualifiedName */ ? node.name.right : node.name));
79459                     }
79460                 }
79461             }
79462         }
79463         function checkJSDocPropertyTag(node) {
79464             checkSourceElement(node.typeExpression);
79465         }
79466         function checkJSDocFunctionType(node) {
79467             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
79468                 reportImplicitAny(node, anyType);
79469             }
79470             checkSignatureDeclaration(node);
79471         }
79472         function checkJSDocImplementsTag(node) {
79473             var classLike = ts.getEffectiveJSDocHost(node);
79474             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
79475                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
79476             }
79477         }
79478         function checkJSDocAugmentsTag(node) {
79479             var classLike = ts.getEffectiveJSDocHost(node);
79480             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
79481                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
79482                 return;
79483             }
79484             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
79485             ts.Debug.assert(augmentsTags.length > 0);
79486             if (augmentsTags.length > 1) {
79487                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
79488             }
79489             var name = getIdentifierFromEntityNameExpression(node.class.expression);
79490             var extend = ts.getClassExtendsHeritageElement(classLike);
79491             if (extend) {
79492                 var className = getIdentifierFromEntityNameExpression(extend.expression);
79493                 if (className && name.escapedText !== className.escapedText) {
79494                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
79495                 }
79496             }
79497         }
79498         function checkJSDocAccessibilityModifiers(node) {
79499             var host = ts.getJSDocHost(node);
79500             if (host && ts.isPrivateIdentifierClassElementDeclaration(host)) {
79501                 error(node, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
79502             }
79503         }
79504         function getIdentifierFromEntityNameExpression(node) {
79505             switch (node.kind) {
79506                 case 79 /* Identifier */:
79507                     return node;
79508                 case 205 /* PropertyAccessExpression */:
79509                     return node.name;
79510                 default:
79511                     return undefined;
79512             }
79513         }
79514         function checkFunctionOrMethodDeclaration(node) {
79515             var _a;
79516             checkDecorators(node);
79517             checkSignatureDeclaration(node);
79518             var functionFlags = ts.getFunctionFlags(node);
79519             // Do not use hasDynamicName here, because that returns false for well known symbols.
79520             // We want to perform checkComputedPropertyName for all computed properties, including
79521             // well known symbols.
79522             if (node.name && node.name.kind === 161 /* ComputedPropertyName */) {
79523                 // This check will account for methods in class/interface declarations,
79524                 // as well as accessors in classes/object literals
79525                 checkComputedPropertyName(node.name);
79526             }
79527             if (hasBindableName(node)) {
79528                 // first we want to check the local symbol that contain this declaration
79529                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
79530                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
79531                 var symbol = getSymbolOfNode(node);
79532                 var localSymbol = node.localSymbol || symbol;
79533                 // Since the javascript won't do semantic analysis like typescript,
79534                 // if the javascript file comes before the typescript file and both contain same name functions,
79535                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
79536                 var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(
79537                 // Get first non javascript function declaration
79538                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
79539                 // Only type check the symbol once
79540                 if (node === firstDeclaration) {
79541                     checkFunctionOrConstructorSymbol(localSymbol);
79542                 }
79543                 if (symbol.parent) {
79544                     // run check on export symbol to check that modifiers agree across all exported declarations
79545                     checkFunctionOrConstructorSymbol(symbol);
79546                 }
79547             }
79548             var body = node.kind === 167 /* MethodSignature */ ? undefined : node.body;
79549             checkSourceElement(body);
79550             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
79551             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
79552                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
79553                 // in an ambient context
79554                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
79555                     reportImplicitAny(node, anyType);
79556                 }
79557                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
79558                     // A generator with a body and no type annotation can still cause errors. It can error if the
79559                     // yielded values have no common supertype, or it can give an implicit any error if it has no
79560                     // yielded values. The only way to trigger these errors is to try checking its return type.
79561                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
79562                 }
79563             }
79564             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
79565             if (ts.isInJSFile(node)) {
79566                 var typeTag = ts.getJSDocTypeTag(node);
79567                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
79568                     error(typeTag.typeExpression.type, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
79569                 }
79570             }
79571         }
79572         function registerForUnusedIdentifiersCheck(node) {
79573             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
79574             if (produceDiagnostics) {
79575                 var sourceFile = ts.getSourceFileOfNode(node);
79576                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
79577                 if (!potentiallyUnusedIdentifiers) {
79578                     potentiallyUnusedIdentifiers = [];
79579                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
79580                 }
79581                 // TODO: GH#22580
79582                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
79583                 potentiallyUnusedIdentifiers.push(node);
79584             }
79585         }
79586         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
79587             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
79588                 var node = potentiallyUnusedIdentifiers_1[_i];
79589                 switch (node.kind) {
79590                     case 256 /* ClassDeclaration */:
79591                     case 225 /* ClassExpression */:
79592                         checkUnusedClassMembers(node, addDiagnostic);
79593                         checkUnusedTypeParameters(node, addDiagnostic);
79594                         break;
79595                     case 303 /* SourceFile */:
79596                     case 260 /* ModuleDeclaration */:
79597                     case 234 /* Block */:
79598                     case 262 /* CaseBlock */:
79599                     case 241 /* ForStatement */:
79600                     case 242 /* ForInStatement */:
79601                     case 243 /* ForOfStatement */:
79602                         checkUnusedLocalsAndParameters(node, addDiagnostic);
79603                         break;
79604                     case 170 /* Constructor */:
79605                     case 212 /* FunctionExpression */:
79606                     case 255 /* FunctionDeclaration */:
79607                     case 213 /* ArrowFunction */:
79608                     case 168 /* MethodDeclaration */:
79609                     case 171 /* GetAccessor */:
79610                     case 172 /* SetAccessor */:
79611                         if (node.body) { // Don't report unused parameters in overloads
79612                             checkUnusedLocalsAndParameters(node, addDiagnostic);
79613                         }
79614                         checkUnusedTypeParameters(node, addDiagnostic);
79615                         break;
79616                     case 167 /* MethodSignature */:
79617                     case 173 /* CallSignature */:
79618                     case 174 /* ConstructSignature */:
79619                     case 178 /* FunctionType */:
79620                     case 179 /* ConstructorType */:
79621                     case 258 /* TypeAliasDeclaration */:
79622                     case 257 /* InterfaceDeclaration */:
79623                         checkUnusedTypeParameters(node, addDiagnostic);
79624                         break;
79625                     case 189 /* InferType */:
79626                         checkUnusedInferTypeParameter(node, addDiagnostic);
79627                         break;
79628                     default:
79629                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
79630                 }
79631             }
79632         }
79633         function errorUnusedLocal(declaration, name, addDiagnostic) {
79634             var node = ts.getNameOfDeclaration(declaration) || declaration;
79635             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
79636             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
79637         }
79638         function isIdentifierThatStartsWithUnderscore(node) {
79639             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
79640         }
79641         function checkUnusedClassMembers(node, addDiagnostic) {
79642             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
79643                 var member = _a[_i];
79644                 switch (member.kind) {
79645                     case 168 /* MethodDeclaration */:
79646                     case 166 /* PropertyDeclaration */:
79647                     case 171 /* GetAccessor */:
79648                     case 172 /* SetAccessor */:
79649                         if (member.kind === 172 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
79650                             // Already would have reported an error on the getter.
79651                             break;
79652                         }
79653                         var symbol = getSymbolOfNode(member);
79654                         if (!symbol.isReferenced
79655                             && (ts.hasEffectiveModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
79656                             && !(member.flags & 8388608 /* Ambient */)) {
79657                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
79658                         }
79659                         break;
79660                     case 170 /* Constructor */:
79661                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
79662                             var parameter = _c[_b];
79663                             if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) {
79664                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
79665                             }
79666                         }
79667                         break;
79668                     case 175 /* IndexSignature */:
79669                     case 233 /* SemicolonClassElement */:
79670                     case 169 /* ClassStaticBlockDeclaration */:
79671                         // Can't be private
79672                         break;
79673                     default:
79674                         ts.Debug.fail("Unexpected class member");
79675                 }
79676             }
79677         }
79678         function checkUnusedInferTypeParameter(node, addDiagnostic) {
79679             var typeParameter = node.typeParameter;
79680             if (isTypeParameterUnused(typeParameter)) {
79681                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
79682             }
79683         }
79684         function checkUnusedTypeParameters(node, addDiagnostic) {
79685             // Only report errors on the last declaration for the type parameter container;
79686             // this ensures that all uses have been accounted for.
79687             var declarations = getSymbolOfNode(node).declarations;
79688             if (!declarations || ts.last(declarations) !== node)
79689                 return;
79690             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
79691             var seenParentsWithEveryUnused = new ts.Set();
79692             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
79693                 var typeParameter = typeParameters_3[_i];
79694                 if (!isTypeParameterUnused(typeParameter))
79695                     continue;
79696                 var name = ts.idText(typeParameter.name);
79697                 var parent = typeParameter.parent;
79698                 if (parent.kind !== 189 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
79699                     if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
79700                         var sourceFile = ts.getSourceFileOfNode(parent);
79701                         var range = ts.isJSDocTemplateTag(parent)
79702                             // Whole @template tag
79703                             ? ts.rangeOfNode(parent)
79704                             // Include the `<>` in the error message
79705                             : ts.rangeOfTypeParameters(sourceFile, parent.typeParameters);
79706                         var only = parent.typeParameters.length === 1;
79707                         //TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag
79708                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
79709                         var arg0 = only ? name : undefined;
79710                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, message, arg0));
79711                     }
79712                 }
79713                 else {
79714                     //TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag
79715                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
79716                 }
79717             }
79718         }
79719         function isTypeParameterUnused(typeParameter) {
79720             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
79721         }
79722         function addToGroup(map, key, value, getKey) {
79723             var keyString = String(getKey(key));
79724             var group = map.get(keyString);
79725             if (group) {
79726                 group[1].push(value);
79727             }
79728             else {
79729                 map.set(keyString, [key, [value]]);
79730             }
79731         }
79732         function tryGetRootParameterDeclaration(node) {
79733             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
79734         }
79735         function isValidUnusedLocalDeclaration(declaration) {
79736             if (ts.isBindingElement(declaration)) {
79737                 if (ts.isObjectBindingPattern(declaration.parent)) {
79738                     /**
79739                      * ignore starts with underscore names _
79740                      * const { a: _a } = { a: 1 }
79741                      */
79742                     return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name));
79743                 }
79744                 return isIdentifierThatStartsWithUnderscore(declaration.name);
79745             }
79746             return ts.isAmbientModule(declaration) ||
79747                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
79748         }
79749         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
79750             // 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.
79751             var unusedImports = new ts.Map();
79752             var unusedDestructures = new ts.Map();
79753             var unusedVariables = new ts.Map();
79754             nodeWithLocals.locals.forEach(function (local) {
79755                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
79756                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
79757                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
79758                     return;
79759                 }
79760                 if (local.declarations) {
79761                     for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
79762                         var declaration = _a[_i];
79763                         if (isValidUnusedLocalDeclaration(declaration)) {
79764                             continue;
79765                         }
79766                         if (isImportedDeclaration(declaration)) {
79767                             addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
79768                         }
79769                         else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
79770                             // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
79771                             var lastElement = ts.last(declaration.parent.elements);
79772                             if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
79773                                 addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
79774                             }
79775                         }
79776                         else if (ts.isVariableDeclaration(declaration)) {
79777                             addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
79778                         }
79779                         else {
79780                             var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
79781                             var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
79782                             if (parameter && name) {
79783                                 if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
79784                                     if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) {
79785                                         addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
79786                                     }
79787                                     else {
79788                                         addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
79789                                     }
79790                                 }
79791                             }
79792                             else {
79793                                 errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
79794                             }
79795                         }
79796                     }
79797                 }
79798             });
79799             unusedImports.forEach(function (_a) {
79800                 var importClause = _a[0], unuseds = _a[1];
79801                 var importDecl = importClause.parent;
79802                 var nDeclarations = (importClause.name ? 1 : 0) +
79803                     (importClause.namedBindings ?
79804                         (importClause.namedBindings.kind === 267 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
79805                         : 0);
79806                 if (nDeclarations === unuseds.length) {
79807                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
79808                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
79809                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
79810                 }
79811                 else {
79812                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
79813                         var unused = unuseds_1[_i];
79814                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
79815                     }
79816                 }
79817             });
79818             unusedDestructures.forEach(function (_a) {
79819                 var bindingPattern = _a[0], bindingElements = _a[1];
79820                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
79821                 if (bindingPattern.elements.length === bindingElements.length) {
79822                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 253 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 254 /* VariableDeclarationList */) {
79823                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
79824                     }
79825                     else {
79826                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
79827                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
79828                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
79829                     }
79830                 }
79831                 else {
79832                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
79833                         var e = bindingElements_1[_i];
79834                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
79835                     }
79836                 }
79837             });
79838             unusedVariables.forEach(function (_a) {
79839                 var declarationList = _a[0], declarations = _a[1];
79840                 if (declarationList.declarations.length === declarations.length) {
79841                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
79842                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
79843                         : ts.createDiagnosticForNode(declarationList.parent.kind === 236 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
79844                 }
79845                 else {
79846                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
79847                         var decl = declarations_5[_i];
79848                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
79849                     }
79850                 }
79851             });
79852         }
79853         function bindingNameText(name) {
79854             switch (name.kind) {
79855                 case 79 /* Identifier */:
79856                     return ts.idText(name);
79857                 case 201 /* ArrayBindingPattern */:
79858                 case 200 /* ObjectBindingPattern */:
79859                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
79860                 default:
79861                     return ts.Debug.assertNever(name);
79862             }
79863         }
79864         function isImportedDeclaration(node) {
79865             return node.kind === 266 /* ImportClause */ || node.kind === 269 /* ImportSpecifier */ || node.kind === 267 /* NamespaceImport */;
79866         }
79867         function importClauseFromImported(decl) {
79868             return decl.kind === 266 /* ImportClause */ ? decl : decl.kind === 267 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
79869         }
79870         function checkBlock(node) {
79871             // Grammar checking for SyntaxKind.Block
79872             if (node.kind === 234 /* Block */) {
79873                 checkGrammarStatementInAmbientContext(node);
79874             }
79875             if (ts.isFunctionOrModuleBlock(node)) {
79876                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
79877                 ts.forEach(node.statements, checkSourceElement);
79878                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
79879             }
79880             else {
79881                 ts.forEach(node.statements, checkSourceElement);
79882             }
79883             if (node.locals) {
79884                 registerForUnusedIdentifiersCheck(node);
79885             }
79886         }
79887         function checkCollisionWithArgumentsInGeneratedCode(node) {
79888             // no rest parameters \ declaration context \ overload - no codegen impact
79889             if (languageVersion >= 2 /* ES2015 */ || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
79890                 return;
79891             }
79892             ts.forEach(node.parameters, function (p) {
79893                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
79894                     errorSkippedOn("noEmit", p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
79895                 }
79896             });
79897         }
79898         /**
79899          * Checks whether an {@link Identifier}, in the context of another {@link Node}, would collide with a runtime value
79900          * of {@link name} in an outer scope. This is used to check for collisions for downlevel transformations that
79901          * require names like `Object`, `Promise`, `Reflect`, `require`, `exports`, etc.
79902          */
79903         function needCollisionCheckForIdentifier(node, identifier, name) {
79904             if ((identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) !== name) {
79905                 return false;
79906             }
79907             if (node.kind === 166 /* PropertyDeclaration */ ||
79908                 node.kind === 165 /* PropertySignature */ ||
79909                 node.kind === 168 /* MethodDeclaration */ ||
79910                 node.kind === 167 /* MethodSignature */ ||
79911                 node.kind === 171 /* GetAccessor */ ||
79912                 node.kind === 172 /* SetAccessor */ ||
79913                 node.kind === 294 /* PropertyAssignment */) {
79914                 // it is ok to have member named '_super', '_this', `Promise`, etc. - member access is always qualified
79915                 return false;
79916             }
79917             if (node.flags & 8388608 /* Ambient */) {
79918                 // ambient context - no codegen impact
79919                 return false;
79920             }
79921             if (ts.isImportClause(node) || ts.isImportEqualsDeclaration(node) || ts.isImportSpecifier(node)) {
79922                 // type-only imports do not require collision checks against runtime values.
79923                 if (ts.isTypeOnlyImportOrExportDeclaration(node)) {
79924                     return false;
79925                 }
79926             }
79927             var root = ts.getRootDeclaration(node);
79928             if (ts.isParameter(root) && ts.nodeIsMissing(root.parent.body)) {
79929                 // just an overload - no codegen impact
79930                 return false;
79931             }
79932             return true;
79933         }
79934         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
79935         function checkIfThisIsCapturedInEnclosingScope(node) {
79936             ts.findAncestor(node, function (current) {
79937                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
79938                     var isDeclaration_1 = node.kind !== 79 /* Identifier */;
79939                     if (isDeclaration_1) {
79940                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
79941                     }
79942                     else {
79943                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
79944                     }
79945                     return true;
79946                 }
79947                 return false;
79948             });
79949         }
79950         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
79951             ts.findAncestor(node, function (current) {
79952                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
79953                     var isDeclaration_2 = node.kind !== 79 /* Identifier */;
79954                     if (isDeclaration_2) {
79955                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
79956                     }
79957                     else {
79958                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
79959                     }
79960                     return true;
79961                 }
79962                 return false;
79963             });
79964         }
79965         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
79966             // No need to check for require or exports for ES6 modules and later
79967             if (moduleKind >= ts.ModuleKind.ES2015 && !(moduleKind >= ts.ModuleKind.Node12 && ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS)) {
79968                 return;
79969             }
79970             if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
79971                 return;
79972             }
79973             // Uninstantiated modules shouldnt do this check
79974             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
79975                 return;
79976             }
79977             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
79978             var parent = getDeclarationContainer(node);
79979             if (parent.kind === 303 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
79980                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
79981                 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));
79982             }
79983         }
79984         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
79985             if (!name || languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
79986                 return;
79987             }
79988             // Uninstantiated modules shouldnt do this check
79989             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
79990                 return;
79991             }
79992             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
79993             var parent = getDeclarationContainer(node);
79994             if (parent.kind === 303 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
79995                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
79996                 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));
79997             }
79998         }
79999         function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) {
80000             if (languageVersion <= 8 /* ES2021 */
80001                 && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) {
80002                 potentialWeakMapSetCollisions.push(node);
80003             }
80004         }
80005         function checkWeakMapSetCollision(node) {
80006             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
80007             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
80008                 ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier");
80009                 errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText);
80010             }
80011         }
80012         function recordPotentialCollisionWithReflectInGeneratedCode(node, name) {
80013             if (name && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */
80014                 && needCollisionCheckForIdentifier(node, name, "Reflect")) {
80015                 potentialReflectCollisions.push(node);
80016             }
80017         }
80018         function checkReflectCollision(node) {
80019             var hasCollision = false;
80020             if (ts.isClassExpression(node)) {
80021                 // ClassExpression names don't contribute to their containers, but do matter for any of their block-scoped members.
80022                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80023                     var member = _a[_i];
80024                     if (getNodeCheckFlags(member) & 134217728 /* ContainsSuperPropertyInStaticInitializer */) {
80025                         hasCollision = true;
80026                         break;
80027                     }
80028                 }
80029             }
80030             else if (ts.isFunctionExpression(node)) {
80031                 // FunctionExpression names don't contribute to their containers, but do matter for their contents
80032                 if (getNodeCheckFlags(node) & 134217728 /* ContainsSuperPropertyInStaticInitializer */) {
80033                     hasCollision = true;
80034                 }
80035             }
80036             else {
80037                 var container = ts.getEnclosingBlockScopeContainer(node);
80038                 if (container && getNodeCheckFlags(container) & 134217728 /* ContainsSuperPropertyInStaticInitializer */) {
80039                     hasCollision = true;
80040                 }
80041             }
80042             if (hasCollision) {
80043                 ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name), "The target of a Reflect collision check should be an identifier");
80044                 errorSkippedOn("noEmit", node, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, ts.declarationNameToString(node.name), "Reflect");
80045             }
80046         }
80047         function checkCollisionsForDeclarationName(node, name) {
80048             if (!name)
80049                 return;
80050             checkCollisionWithRequireExportsInGeneratedCode(node, name);
80051             checkCollisionWithGlobalPromiseInGeneratedCode(node, name);
80052             recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name);
80053             recordPotentialCollisionWithReflectInGeneratedCode(node, name);
80054             if (ts.isClassLike(node)) {
80055                 checkTypeNameIsReserved(name, ts.Diagnostics.Class_name_cannot_be_0);
80056                 if (!(node.flags & 8388608 /* Ambient */)) {
80057                     checkClassNameCollisionWithObject(name);
80058                 }
80059             }
80060             else if (ts.isEnumDeclaration(node)) {
80061                 checkTypeNameIsReserved(name, ts.Diagnostics.Enum_name_cannot_be_0);
80062             }
80063         }
80064         function checkVarDeclaredNamesNotShadowed(node) {
80065             // - ScriptBody : StatementList
80066             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
80067             // also occurs in the VarDeclaredNames of StatementList.
80068             // - Block : { StatementList }
80069             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
80070             // also occurs in the VarDeclaredNames of StatementList.
80071             // Variable declarations are hoisted to the top of their function scope. They can shadow
80072             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
80073             // by the binder as the declaration scope is different.
80074             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
80075             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
80076             // block declared value. this is fine for let, but not const.
80077             // Only consider declarations with initializers, uninitialized const declarations will not
80078             // step on a let/const variable.
80079             // Do not consider const and const declarations, as duplicate block-scoped declarations
80080             // are handled by the binder.
80081             // We are only looking for const declarations that step on let\const declarations from a
80082             // different scope. e.g.:
80083             //      {
80084             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
80085             //          const x = 0; // symbol for this declaration will be 'symbol'
80086             //      }
80087             // skip block-scoped variables and parameters
80088             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
80089                 return;
80090             }
80091             // skip variable declarations that don't have initializers
80092             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
80093             // so we'll always treat binding elements as initialized
80094             if (node.kind === 253 /* VariableDeclaration */ && !node.initializer) {
80095                 return;
80096             }
80097             var symbol = getSymbolOfNode(node);
80098             if (symbol.flags & 1 /* FunctionScopedVariable */) {
80099                 if (!ts.isIdentifier(node.name))
80100                     return ts.Debug.fail();
80101                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
80102                 if (localDeclarationSymbol &&
80103                     localDeclarationSymbol !== symbol &&
80104                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
80105                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
80106                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 254 /* VariableDeclarationList */);
80107                         var container = varDeclList.parent.kind === 236 /* VariableStatement */ && varDeclList.parent.parent
80108                             ? varDeclList.parent.parent
80109                             : undefined;
80110                         // names of block-scoped and function scoped variables can collide only
80111                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
80112                         var namesShareScope = container &&
80113                             (container.kind === 234 /* Block */ && ts.isFunctionLike(container.parent) ||
80114                                 container.kind === 261 /* ModuleBlock */ ||
80115                                 container.kind === 260 /* ModuleDeclaration */ ||
80116                                 container.kind === 303 /* SourceFile */);
80117                         // here we know that function scoped variable is shadowed by block scoped one
80118                         // if they are defined in the same scope - binder has already reported redeclaration error
80119                         // otherwise if variable has an initializer - show error that initialization will fail
80120                         // since LHS will be block scoped name instead of function scoped
80121                         if (!namesShareScope) {
80122                             var name = symbolToString(localDeclarationSymbol);
80123                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
80124                         }
80125                     }
80126                 }
80127             }
80128         }
80129         function convertAutoToAny(type) {
80130             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
80131         }
80132         // Check variable, parameter, or property declaration
80133         function checkVariableLikeDeclaration(node) {
80134             var _a;
80135             checkDecorators(node);
80136             if (!ts.isBindingElement(node)) {
80137                 checkSourceElement(node.type);
80138             }
80139             // JSDoc `function(string, string): string` syntax results in parameters with no name
80140             if (!node.name) {
80141                 return;
80142             }
80143             // For a computed property, just check the initializer and exit
80144             // Do not use hasDynamicName here, because that returns false for well known symbols.
80145             // We want to perform checkComputedPropertyName for all computed properties, including
80146             // well known symbols.
80147             if (node.name.kind === 161 /* ComputedPropertyName */) {
80148                 checkComputedPropertyName(node.name);
80149                 if (node.initializer) {
80150                     checkExpressionCached(node.initializer);
80151                 }
80152             }
80153             if (ts.isBindingElement(node)) {
80154                 if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) {
80155                     checkExternalEmitHelpers(node, 4 /* Rest */);
80156                 }
80157                 // check computed properties inside property names of binding elements
80158                 if (node.propertyName && node.propertyName.kind === 161 /* ComputedPropertyName */) {
80159                     checkComputedPropertyName(node.propertyName);
80160                 }
80161                 // check private/protected variable access
80162                 var parent = node.parent.parent;
80163                 var parentType = getTypeForBindingElementParent(parent);
80164                 var name = node.propertyName || node.name;
80165                 if (parentType && !ts.isBindingPattern(name)) {
80166                     var exprType = getLiteralTypeFromPropertyName(name);
80167                     if (isTypeUsableAsPropertyName(exprType)) {
80168                         var nameText = getPropertyNameFromType(exprType);
80169                         var property = getPropertyOfType(parentType, nameText);
80170                         if (property) {
80171                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference.
80172                             checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 106 /* SuperKeyword */, /*writing*/ false, parentType, property);
80173                         }
80174                     }
80175                 }
80176             }
80177             // For a binding pattern, check contained binding elements
80178             if (ts.isBindingPattern(node.name)) {
80179                 if (node.name.kind === 201 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
80180                     checkExternalEmitHelpers(node, 512 /* Read */);
80181                 }
80182                 ts.forEach(node.name.elements, checkSourceElement);
80183             }
80184             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
80185             if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
80186                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
80187                 return;
80188             }
80189             // For a binding pattern, validate the initializer and exit
80190             if (ts.isBindingPattern(node.name)) {
80191                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 242 /* ForInStatement */;
80192                 var needCheckWidenedType = node.name.elements.length === 0;
80193                 if (needCheckInitializer || needCheckWidenedType) {
80194                     // Don't validate for-in initializer as it is already an error
80195                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
80196                     if (needCheckInitializer) {
80197                         var initializerType = checkExpressionCached(node.initializer);
80198                         if (strictNullChecks && needCheckWidenedType) {
80199                             checkNonNullNonVoidType(initializerType, node);
80200                         }
80201                         else {
80202                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
80203                         }
80204                     }
80205                     // check the binding pattern with empty elements
80206                     if (needCheckWidenedType) {
80207                         if (ts.isArrayBindingPattern(node.name)) {
80208                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
80209                         }
80210                         else if (strictNullChecks) {
80211                             checkNonNullNonVoidType(widenedType, node);
80212                         }
80213                     }
80214                 }
80215                 return;
80216             }
80217             // For a commonjs `const x = require`, validate the alias and exit
80218             var symbol = getSymbolOfNode(node);
80219             if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) {
80220                 checkAliasSymbol(node);
80221                 return;
80222             }
80223             var type = convertAutoToAny(getTypeOfSymbol(symbol));
80224             if (node === symbol.valueDeclaration) {
80225                 // Node is the primary declaration of the symbol, just validate the initializer
80226                 // Don't validate for-in initializer as it is already an error
80227                 var initializer = ts.getEffectiveInitializer(node);
80228                 if (initializer) {
80229                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
80230                         ts.isObjectLiteralExpression(initializer) &&
80231                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
80232                         !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
80233                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 242 /* ForInStatement */) {
80234                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
80235                     }
80236                 }
80237                 if (symbol.declarations && symbol.declarations.length > 1) {
80238                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
80239                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
80240                     }
80241                 }
80242             }
80243             else {
80244                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
80245                 // initializer is consistent with type associated with the node
80246                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
80247                 if (!isErrorType(type) && !isErrorType(declarationType) &&
80248                     !isTypeIdenticalTo(type, declarationType) &&
80249                     !(symbol.flags & 67108864 /* Assignment */)) {
80250                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
80251                 }
80252                 if (node.initializer) {
80253                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
80254                 }
80255                 if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
80256                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
80257                 }
80258             }
80259             if (node.kind !== 166 /* PropertyDeclaration */ && node.kind !== 165 /* PropertySignature */) {
80260                 // We know we don't have a binding pattern or computed name here
80261                 checkExportsOnMergedDeclarations(node);
80262                 if (node.kind === 253 /* VariableDeclaration */ || node.kind === 202 /* BindingElement */) {
80263                     checkVarDeclaredNamesNotShadowed(node);
80264                 }
80265                 checkCollisionsForDeclarationName(node, node.name);
80266             }
80267         }
80268         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
80269             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
80270             var message = nextDeclaration.kind === 166 /* PropertyDeclaration */ || nextDeclaration.kind === 165 /* PropertySignature */
80271                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
80272                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
80273             var declName = ts.declarationNameToString(nextDeclarationName);
80274             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
80275             if (firstDeclaration) {
80276                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
80277             }
80278         }
80279         function areDeclarationFlagsIdentical(left, right) {
80280             if ((left.kind === 163 /* Parameter */ && right.kind === 253 /* VariableDeclaration */) ||
80281                 (left.kind === 253 /* VariableDeclaration */ && right.kind === 163 /* Parameter */)) {
80282                 // Differences in optionality between parameters and variables are allowed.
80283                 return true;
80284             }
80285             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
80286                 return false;
80287             }
80288             var interestingFlags = 8 /* Private */ |
80289                 16 /* Protected */ |
80290                 256 /* Async */ |
80291                 128 /* Abstract */ |
80292                 64 /* Readonly */ |
80293                 32 /* Static */;
80294             return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
80295         }
80296         function checkVariableDeclaration(node) {
80297             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
80298             checkGrammarVariableDeclaration(node);
80299             checkVariableLikeDeclaration(node);
80300             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
80301         }
80302         function checkBindingElement(node) {
80303             checkGrammarBindingElement(node);
80304             return checkVariableLikeDeclaration(node);
80305         }
80306         function checkVariableStatement(node) {
80307             // Grammar checking
80308             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
80309                 checkGrammarForDisallowedLetOrConstStatement(node);
80310             ts.forEach(node.declarationList.declarations, checkSourceElement);
80311         }
80312         function checkExpressionStatement(node) {
80313             // Grammar checking
80314             checkGrammarStatementInAmbientContext(node);
80315             checkExpression(node.expression);
80316         }
80317         function checkIfStatement(node) {
80318             // Grammar checking
80319             checkGrammarStatementInAmbientContext(node);
80320             var type = checkTruthinessExpression(node.expression);
80321             checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement);
80322             checkSourceElement(node.thenStatement);
80323             if (node.thenStatement.kind === 235 /* EmptyStatement */) {
80324                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
80325             }
80326             checkSourceElement(node.elseStatement);
80327         }
80328         function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) {
80329             if (!strictNullChecks)
80330                 return;
80331             if (getFalsyFlags(type))
80332                 return;
80333             var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr;
80334             if (ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression)) {
80335                 return;
80336             }
80337             var testedNode = ts.isIdentifier(location) ? location
80338                 : ts.isPropertyAccessExpression(location) ? location.name
80339                     : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right
80340                         : undefined;
80341             // While it technically should be invalid for any known-truthy value
80342             // to be tested, we de-scope to functions and Promises unreferenced in
80343             // the block as a heuristic to identify the most common bugs. There
80344             // are too many false positives for values sourced from type
80345             // definitions without strictNullChecks otherwise.
80346             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
80347             var isPromise = !!getAwaitedTypeOfPromise(type);
80348             if (callSignatures.length === 0 && !isPromise) {
80349                 return;
80350             }
80351             var testedSymbol = testedNode && getSymbolAtLocation(testedNode);
80352             if (!testedSymbol && !isPromise) {
80353                 return;
80354             }
80355             var isUsed = testedSymbol && ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol)
80356                 || testedSymbol && body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol);
80357             if (!isUsed) {
80358                 if (isPromise) {
80359                     errorAndMaybeSuggestAwait(location, 
80360                     /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type));
80361                 }
80362                 else {
80363                     error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead);
80364                 }
80365             }
80366         }
80367         function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) {
80368             return !!ts.forEachChild(body, function check(childNode) {
80369                 if (ts.isIdentifier(childNode)) {
80370                     var childSymbol = getSymbolAtLocation(childNode);
80371                     if (childSymbol && childSymbol === testedSymbol) {
80372                         // If the test was a simple identifier, the above check is sufficient
80373                         if (ts.isIdentifier(expr)) {
80374                             return true;
80375                         }
80376                         // Otherwise we need to ensure the symbol is called on the same target
80377                         var testedExpression = testedNode.parent;
80378                         var childExpression = childNode.parent;
80379                         while (testedExpression && childExpression) {
80380                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
80381                                 testedExpression.kind === 108 /* ThisKeyword */ && childExpression.kind === 108 /* ThisKeyword */) {
80382                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
80383                             }
80384                             else if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
80385                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
80386                                     return false;
80387                                 }
80388                                 childExpression = childExpression.expression;
80389                                 testedExpression = testedExpression.expression;
80390                             }
80391                             else if (ts.isCallExpression(testedExpression) && ts.isCallExpression(childExpression)) {
80392                                 childExpression = childExpression.expression;
80393                                 testedExpression = testedExpression.expression;
80394                             }
80395                             else {
80396                                 return false;
80397                             }
80398                         }
80399                     }
80400                 }
80401                 return ts.forEachChild(childNode, check);
80402             });
80403         }
80404         function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) {
80405             while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
80406                 var isUsed = ts.forEachChild(node.right, function visit(child) {
80407                     if (ts.isIdentifier(child)) {
80408                         var symbol = getSymbolAtLocation(child);
80409                         if (symbol && symbol === testedSymbol) {
80410                             return true;
80411                         }
80412                     }
80413                     return ts.forEachChild(child, visit);
80414                 });
80415                 if (isUsed) {
80416                     return true;
80417                 }
80418                 node = node.parent;
80419             }
80420             return false;
80421         }
80422         function checkDoStatement(node) {
80423             // Grammar checking
80424             checkGrammarStatementInAmbientContext(node);
80425             checkSourceElement(node.statement);
80426             checkTruthinessExpression(node.expression);
80427         }
80428         function checkWhileStatement(node) {
80429             // Grammar checking
80430             checkGrammarStatementInAmbientContext(node);
80431             checkTruthinessExpression(node.expression);
80432             checkSourceElement(node.statement);
80433         }
80434         function checkTruthinessOfType(type, node) {
80435             if (type.flags & 16384 /* Void */) {
80436                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
80437             }
80438             return type;
80439         }
80440         function checkTruthinessExpression(node, checkMode) {
80441             return checkTruthinessOfType(checkExpression(node, checkMode), node);
80442         }
80443         function checkForStatement(node) {
80444             // Grammar checking
80445             if (!checkGrammarStatementInAmbientContext(node)) {
80446                 if (node.initializer && node.initializer.kind === 254 /* VariableDeclarationList */) {
80447                     checkGrammarVariableDeclarationList(node.initializer);
80448                 }
80449             }
80450             if (node.initializer) {
80451                 if (node.initializer.kind === 254 /* VariableDeclarationList */) {
80452                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
80453                 }
80454                 else {
80455                     checkExpression(node.initializer);
80456                 }
80457             }
80458             if (node.condition)
80459                 checkTruthinessExpression(node.condition);
80460             if (node.incrementor)
80461                 checkExpression(node.incrementor);
80462             checkSourceElement(node.statement);
80463             if (node.locals) {
80464                 registerForUnusedIdentifiersCheck(node);
80465             }
80466         }
80467         function checkForOfStatement(node) {
80468             checkGrammarForInOrForOfStatement(node);
80469             var container = ts.getContainingFunctionOrClassStaticBlock(node);
80470             if (node.awaitModifier) {
80471                 if (container && ts.isClassStaticBlockDeclaration(container)) {
80472                     grammarErrorOnNode(node.awaitModifier, ts.Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block);
80473                 }
80474                 else {
80475                     var functionFlags = ts.getFunctionFlags(container);
80476                     if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
80477                         // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
80478                         checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
80479                     }
80480                 }
80481             }
80482             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
80483                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
80484                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
80485             }
80486             // Check the LHS and RHS
80487             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
80488             // via checkRightHandSideOfForOf.
80489             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
80490             // Then check that the RHS is assignable to it.
80491             if (node.initializer.kind === 254 /* VariableDeclarationList */) {
80492                 checkForInOrForOfVariableDeclaration(node);
80493             }
80494             else {
80495                 var varExpr = node.initializer;
80496                 var iteratedType = checkRightHandSideOfForOf(node);
80497                 // There may be a destructuring assignment on the left side
80498                 if (varExpr.kind === 203 /* ArrayLiteralExpression */ || varExpr.kind === 204 /* ObjectLiteralExpression */) {
80499                     // iteratedType may be undefined. In this case, we still want to check the structure of
80500                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
80501                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
80502                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
80503                 }
80504                 else {
80505                     var leftType = checkExpression(varExpr);
80506                     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);
80507                     // iteratedType will be undefined if the rightType was missing properties/signatures
80508                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
80509                     // because we accessed properties from anyType, or it may have led to an error inside
80510                     // getElementTypeOfIterable.
80511                     if (iteratedType) {
80512                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
80513                     }
80514                 }
80515             }
80516             checkSourceElement(node.statement);
80517             if (node.locals) {
80518                 registerForUnusedIdentifiersCheck(node);
80519             }
80520         }
80521         function checkForInStatement(node) {
80522             // Grammar checking
80523             checkGrammarForInOrForOfStatement(node);
80524             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
80525             // TypeScript 1.0 spec (April 2014): 5.4
80526             // In a 'for-in' statement of the form
80527             // for (let VarDecl in Expr) Statement
80528             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
80529             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
80530             if (node.initializer.kind === 254 /* VariableDeclarationList */) {
80531                 var variable = node.initializer.declarations[0];
80532                 if (variable && ts.isBindingPattern(variable.name)) {
80533                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
80534                 }
80535                 checkForInOrForOfVariableDeclaration(node);
80536             }
80537             else {
80538                 // In a 'for-in' statement of the form
80539                 // for (Var in Expr) Statement
80540                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
80541                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
80542                 var varExpr = node.initializer;
80543                 var leftType = checkExpression(varExpr);
80544                 if (varExpr.kind === 203 /* ArrayLiteralExpression */ || varExpr.kind === 204 /* ObjectLiteralExpression */) {
80545                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
80546                 }
80547                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
80548                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
80549                 }
80550                 else {
80551                     // run check only former check succeeded to avoid cascading errors
80552                     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);
80553                 }
80554             }
80555             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
80556             // in this case error about missing name is already reported - do not report extra one
80557             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
80558                 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));
80559             }
80560             checkSourceElement(node.statement);
80561             if (node.locals) {
80562                 registerForUnusedIdentifiersCheck(node);
80563             }
80564         }
80565         function checkForInOrForOfVariableDeclaration(iterationStatement) {
80566             var variableDeclarationList = iterationStatement.initializer;
80567             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
80568             if (variableDeclarationList.declarations.length >= 1) {
80569                 var decl = variableDeclarationList.declarations[0];
80570                 checkVariableDeclaration(decl);
80571             }
80572         }
80573         function checkRightHandSideOfForOf(statement) {
80574             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
80575             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
80576         }
80577         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
80578             if (isTypeAny(inputType)) {
80579                 return inputType;
80580             }
80581             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
80582         }
80583         /**
80584          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
80585          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
80586          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
80587          */
80588         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
80589             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
80590             if (inputType === neverType) {
80591                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
80592                 return undefined;
80593             }
80594             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
80595             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
80596             var possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
80597             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
80598             // or higher, when inside of an async generator or for-await-if, or when
80599             // downlevelIteration is requested.
80600             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
80601                 // We only report errors for an invalid iterable type in ES2015 or higher.
80602                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
80603                 if (checkAssignability) {
80604                     if (iterationTypes) {
80605                         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 :
80606                             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 :
80607                                 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 :
80608                                     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 :
80609                                         undefined;
80610                         if (diagnostic) {
80611                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
80612                         }
80613                     }
80614                 }
80615                 if (iterationTypes || uplevelIteration) {
80616                     return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : (iterationTypes && iterationTypes.yieldType);
80617                 }
80618             }
80619             var arrayType = inputType;
80620             var reportedError = false;
80621             var hasStringConstituent = false;
80622             // If strings are permitted, remove any string-like constituents from the array type.
80623             // This allows us to find other non-string element types from an array unioned with
80624             // a string.
80625             if (use & 4 /* AllowsStringInputFlag */) {
80626                 if (arrayType.flags & 1048576 /* Union */) {
80627                     // After we remove all types that are StringLike, we will know if there was a string constituent
80628                     // based on whether the result of filter is a new array.
80629                     var arrayTypes = inputType.types;
80630                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 402653316 /* StringLike */); });
80631                     if (filteredTypes !== arrayTypes) {
80632                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
80633                     }
80634                 }
80635                 else if (arrayType.flags & 402653316 /* StringLike */) {
80636                     arrayType = neverType;
80637                 }
80638                 hasStringConstituent = arrayType !== inputType;
80639                 if (hasStringConstituent) {
80640                     if (languageVersion < 1 /* ES5 */) {
80641                         if (errorNode) {
80642                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
80643                             reportedError = true;
80644                         }
80645                     }
80646                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
80647                     // arrayOrStringType was a string.
80648                     if (arrayType.flags & 131072 /* Never */) {
80649                         return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
80650                     }
80651                 }
80652             }
80653             if (!isArrayLikeType(arrayType)) {
80654                 if (errorNode && !reportedError) {
80655                     // Which error we report depends on whether we allow strings or if there was a
80656                     // string constituent. For example, if the input type is number | string, we
80657                     // want to say that number is not an array type. But if the input was just
80658                     // number and string input is allowed, we want to say that number is not an
80659                     // array type or a string type.
80660                     var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent;
80661                     var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
80662                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
80663                 }
80664                 return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined;
80665             }
80666             var arrayElementType = getIndexTypeOfType(arrayType, numberType);
80667             if (hasStringConstituent && arrayElementType) {
80668                 // This is just an optimization for the case where arrayOrStringType is string | string[]
80669                 if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
80670                     return stringType;
80671                 }
80672                 return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
80673             }
80674             return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
80675             function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) {
80676                 var _a;
80677                 if (downlevelIteration) {
80678                     return allowsStrings
80679                         ? [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]
80680                         : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true];
80681                 }
80682                 var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
80683                 if (yieldType) {
80684                     return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false];
80685                 }
80686                 if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) {
80687                     return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true];
80688                 }
80689                 return allowsStrings
80690                     ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true]
80691                     : [ts.Diagnostics.Type_0_is_not_an_array_type, true];
80692             }
80693         }
80694         function isES2015OrLaterIterable(n) {
80695             switch (n) {
80696                 case "Float32Array":
80697                 case "Float64Array":
80698                 case "Int16Array":
80699                 case "Int32Array":
80700                 case "Int8Array":
80701                 case "NodeList":
80702                 case "Uint16Array":
80703                 case "Uint32Array":
80704                 case "Uint8Array":
80705                 case "Uint8ClampedArray":
80706                     return true;
80707             }
80708             return false;
80709         }
80710         /**
80711          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
80712          */
80713         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
80714             if (isTypeAny(inputType)) {
80715                 return undefined;
80716             }
80717             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
80718             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
80719         }
80720         function createIterationTypes(yieldType, returnType, nextType) {
80721             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
80722             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
80723             // as it is combined via `getIntersectionType` when merging iteration types.
80724             if (yieldType === void 0) { yieldType = neverType; }
80725             if (returnType === void 0) { returnType = neverType; }
80726             if (nextType === void 0) { nextType = unknownType; }
80727             // Use the cache only for intrinsic types to keep it small as they are likely to be
80728             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
80729             // are also cached on the type they are requested for, so we shouldn't need to maintain
80730             // the cache for less-frequently used types.
80731             if (yieldType.flags & 67359327 /* Intrinsic */ &&
80732                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
80733                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
80734                 var id = getTypeListId([yieldType, returnType, nextType]);
80735                 var iterationTypes = iterationTypesCache.get(id);
80736                 if (!iterationTypes) {
80737                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
80738                     iterationTypesCache.set(id, iterationTypes);
80739                 }
80740                 return iterationTypes;
80741             }
80742             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
80743         }
80744         /**
80745          * Combines multiple `IterationTypes` records.
80746          *
80747          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
80748          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
80749          * for the combined iteration types.
80750          */
80751         function combineIterationTypes(array) {
80752             var yieldTypes;
80753             var returnTypes;
80754             var nextTypes;
80755             for (var _i = 0, array_11 = array; _i < array_11.length; _i++) {
80756                 var iterationTypes = array_11[_i];
80757                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
80758                     continue;
80759                 }
80760                 if (iterationTypes === anyIterationTypes) {
80761                     return anyIterationTypes;
80762                 }
80763                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
80764                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
80765                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
80766             }
80767             if (yieldTypes || returnTypes || nextTypes) {
80768                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
80769             }
80770             return noIterationTypes;
80771         }
80772         function getCachedIterationTypes(type, cacheKey) {
80773             return type[cacheKey];
80774         }
80775         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
80776             return type[cacheKey] = cachedTypes;
80777         }
80778         /**
80779          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
80780          *
80781          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
80782          *
80783          * Another thing to note is that at any step of this process, we could run into a dead end,
80784          * meaning either the property is missing, or we run into the anyType. If either of these things
80785          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
80786          * is missing, and the previous step did not result in `any`, then we also give an error if the
80787          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
80788          * type.
80789          *
80790          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
80791          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
80792          * method.
80793          *
80794          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
80795          *
80796          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
80797          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
80798          */
80799         function getIterationTypesOfIterable(type, use, errorNode) {
80800             if (isTypeAny(type)) {
80801                 return anyIterationTypes;
80802             }
80803             if (!(type.flags & 1048576 /* Union */)) {
80804                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
80805                 if (iterationTypes_1 === noIterationTypes) {
80806                     if (errorNode) {
80807                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
80808                     }
80809                     return undefined;
80810                 }
80811                 return iterationTypes_1;
80812             }
80813             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
80814             var cachedTypes = getCachedIterationTypes(type, cacheKey);
80815             if (cachedTypes)
80816                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
80817             var allIterationTypes;
80818             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
80819                 var constituent = _a[_i];
80820                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
80821                 if (iterationTypes_2 === noIterationTypes) {
80822                     if (errorNode) {
80823                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
80824                     }
80825                     setCachedIterationTypes(type, cacheKey, noIterationTypes);
80826                     return undefined;
80827                 }
80828                 else {
80829                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
80830                 }
80831             }
80832             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
80833             setCachedIterationTypes(type, cacheKey, iterationTypes);
80834             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
80835         }
80836         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
80837             if (iterationTypes === noIterationTypes)
80838                 return noIterationTypes;
80839             if (iterationTypes === anyIterationTypes)
80840                 return anyIterationTypes;
80841             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
80842             // if we're requesting diagnostics, report errors for a missing `Awaited<T>`.
80843             if (errorNode) {
80844                 getGlobalAwaitedSymbol(/*reportErrors*/ true);
80845             }
80846             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
80847         }
80848         /**
80849          * Gets the *yield*, *return*, and *next* types from a non-union type.
80850          *
80851          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
80852          * returned to indicate to the caller that it should report an error. Otherwise, an
80853          * `IterationTypes` record is returned.
80854          *
80855          * NOTE: You probably don't want to call this directly and should be calling
80856          * `getIterationTypesOfIterable` instead.
80857          */
80858         function getIterationTypesOfIterableWorker(type, use, errorNode) {
80859             if (isTypeAny(type)) {
80860                 return anyIterationTypes;
80861             }
80862             if (use & 2 /* AllowsAsyncIterablesFlag */) {
80863                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
80864                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
80865                 if (iterationTypes) {
80866                     return use & 8 /* ForOfFlag */ ?
80867                         getAsyncFromSyncIterationTypes(iterationTypes, errorNode) :
80868                         iterationTypes;
80869                 }
80870             }
80871             if (use & 1 /* AllowsSyncIterablesFlag */) {
80872                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
80873                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
80874                 if (iterationTypes) {
80875                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
80876                         // for a sync iterable in an async context, only use the cached types if they are valid.
80877                         if (iterationTypes !== noIterationTypes) {
80878                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
80879                         }
80880                     }
80881                     else {
80882                         return iterationTypes;
80883                     }
80884                 }
80885             }
80886             if (use & 2 /* AllowsAsyncIterablesFlag */) {
80887                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
80888                 if (iterationTypes !== noIterationTypes) {
80889                     return iterationTypes;
80890                 }
80891             }
80892             if (use & 1 /* AllowsSyncIterablesFlag */) {
80893                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
80894                 if (iterationTypes !== noIterationTypes) {
80895                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
80896                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
80897                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
80898                             : noIterationTypes);
80899                     }
80900                     else {
80901                         return iterationTypes;
80902                     }
80903                 }
80904             }
80905             return noIterationTypes;
80906         }
80907         /**
80908          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
80909          * `AsyncIterable`-like type from the cache.
80910          *
80911          * NOTE: You probably don't want to call this directly and should be calling
80912          * `getIterationTypesOfIterable` instead.
80913          */
80914         function getIterationTypesOfIterableCached(type, resolver) {
80915             return getCachedIterationTypes(type, resolver.iterableCacheKey);
80916         }
80917         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
80918             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
80919                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
80920             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
80921         }
80922         /**
80923          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
80924          * type from from common heuristics.
80925          *
80926          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
80927          * returned. If we found iteration types, an `IterationTypes` record is returned.
80928          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
80929          * exhaustive analysis.
80930          *
80931          * NOTE: You probably don't want to call this directly and should be calling
80932          * `getIterationTypesOfIterable` instead.
80933          */
80934         function getIterationTypesOfIterableFast(type, resolver) {
80935             // As an optimization, if the type is an instantiation of one of the following global types, then
80936             // just grab its related type argument:
80937             // - `Iterable<T>` or `AsyncIterable<T>`
80938             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
80939             var globalType;
80940             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
80941                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
80942                 var yieldType = getTypeArguments(type)[0];
80943                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
80944                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
80945                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
80946                 // different definitions.
80947                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
80948                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || yieldType, resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || returnType, nextType));
80949             }
80950             // As an optimization, if the type is an instantiation of the following global type, then
80951             // just grab its related type arguments:
80952             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
80953             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
80954                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
80955                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || yieldType, resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || returnType, nextType));
80956             }
80957         }
80958         function getPropertyNameForKnownSymbolName(symbolName) {
80959             var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
80960             var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName));
80961             return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@".concat(symbolName);
80962         }
80963         /**
80964          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
80965          * type from its members.
80966          *
80967          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
80968          * record is returned. Otherwise, `noIterationTypes` is returned.
80969          *
80970          * NOTE: You probably don't want to call this directly and should be calling
80971          * `getIterationTypesOfIterable` instead.
80972          */
80973         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
80974             var _a;
80975             var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
80976             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
80977             if (isTypeAny(methodType)) {
80978                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
80979             }
80980             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
80981             if (!ts.some(signatures)) {
80982                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
80983             }
80984             var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature));
80985             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
80986             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
80987         }
80988         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
80989             var message = allowAsyncIterables
80990                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
80991                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
80992             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
80993         }
80994         /**
80995          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
80996          *
80997          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
80998          * record is returned. Otherwise, `undefined` is returned.
80999          */
81000         function getIterationTypesOfIterator(type, resolver, errorNode) {
81001             if (isTypeAny(type)) {
81002                 return anyIterationTypes;
81003             }
81004             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
81005                 getIterationTypesOfIteratorFast(type, resolver) ||
81006                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
81007             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
81008         }
81009         /**
81010          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
81011          * cache.
81012          *
81013          * NOTE: You probably don't want to call this directly and should be calling
81014          * `getIterationTypesOfIterator` instead.
81015          */
81016         function getIterationTypesOfIteratorCached(type, resolver) {
81017             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
81018         }
81019         /**
81020          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
81021          * cache or from common heuristics.
81022          *
81023          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
81024          * returned. If we found iteration types, an `IterationTypes` record is returned.
81025          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
81026          * exhaustive analysis.
81027          *
81028          * NOTE: You probably don't want to call this directly and should be calling
81029          * `getIterationTypesOfIterator` instead.
81030          */
81031         function getIterationTypesOfIteratorFast(type, resolver) {
81032             // As an optimization, if the type is an instantiation of one of the following global types,
81033             // then just grab its related type argument:
81034             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
81035             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
81036             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
81037             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
81038             if (isReferenceToType(type, globalType)) {
81039                 var yieldType = getTypeArguments(type)[0];
81040                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
81041                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
81042                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
81043                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
81044                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
81045                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
81046                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
81047             }
81048             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
81049                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
81050                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
81051                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
81052             }
81053         }
81054         function isIteratorResult(type, kind) {
81055             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
81056             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
81057             // > If the end was not reached `done` is `false` and a value is available.
81058             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
81059             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
81060             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
81061         }
81062         function isYieldIteratorResult(type) {
81063             return isIteratorResult(type, 0 /* Yield */);
81064         }
81065         function isReturnIteratorResult(type) {
81066             return isIteratorResult(type, 1 /* Return */);
81067         }
81068         /**
81069          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
81070          *
81071          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
81072          * returned to indicate to the caller that it should handle the error. Otherwise, an
81073          * `IterationTypes` record is returned.
81074          */
81075         function getIterationTypesOfIteratorResult(type) {
81076             if (isTypeAny(type)) {
81077                 return anyIterationTypes;
81078             }
81079             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
81080             if (cachedTypes) {
81081                 return cachedTypes;
81082             }
81083             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
81084             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
81085             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
81086                 var yieldType_1 = getTypeArguments(type)[0];
81087                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
81088             }
81089             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
81090                 var returnType_1 = getTypeArguments(type)[0];
81091                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
81092             }
81093             // Choose any constituents that can produce the requested iteration type.
81094             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
81095             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
81096             var returnIteratorResult = filterType(type, isReturnIteratorResult);
81097             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
81098             if (!yieldType && !returnType) {
81099                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
81100             }
81101             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
81102             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
81103             // > `value` property may be absent from the conforming object if it does not inherit an explicit
81104             // > `value` property.
81105             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
81106         }
81107         /**
81108          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
81109          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
81110          *
81111          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
81112          * record is returned. Otherwise, we return `undefined`.
81113          */
81114         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
81115             var _a, _b, _c, _d;
81116             var method = getPropertyOfType(type, methodName);
81117             // Ignore 'return' or 'throw' if they are missing.
81118             if (!method && methodName !== "next") {
81119                 return undefined;
81120             }
81121             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
81122                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
81123                 : undefined;
81124             if (isTypeAny(methodType)) {
81125                 // `return()` and `throw()` don't provide a *next* type.
81126                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
81127             }
81128             // Both async and non-async iterators *must* have a `next` method.
81129             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
81130             if (methodSignatures.length === 0) {
81131                 if (errorNode) {
81132                     var diagnostic = methodName === "next"
81133                         ? resolver.mustHaveANextMethodDiagnostic
81134                         : resolver.mustBeAMethodDiagnostic;
81135                     error(errorNode, diagnostic, methodName);
81136                 }
81137                 return methodName === "next" ? anyIterationTypes : undefined;
81138             }
81139             // If the method signature comes exclusively from the global iterator or generator type,
81140             // create iteration types from its type arguments like `getIterationTypesOfIteratorFast`
81141             // does (so as to remove `undefined` from the next and return types). We arrive here when
81142             // a contextual type for a generator was not a direct reference to one of those global types,
81143             // but looking up `methodType` referred to one of them (and nothing else). E.g., in
81144             // `interface SpecialIterator extends Iterator<number> {}`, `SpecialIterator` is not a
81145             // reference to `Iterator`, but its `next` member derives exclusively from `Iterator`.
81146             if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
81147                 var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
81148                 var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false);
81149                 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;
81150                 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;
81151                 if (isGeneratorMethod || isIteratorMethod) {
81152                     var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
81153                     var mapper = methodType.mapper;
81154                     return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : undefined);
81155                 }
81156             }
81157             // Extract the first parameter and return type of each signature.
81158             var methodParameterTypes;
81159             var methodReturnTypes;
81160             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
81161                 var signature = methodSignatures_1[_i];
81162                 if (methodName !== "throw" && ts.some(signature.parameters)) {
81163                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
81164                 }
81165                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
81166             }
81167             // Resolve the *next* or *return* type from the first parameter of a `next()` or
81168             // `return()` method, respectively.
81169             var returnTypes;
81170             var nextType;
81171             if (methodName !== "throw") {
81172                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
81173                 if (methodName === "next") {
81174                     // The value of `next(value)` is *not* awaited by async generators
81175                     nextType = methodParameterType;
81176                 }
81177                 else if (methodName === "return") {
81178                     // The value of `return(value)` *is* awaited by async generators
81179                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
81180                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
81181                 }
81182             }
81183             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
81184             var yieldType;
81185             var methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
81186             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
81187             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
81188             if (iterationTypes === noIterationTypes) {
81189                 if (errorNode) {
81190                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
81191                 }
81192                 yieldType = anyType;
81193                 returnTypes = ts.append(returnTypes, anyType);
81194             }
81195             else {
81196                 yieldType = iterationTypes.yieldType;
81197                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
81198             }
81199             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
81200         }
81201         /**
81202          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
81203          * type from its members.
81204          *
81205          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
81206          * record is returned. Otherwise, `noIterationTypes` is returned.
81207          *
81208          * NOTE: You probably don't want to call this directly and should be calling
81209          * `getIterationTypesOfIterator` instead.
81210          */
81211         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
81212             var iterationTypes = combineIterationTypes([
81213                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
81214                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
81215                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
81216             ]);
81217             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
81218         }
81219         /**
81220          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
81221          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
81222          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
81223          */
81224         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
81225             if (isTypeAny(returnType)) {
81226                 return undefined;
81227             }
81228             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
81229             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
81230         }
81231         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
81232             if (isTypeAny(type)) {
81233                 return anyIterationTypes;
81234             }
81235             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
81236             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
81237             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
81238                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
81239         }
81240         function checkBreakOrContinueStatement(node) {
81241             // Grammar checking
81242             if (!checkGrammarStatementInAmbientContext(node))
81243                 checkGrammarBreakOrContinueStatement(node);
81244             // TODO: Check that target label is valid
81245         }
81246         function unwrapReturnType(returnType, functionFlags) {
81247             var isGenerator = !!(functionFlags & 1 /* Generator */);
81248             var isAsync = !!(functionFlags & 2 /* Async */);
81249             return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType :
81250                 isAsync ? getAwaitedTypeNoAlias(returnType) || errorType :
81251                     returnType;
81252         }
81253         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
81254             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
81255             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
81256         }
81257         function checkReturnStatement(node) {
81258             var _a;
81259             // Grammar checking
81260             if (checkGrammarStatementInAmbientContext(node)) {
81261                 return;
81262             }
81263             var container = ts.getContainingFunctionOrClassStaticBlock(node);
81264             if (container && ts.isClassStaticBlockDeclaration(container)) {
81265                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block);
81266                 return;
81267             }
81268             if (!container) {
81269                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
81270                 return;
81271             }
81272             var signature = getSignatureFromDeclaration(container);
81273             var returnType = getReturnTypeOfSignature(signature);
81274             var functionFlags = ts.getFunctionFlags(container);
81275             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
81276                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
81277                 if (container.kind === 172 /* SetAccessor */) {
81278                     if (node.expression) {
81279                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
81280                     }
81281                 }
81282                 else if (container.kind === 170 /* Constructor */) {
81283                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
81284                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
81285                     }
81286                 }
81287                 else if (getReturnTypeFromAnnotation(container)) {
81288                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
81289                     var unwrappedExprType = functionFlags & 2 /* Async */
81290                         ? checkAwaitedType(exprType, /*withAlias*/ false, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
81291                         : exprType;
81292                     if (unwrappedReturnType) {
81293                         // If the function has a return type, but promisedType is
81294                         // undefined, an error will be reported in checkAsyncFunctionReturnType
81295                         // so we don't need to report one here.
81296                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
81297                     }
81298                 }
81299             }
81300             else if (container.kind !== 170 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(container, returnType)) {
81301                 // The function has a return type, but the return statement doesn't have an expression.
81302                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
81303             }
81304         }
81305         function checkWithStatement(node) {
81306             // Grammar checking for withStatement
81307             if (!checkGrammarStatementInAmbientContext(node)) {
81308                 if (node.flags & 32768 /* AwaitContext */) {
81309                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
81310                 }
81311             }
81312             checkExpression(node.expression);
81313             var sourceFile = ts.getSourceFileOfNode(node);
81314             if (!hasParseDiagnostics(sourceFile)) {
81315                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
81316                 var end = node.statement.pos;
81317                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
81318             }
81319         }
81320         function checkSwitchStatement(node) {
81321             // Grammar checking
81322             checkGrammarStatementInAmbientContext(node);
81323             var firstDefaultClause;
81324             var hasDuplicateDefaultClause = false;
81325             var expressionType = checkExpression(node.expression);
81326             var expressionIsLiteral = isLiteralType(expressionType);
81327             ts.forEach(node.caseBlock.clauses, function (clause) {
81328                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
81329                 if (clause.kind === 289 /* DefaultClause */ && !hasDuplicateDefaultClause) {
81330                     if (firstDefaultClause === undefined) {
81331                         firstDefaultClause = clause;
81332                     }
81333                     else {
81334                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
81335                         hasDuplicateDefaultClause = true;
81336                     }
81337                 }
81338                 if (produceDiagnostics && clause.kind === 288 /* CaseClause */) {
81339                     // TypeScript 1.0 spec (April 2014): 5.9
81340                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
81341                     // to or from the type of the 'switch' expression.
81342                     var caseType = checkExpression(clause.expression);
81343                     var caseIsLiteral = isLiteralType(caseType);
81344                     var comparedExpressionType = expressionType;
81345                     if (!caseIsLiteral || !expressionIsLiteral) {
81346                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
81347                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
81348                     }
81349                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
81350                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
81351                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
81352                     }
81353                 }
81354                 ts.forEach(clause.statements, checkSourceElement);
81355                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
81356                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
81357                 }
81358             });
81359             if (node.caseBlock.locals) {
81360                 registerForUnusedIdentifiersCheck(node.caseBlock);
81361             }
81362         }
81363         function checkLabeledStatement(node) {
81364             // Grammar checking
81365             if (!checkGrammarStatementInAmbientContext(node)) {
81366                 ts.findAncestor(node.parent, function (current) {
81367                     if (ts.isFunctionLike(current)) {
81368                         return "quit";
81369                     }
81370                     if (current.kind === 249 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
81371                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
81372                         return true;
81373                     }
81374                     return false;
81375                 });
81376             }
81377             // ensure that label is unique
81378             checkSourceElement(node.statement);
81379         }
81380         function checkThrowStatement(node) {
81381             // Grammar checking
81382             if (!checkGrammarStatementInAmbientContext(node)) {
81383                 if (ts.isIdentifier(node.expression) && !node.expression.escapedText) {
81384                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
81385                 }
81386             }
81387             if (node.expression) {
81388                 checkExpression(node.expression);
81389             }
81390         }
81391         function checkTryStatement(node) {
81392             // Grammar checking
81393             checkGrammarStatementInAmbientContext(node);
81394             checkBlock(node.tryBlock);
81395             var catchClause = node.catchClause;
81396             if (catchClause) {
81397                 // Grammar checking
81398                 if (catchClause.variableDeclaration) {
81399                     var declaration = catchClause.variableDeclaration;
81400                     var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration));
81401                     if (typeNode) {
81402                         var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false);
81403                         if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
81404                             grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
81405                         }
81406                     }
81407                     else if (declaration.initializer) {
81408                         grammarErrorOnFirstToken(declaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
81409                     }
81410                     else {
81411                         var blockLocals_1 = catchClause.block.locals;
81412                         if (blockLocals_1) {
81413                             ts.forEachKey(catchClause.locals, function (caughtName) {
81414                                 var blockLocal = blockLocals_1.get(caughtName);
81415                                 if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
81416                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
81417                                 }
81418                             });
81419                         }
81420                     }
81421                 }
81422                 checkBlock(catchClause.block);
81423             }
81424             if (node.finallyBlock) {
81425                 checkBlock(node.finallyBlock);
81426             }
81427         }
81428         function checkIndexConstraints(type, symbol, isStaticIndex) {
81429             var indexInfos = getIndexInfosOfType(type);
81430             if (indexInfos.length === 0) {
81431                 return;
81432             }
81433             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
81434                 var prop = _a[_i];
81435                 if (!(isStaticIndex && prop.flags & 4194304 /* Prototype */)) {
81436                     checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop));
81437                 }
81438             }
81439             var typeDeclaration = symbol.valueDeclaration;
81440             if (typeDeclaration && ts.isClassLike(typeDeclaration)) {
81441                 for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) {
81442                     var member = _c[_b];
81443                     // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers,
81444                     // and properties with literal names were already checked.
81445                     if (!ts.isStatic(member) && !hasBindableName(member)) {
81446                         var symbol_3 = getSymbolOfNode(member);
81447                         checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3));
81448                     }
81449                 }
81450             }
81451             if (indexInfos.length > 1) {
81452                 for (var _d = 0, indexInfos_6 = indexInfos; _d < indexInfos_6.length; _d++) {
81453                     var info = indexInfos_6[_d];
81454                     checkIndexConstraintForIndexSignature(type, info);
81455                 }
81456             }
81457         }
81458         function checkIndexConstraintForProperty(type, prop, propNameType, propType) {
81459             var declaration = prop.valueDeclaration;
81460             var name = ts.getNameOfDeclaration(declaration);
81461             if (name && ts.isPrivateIdentifier(name)) {
81462                 return;
81463             }
81464             var indexInfos = getApplicableIndexInfos(type, propNameType);
81465             var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* Interface */ ? ts.getDeclarationOfKind(type.symbol, 257 /* InterfaceDeclaration */) : undefined;
81466             var localPropDeclaration = declaration && declaration.kind === 220 /* BinaryExpression */ ||
81467                 name && name.kind === 161 /* ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined;
81468             var _loop_27 = function (info) {
81469                 var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined;
81470                 // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared
81471                 // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and
81472                 // the index signature (i.e. property and index signature are declared in separate inherited interfaces).
81473                 var errorNode = localPropDeclaration || localIndexDeclaration ||
81474                     (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined);
81475                 if (errorNode && !isTypeAssignableTo(propType, info.type)) {
81476                     error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type));
81477                 }
81478             };
81479             for (var _i = 0, indexInfos_7 = indexInfos; _i < indexInfos_7.length; _i++) {
81480                 var info = indexInfos_7[_i];
81481                 _loop_27(info);
81482             }
81483         }
81484         function checkIndexConstraintForIndexSignature(type, checkInfo) {
81485             var declaration = checkInfo.declaration;
81486             var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType);
81487             var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* Interface */ ? ts.getDeclarationOfKind(type.symbol, 257 /* InterfaceDeclaration */) : undefined;
81488             var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined;
81489             var _loop_28 = function (info) {
81490                 if (info === checkInfo)
81491                     return "continue";
81492                 var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined;
81493                 // We check only when (a) the check index signature is declared in the containing type, or (b) the applicable index
81494                 // signature is declared in the containing type, or (c) the containing type is an interface and no base interface contains
81495                 // both index signatures (i.e. the index signatures are declared in separate inherited interfaces).
81496                 var errorNode = localCheckDeclaration || localIndexDeclaration ||
81497                     (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined);
81498                 if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) {
81499                     error(errorNode, ts.Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type));
81500                 }
81501             };
81502             for (var _i = 0, indexInfos_8 = indexInfos; _i < indexInfos_8.length; _i++) {
81503                 var info = indexInfos_8[_i];
81504                 _loop_28(info);
81505             }
81506         }
81507         function checkTypeNameIsReserved(name, message) {
81508             // TS 1.0 spec (April 2014): 3.6.1
81509             // The predefined type keywords are reserved and cannot be used as names of user defined types.
81510             switch (name.escapedText) {
81511                 case "any":
81512                 case "unknown":
81513                 case "never":
81514                 case "number":
81515                 case "bigint":
81516                 case "boolean":
81517                 case "string":
81518                 case "symbol":
81519                 case "void":
81520                 case "object":
81521                     error(name, message, name.escapedText);
81522             }
81523         }
81524         /**
81525          * The name cannot be used as 'Object' of user defined types with special target.
81526          */
81527         function checkClassNameCollisionWithObject(name) {
81528             if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object"
81529                 && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(name).impliedNodeFormat === ts.ModuleKind.CommonJS)) {
81530                 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
81531             }
81532         }
81533         /**
81534          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
81535          */
81536         function checkTypeParameters(typeParameterDeclarations) {
81537             if (typeParameterDeclarations) {
81538                 var seenDefault = false;
81539                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
81540                     var node = typeParameterDeclarations[i];
81541                     checkTypeParameter(node);
81542                     if (produceDiagnostics) {
81543                         if (node.default) {
81544                             seenDefault = true;
81545                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
81546                         }
81547                         else if (seenDefault) {
81548                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
81549                         }
81550                         for (var j = 0; j < i; j++) {
81551                             if (typeParameterDeclarations[j].symbol === node.symbol) {
81552                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
81553                             }
81554                         }
81555                     }
81556                 }
81557             }
81558         }
81559         /** Check that type parameter defaults only reference previously declared type parameters */
81560         function checkTypeParametersNotReferenced(root, typeParameters, index) {
81561             visit(root);
81562             function visit(node) {
81563                 if (node.kind === 177 /* TypeReference */) {
81564                     var type = getTypeFromTypeReference(node);
81565                     if (type.flags & 262144 /* TypeParameter */) {
81566                         for (var i = index; i < typeParameters.length; i++) {
81567                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
81568                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
81569                             }
81570                         }
81571                     }
81572                 }
81573                 ts.forEachChild(node, visit);
81574             }
81575         }
81576         /** Check that type parameter lists are identical across multiple declarations */
81577         function checkTypeParameterListsIdentical(symbol) {
81578             if (symbol.declarations && symbol.declarations.length === 1) {
81579                 return;
81580             }
81581             var links = getSymbolLinks(symbol);
81582             if (!links.typeParametersChecked) {
81583                 links.typeParametersChecked = true;
81584                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
81585                 if (!declarations || declarations.length <= 1) {
81586                     return;
81587                 }
81588                 var type = getDeclaredTypeOfSymbol(symbol);
81589                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
81590                     // Report an error on every conflicting declaration.
81591                     var name = symbolToString(symbol);
81592                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
81593                         var declaration = declarations_6[_i];
81594                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
81595                     }
81596                 }
81597             }
81598         }
81599         function areTypeParametersIdentical(declarations, targetParameters) {
81600             var maxTypeArgumentCount = ts.length(targetParameters);
81601             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
81602             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
81603                 var declaration = declarations_7[_i];
81604                 // If this declaration has too few or too many type parameters, we report an error
81605                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
81606                 var numTypeParameters = sourceParameters.length;
81607                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
81608                     return false;
81609                 }
81610                 for (var i = 0; i < numTypeParameters; i++) {
81611                     var source = sourceParameters[i];
81612                     var target = targetParameters[i];
81613                     // If the type parameter node does not have the same as the resolved type
81614                     // parameter at this position, we report an error.
81615                     if (source.name.escapedText !== target.symbol.escapedName) {
81616                         return false;
81617                     }
81618                     // If the type parameter node does not have an identical constraint as the resolved
81619                     // type parameter at this position, we report an error.
81620                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
81621                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
81622                     var targetConstraint = getConstraintOfTypeParameter(target);
81623                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
81624                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
81625                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
81626                         return false;
81627                     }
81628                     // If the type parameter node has a default and it is not identical to the default
81629                     // for the type parameter at this position, we report an error.
81630                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
81631                     var targetDefault = getDefaultFromTypeParameter(target);
81632                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
81633                         return false;
81634                     }
81635                 }
81636             }
81637             return true;
81638         }
81639         function checkClassExpression(node) {
81640             checkClassLikeDeclaration(node);
81641             checkNodeDeferred(node);
81642             return getTypeOfSymbol(getSymbolOfNode(node));
81643         }
81644         function checkClassExpressionDeferred(node) {
81645             ts.forEach(node.members, checkSourceElement);
81646             registerForUnusedIdentifiersCheck(node);
81647         }
81648         function checkClassDeclaration(node) {
81649             if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) {
81650                 grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator);
81651             }
81652             if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) {
81653                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
81654             }
81655             checkClassLikeDeclaration(node);
81656             ts.forEach(node.members, checkSourceElement);
81657             registerForUnusedIdentifiersCheck(node);
81658         }
81659         function checkClassLikeDeclaration(node) {
81660             checkGrammarClassLikeDeclaration(node);
81661             checkDecorators(node);
81662             checkCollisionsForDeclarationName(node, node.name);
81663             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
81664             checkExportsOnMergedDeclarations(node);
81665             var symbol = getSymbolOfNode(node);
81666             var type = getDeclaredTypeOfSymbol(symbol);
81667             var typeWithThis = getTypeWithThisArgument(type);
81668             var staticType = getTypeOfSymbol(symbol);
81669             checkTypeParameterListsIdentical(symbol);
81670             checkFunctionOrConstructorSymbol(symbol);
81671             checkClassForDuplicateDeclarations(node);
81672             // Only check for reserved static identifiers on non-ambient context.
81673             var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */);
81674             if (!nodeInAmbientContext) {
81675                 checkClassForStaticPropertyNameConflicts(node);
81676             }
81677             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
81678             if (baseTypeNode) {
81679                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
81680                 if (languageVersion < 2 /* ES2015 */) {
81681                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
81682                 }
81683                 // check both @extends and extends if both are specified.
81684                 var extendsNode = ts.getClassExtendsHeritageElement(node);
81685                 if (extendsNode && extendsNode !== baseTypeNode) {
81686                     checkExpression(extendsNode.expression);
81687                 }
81688                 var baseTypes = getBaseTypes(type);
81689                 if (baseTypes.length && produceDiagnostics) {
81690                     var baseType_1 = baseTypes[0];
81691                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
81692                     var staticBaseType = getApparentType(baseConstructorType);
81693                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
81694                     checkSourceElement(baseTypeNode.expression);
81695                     if (ts.some(baseTypeNode.typeArguments)) {
81696                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
81697                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
81698                             var constructor = _a[_i];
81699                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
81700                                 break;
81701                             }
81702                         }
81703                     }
81704                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
81705                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
81706                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
81707                     }
81708                     else {
81709                         // Report static side error only when instance type is assignable
81710                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
81711                     }
81712                     if (baseConstructorType.flags & 8650752 /* TypeVariable */) {
81713                         if (!isMixinConstructorType(staticType)) {
81714                             error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
81715                         }
81716                         else {
81717                             var constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
81718                             if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; }) && !ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
81719                                 error(node.name || node, ts.Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract);
81720                             }
81721                         }
81722                     }
81723                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
81724                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
81725                         // that all instantiated base constructor signatures return the same type.
81726                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
81727                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
81728                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
81729                         }
81730                     }
81731                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
81732                 }
81733             }
81734             checkMembersForOverrideModifier(node, type, typeWithThis, staticType);
81735             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
81736             if (implementedTypeNodes) {
81737                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
81738                     var typeRefNode = implementedTypeNodes_1[_b];
81739                     if (!ts.isEntityNameExpression(typeRefNode.expression) || ts.isOptionalChain(typeRefNode.expression)) {
81740                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
81741                     }
81742                     checkTypeReferenceNode(typeRefNode);
81743                     if (produceDiagnostics) {
81744                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
81745                         if (!isErrorType(t)) {
81746                             if (isValidBaseType(t)) {
81747                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
81748                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
81749                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
81750                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
81751                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
81752                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
81753                                 }
81754                             }
81755                             else {
81756                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
81757                             }
81758                         }
81759                     }
81760                 }
81761             }
81762             if (produceDiagnostics) {
81763                 checkIndexConstraints(type, symbol);
81764                 checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true);
81765                 checkTypeForDuplicateIndexSignatures(node);
81766                 checkPropertyInitialization(node);
81767             }
81768         }
81769         function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) {
81770             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
81771             var baseTypes = baseTypeNode && getBaseTypes(type);
81772             var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined;
81773             var baseStaticType = getBaseConstructorTypeOfClass(type);
81774             var _loop_29 = function (member) {
81775                 if (ts.hasAmbientModifier(member)) {
81776                     return "continue";
81777                 }
81778                 if (ts.isConstructorDeclaration(member)) {
81779                     ts.forEach(member.parameters, function (param) {
81780                         if (ts.isParameterPropertyDeclaration(param, member)) {
81781                             checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, 
81782                             /* memberIsParameterProperty */ true);
81783                         }
81784                     });
81785                 }
81786                 checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, 
81787                 /* memberIsParameterProperty */ false);
81788             };
81789             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
81790                 var member = _a[_i];
81791                 _loop_29(member);
81792             }
81793         }
81794         /**
81795          * @param member Existing member node to be checked.
81796          * Note: `member` cannot be a synthetic node.
81797          */
81798         function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) {
81799             if (reportErrors === void 0) { reportErrors = true; }
81800             var declaredProp = member.name
81801                 && getSymbolAtLocation(member.name)
81802                 || getSymbolAtLocation(member);
81803             if (!declaredProp) {
81804                 return 0 /* Ok */;
81805             }
81806             return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined);
81807         }
81808         /**
81809          * Checks a class member declaration for either a missing or an invalid `override` modifier.
81810          * Note: this function can be used for speculative checking,
81811          * i.e. checking a member that does not yet exist in the program.
81812          * An example of that would be to call this function in a completions scenario,
81813          * when offering a method declaration as completion.
81814          * @param errorNode The node where we should report an error, or undefined if we should not report errors.
81815          */
81816         function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) {
81817             var isJs = ts.isInJSFile(node);
81818             var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */);
81819             if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) {
81820                 var memberEscapedName = ts.escapeLeadingUnderscores(memberName);
81821                 var thisType = memberIsStatic ? staticType : typeWithThis;
81822                 var baseType = memberIsStatic ? baseStaticType : baseWithThis;
81823                 var prop = getPropertyOfType(thisType, memberEscapedName);
81824                 var baseProp = getPropertyOfType(baseType, memberEscapedName);
81825                 var baseClassName = typeToString(baseWithThis);
81826                 if (prop && !baseProp && memberHasOverrideModifier) {
81827                     if (errorNode) {
81828                         var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName`
81829                         suggestion ?
81830                             error(errorNode, isJs ?
81831                                 ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 :
81832                                 ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) :
81833                             error(errorNode, isJs ?
81834                                 ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 :
81835                                 ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName);
81836                     }
81837                     return 2 /* HasInvalidOverride */;
81838                 }
81839                 else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) {
81840                     var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier);
81841                     if (memberHasOverrideModifier) {
81842                         return 0 /* Ok */;
81843                     }
81844                     if (!baseHasAbstract) {
81845                         if (errorNode) {
81846                             var diag = memberIsParameterProperty ?
81847                                 isJs ?
81848                                     ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 :
81849                                     ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 :
81850                                 isJs ?
81851                                     ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 :
81852                                     ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0;
81853                             error(errorNode, diag, baseClassName);
81854                         }
81855                         return 1 /* NeedsOverride */;
81856                     }
81857                     else if (memberHasAbstractModifier && baseHasAbstract) {
81858                         if (errorNode) {
81859                             error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName);
81860                         }
81861                         return 1 /* NeedsOverride */;
81862                     }
81863                 }
81864             }
81865             else if (memberHasOverrideModifier) {
81866                 if (errorNode) {
81867                     var className = typeToString(type);
81868                     error(errorNode, isJs ?
81869                         ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class :
81870                         ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className);
81871                 }
81872                 return 2 /* HasInvalidOverride */;
81873             }
81874             return 0 /* Ok */;
81875         }
81876         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
81877             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
81878             var issuedMemberError = false;
81879             var _loop_30 = function (member) {
81880                 if (ts.isStatic(member)) {
81881                     return "continue";
81882                 }
81883                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
81884                 if (declaredProp) {
81885                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
81886                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
81887                     if (prop && baseProp) {
81888                         var rootChain = function () { return ts.chainDiagnosticMessages(
81889                         /*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)); };
81890                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
81891                             issuedMemberError = true;
81892                         }
81893                     }
81894                 }
81895             };
81896             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
81897                 var member = _a[_i];
81898                 _loop_30(member);
81899             }
81900             if (!issuedMemberError) {
81901                 // check again with diagnostics to generate a less-specific error
81902                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
81903             }
81904         }
81905         function checkBaseTypeAccessibility(type, node) {
81906             var signatures = getSignaturesOfType(type, 1 /* Construct */);
81907             if (signatures.length) {
81908                 var declaration = signatures[0].declaration;
81909                 if (declaration && ts.hasEffectiveModifier(declaration, 8 /* Private */)) {
81910                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
81911                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
81912                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
81913                     }
81914                 }
81915             }
81916         }
81917         /**
81918          * Checks a member declaration node to see if has a missing or invalid `override` modifier.
81919          * @param node Class-like node where the member is declared.
81920          * @param member Member declaration node.
81921          * Note: `member` can be a synthetic node without a parent.
81922          */
81923         function getMemberOverrideModifierStatus(node, member) {
81924             if (!member.name) {
81925                 return 0 /* Ok */;
81926             }
81927             var symbol = getSymbolOfNode(node);
81928             var type = getDeclaredTypeOfSymbol(symbol);
81929             var typeWithThis = getTypeWithThisArgument(type);
81930             var staticType = getTypeOfSymbol(symbol);
81931             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
81932             var baseTypes = baseTypeNode && getBaseTypes(type);
81933             var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined;
81934             var baseStaticType = getBaseConstructorTypeOfClass(type);
81935             var memberHasOverrideModifier = member.parent
81936                 ? ts.hasOverrideModifier(member)
81937                 : ts.hasSyntacticModifier(member, 16384 /* Override */);
81938             var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name));
81939             return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), 
81940             /* memberIsParameterProperty */ false, memberName);
81941         }
81942         function getTargetSymbol(s) {
81943             // if symbol is instantiated its flags are not copied from the 'target'
81944             // so we'll need to get back original 'target' symbol to work with correct set of flags
81945             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
81946         }
81947         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
81948             return ts.filter(symbol.declarations, function (d) {
81949                 return d.kind === 256 /* ClassDeclaration */ || d.kind === 257 /* InterfaceDeclaration */;
81950             });
81951         }
81952         function checkKindsOfPropertyMemberOverrides(type, baseType) {
81953             // TypeScript 1.0 spec (April 2014): 8.2.3
81954             // A derived class inherits all members from its base class it doesn't override.
81955             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
81956             // Both public and private property members are inherited, but only public property members can be overridden.
81957             // A property member in a derived class is said to override a property member in a base class
81958             // when the derived class property member has the same name and kind(instance or static)
81959             // as the base class property member.
81960             // The type of an overriding property member must be assignable(section 3.8.4)
81961             // to the type of the overridden property member, or otherwise a compile - time error occurs.
81962             // Base class instance member functions can be overridden by derived class instance member functions,
81963             // but not by other kinds of members.
81964             // Base class instance member variables and accessors can be overridden by
81965             // derived class instance member variables and accessors, but not by other kinds of members.
81966             var _a, _b;
81967             // NOTE: assignability is checked in checkClassDeclaration
81968             var baseProperties = getPropertiesOfType(baseType);
81969             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
81970                 var baseProperty = baseProperties_1[_i];
81971                 var base = getTargetSymbol(baseProperty);
81972                 if (base.flags & 4194304 /* Prototype */) {
81973                     continue;
81974                 }
81975                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
81976                 if (!baseSymbol) {
81977                     continue;
81978                 }
81979                 var derived = getTargetSymbol(baseSymbol);
81980                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
81981                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
81982                 // In order to resolve whether the inherited method was overridden in the base class or not,
81983                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
81984                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
81985                 if (derived === base) {
81986                     // derived class inherits base without override/redeclaration
81987                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
81988                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
81989                     // If there is no declaration for the derived class (as in the case of class expressions),
81990                     // then the class cannot be declared abstract.
81991                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* Abstract */))) {
81992                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
81993                         // (The class may have more than one base type via declaration merging with an interface with the
81994                         // same name.)
81995                         for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) {
81996                             var otherBaseType = _d[_c];
81997                             if (otherBaseType === baseType)
81998                                 continue;
81999                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
82000                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
82001                             if (derivedElsewhere && derivedElsewhere !== base) {
82002                                 continue basePropertyCheck;
82003                             }
82004                         }
82005                         if (derivedClassDecl.kind === 225 /* ClassExpression */) {
82006                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
82007                         }
82008                         else {
82009                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
82010                         }
82011                     }
82012                 }
82013                 else {
82014                     // derived overrides base.
82015                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
82016                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
82017                         // either base or derived property is private - not override, skip it
82018                         continue;
82019                     }
82020                     var errorMessage = void 0;
82021                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
82022                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
82023                     if (basePropertyFlags && derivedPropertyFlags) {
82024                         // property/accessor is overridden with property/accessor
82025                         if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
82026                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 257 /* InterfaceDeclaration */
82027                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
82028                             // when the base property is abstract or from an interface, base/derived flags don't need to match
82029                             // same when the derived property is from an assignment
82030                             continue;
82031                         }
82032                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
82033                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
82034                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
82035                             var errorMessage_1 = overriddenInstanceProperty ?
82036                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
82037                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
82038                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
82039                         }
82040                         else if (useDefineForClassFields) {
82041                             var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 166 /* PropertyDeclaration */ && !d.initializer; });
82042                             if (uninitialized
82043                                 && !(derived.flags & 33554432 /* Transient */)
82044                                 && !(baseDeclarationFlags & 128 /* Abstract */)
82045                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
82046                                 && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) {
82047                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
82048                                 var propName = uninitialized.name;
82049                                 if (uninitialized.exclamationToken
82050                                     || !constructor
82051                                     || !ts.isIdentifier(propName)
82052                                     || !strictNullChecks
82053                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
82054                                     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;
82055                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
82056                                 }
82057                             }
82058                         }
82059                         // correct case
82060                         continue;
82061                     }
82062                     else if (isPrototypeProperty(base)) {
82063                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
82064                             // method is overridden with method or property -- correct case
82065                             continue;
82066                         }
82067                         else {
82068                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
82069                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
82070                         }
82071                     }
82072                     else if (base.flags & 98304 /* Accessor */) {
82073                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
82074                     }
82075                     else {
82076                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
82077                     }
82078                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
82079                 }
82080             }
82081         }
82082         function getNonInterhitedProperties(type, baseTypes, properties) {
82083             if (!ts.length(baseTypes)) {
82084                 return properties;
82085             }
82086             var seen = new ts.Map();
82087             ts.forEach(properties, function (p) {
82088                 seen.set(p.escapedName, p);
82089             });
82090             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
82091                 var base = baseTypes_2[_i];
82092                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
82093                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
82094                     var prop = properties_4[_a];
82095                     var existing = seen.get(prop.escapedName);
82096                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
82097                         seen.delete(prop.escapedName);
82098                     }
82099                 }
82100             }
82101             return ts.arrayFrom(seen.values());
82102         }
82103         function checkInheritedPropertiesAreIdentical(type, typeNode) {
82104             var baseTypes = getBaseTypes(type);
82105             if (baseTypes.length < 2) {
82106                 return true;
82107             }
82108             var seen = new ts.Map();
82109             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) {
82110                 seen.set(p.escapedName, { prop: p, containingType: type });
82111             });
82112             var ok = true;
82113             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
82114                 var base = baseTypes_3[_i];
82115                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
82116                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
82117                     var prop = properties_6[_a];
82118                     var existing = seen.get(prop.escapedName);
82119                     if (!existing) {
82120                         seen.set(prop.escapedName, { prop: prop, containingType: base });
82121                     }
82122                     else {
82123                         var isInheritedProperty = existing.containingType !== type;
82124                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
82125                             ok = false;
82126                             var typeName1 = typeToString(existing.containingType);
82127                             var typeName2 = typeToString(base);
82128                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
82129                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
82130                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
82131                         }
82132                     }
82133                 }
82134             }
82135             return ok;
82136         }
82137         function checkPropertyInitialization(node) {
82138             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
82139                 return;
82140             }
82141             var constructor = findConstructorDeclaration(node);
82142             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
82143                 var member = _a[_i];
82144                 if (ts.getEffectiveModifierFlags(member) & 2 /* Ambient */) {
82145                     continue;
82146                 }
82147                 if (!ts.isStatic(member) && isPropertyWithoutInitializer(member)) {
82148                     var propName = member.name;
82149                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
82150                         var type = getTypeOfSymbol(getSymbolOfNode(member));
82151                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
82152                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
82153                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
82154                             }
82155                         }
82156                     }
82157                 }
82158             }
82159         }
82160         function isPropertyWithoutInitializer(node) {
82161             return node.kind === 166 /* PropertyDeclaration */ &&
82162                 !ts.hasAbstractModifier(node) &&
82163                 !node.exclamationToken &&
82164                 !node.initializer;
82165         }
82166         function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) {
82167             for (var _i = 0, staticBlocks_2 = staticBlocks; _i < staticBlocks_2.length; _i++) {
82168                 var staticBlock = staticBlocks_2[_i];
82169                 // static block must be within the provided range as they are evaluated in document order (unlike constructors)
82170                 if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) {
82171                     var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
82172                     ts.setParent(reference.expression, reference);
82173                     ts.setParent(reference, staticBlock);
82174                     reference.flowNode = staticBlock.returnFlowNode;
82175                     var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
82176                     if (!(getFalsyFlags(flowType) & 32768 /* Undefined */)) {
82177                         return true;
82178                     }
82179                 }
82180             }
82181             return false;
82182         }
82183         function isPropertyInitializedInConstructor(propName, propType, constructor) {
82184             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
82185             ts.setParent(reference.expression, reference);
82186             ts.setParent(reference, constructor);
82187             reference.flowNode = constructor.returnFlowNode;
82188             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
82189             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
82190         }
82191         function checkInterfaceDeclaration(node) {
82192             // Grammar checking
82193             if (!checkGrammarDecoratorsAndModifiers(node))
82194                 checkGrammarInterfaceDeclaration(node);
82195             checkTypeParameters(node.typeParameters);
82196             if (produceDiagnostics) {
82197                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
82198                 checkExportsOnMergedDeclarations(node);
82199                 var symbol = getSymbolOfNode(node);
82200                 checkTypeParameterListsIdentical(symbol);
82201                 // Only check this symbol once
82202                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 257 /* InterfaceDeclaration */);
82203                 if (node === firstInterfaceDecl) {
82204                     var type = getDeclaredTypeOfSymbol(symbol);
82205                     var typeWithThis = getTypeWithThisArgument(type);
82206                     // run subsequent checks only if first set succeeded
82207                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
82208                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
82209                             var baseType = _a[_i];
82210                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
82211                         }
82212                         checkIndexConstraints(type, symbol);
82213                     }
82214                 }
82215                 checkObjectTypeForDuplicateDeclarations(node);
82216             }
82217             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
82218                 if (!ts.isEntityNameExpression(heritageElement.expression) || ts.isOptionalChain(heritageElement.expression)) {
82219                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
82220                 }
82221                 checkTypeReferenceNode(heritageElement);
82222             });
82223             ts.forEach(node.members, checkSourceElement);
82224             if (produceDiagnostics) {
82225                 checkTypeForDuplicateIndexSignatures(node);
82226                 registerForUnusedIdentifiersCheck(node);
82227             }
82228         }
82229         function checkTypeAliasDeclaration(node) {
82230             // Grammar checking
82231             checkGrammarDecoratorsAndModifiers(node);
82232             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
82233             checkExportsOnMergedDeclarations(node);
82234             checkTypeParameters(node.typeParameters);
82235             if (node.type.kind === 138 /* IntrinsicKeyword */) {
82236                 if (!intrinsicTypeKinds.has(node.name.escapedText) || ts.length(node.typeParameters) !== 1) {
82237                     error(node.type, ts.Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
82238                 }
82239             }
82240             else {
82241                 checkSourceElement(node.type);
82242                 registerForUnusedIdentifiersCheck(node);
82243             }
82244         }
82245         function computeEnumMemberValues(node) {
82246             var nodeLinks = getNodeLinks(node);
82247             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
82248                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
82249                 var autoValue = 0;
82250                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
82251                     var member = _a[_i];
82252                     var value = computeMemberValue(member, autoValue);
82253                     getNodeLinks(member).enumMemberValue = value;
82254                     autoValue = typeof value === "number" ? value + 1 : undefined;
82255                 }
82256             }
82257         }
82258         function computeMemberValue(member, autoValue) {
82259             if (ts.isComputedNonLiteralName(member.name)) {
82260                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
82261             }
82262             else {
82263                 var text = ts.getTextOfPropertyName(member.name);
82264                 if (isNumericLiteralName(text) && !ts.isInfinityOrNaNString(text)) {
82265                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
82266                 }
82267             }
82268             if (member.initializer) {
82269                 return computeConstantValue(member);
82270             }
82271             // In ambient non-const numeric enum declarations, enum members without initializers are
82272             // considered computed members (as opposed to having auto-incremented values).
82273             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
82274                 return undefined;
82275             }
82276             // If the member declaration specifies no value, the member is considered a constant enum member.
82277             // If the member is the first member in the enum declaration, it is assigned the value zero.
82278             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
82279             // occurs if the immediately preceding member is not a constant enum member.
82280             if (autoValue !== undefined) {
82281                 return autoValue;
82282             }
82283             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
82284             return undefined;
82285         }
82286         function computeConstantValue(member) {
82287             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
82288             var isConstEnum = ts.isEnumConst(member.parent);
82289             var initializer = member.initializer;
82290             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
82291             if (value !== undefined) {
82292                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
82293                     error(initializer, isNaN(value) ?
82294                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
82295                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
82296                 }
82297             }
82298             else if (enumKind === 1 /* Literal */) {
82299                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
82300                 return 0;
82301             }
82302             else if (isConstEnum) {
82303                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
82304             }
82305             else if (member.parent.flags & 8388608 /* Ambient */) {
82306                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
82307             }
82308             else {
82309                 // Only here do we need to check that the initializer is assignable to the enum type.
82310                 var source = checkExpression(initializer);
82311                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
82312                     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));
82313                 }
82314                 else {
82315                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
82316                 }
82317             }
82318             return value;
82319             function evaluate(expr) {
82320                 switch (expr.kind) {
82321                     case 218 /* PrefixUnaryExpression */:
82322                         var value_2 = evaluate(expr.operand);
82323                         if (typeof value_2 === "number") {
82324                             switch (expr.operator) {
82325                                 case 39 /* PlusToken */: return value_2;
82326                                 case 40 /* MinusToken */: return -value_2;
82327                                 case 54 /* TildeToken */: return ~value_2;
82328                             }
82329                         }
82330                         break;
82331                     case 220 /* BinaryExpression */:
82332                         var left = evaluate(expr.left);
82333                         var right = evaluate(expr.right);
82334                         if (typeof left === "number" && typeof right === "number") {
82335                             switch (expr.operatorToken.kind) {
82336                                 case 51 /* BarToken */: return left | right;
82337                                 case 50 /* AmpersandToken */: return left & right;
82338                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
82339                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
82340                                 case 47 /* LessThanLessThanToken */: return left << right;
82341                                 case 52 /* CaretToken */: return left ^ right;
82342                                 case 41 /* AsteriskToken */: return left * right;
82343                                 case 43 /* SlashToken */: return left / right;
82344                                 case 39 /* PlusToken */: return left + right;
82345                                 case 40 /* MinusToken */: return left - right;
82346                                 case 44 /* PercentToken */: return left % right;
82347                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
82348                             }
82349                         }
82350                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
82351                             return left + right;
82352                         }
82353                         break;
82354                     case 10 /* StringLiteral */:
82355                     case 14 /* NoSubstitutionTemplateLiteral */:
82356                         return expr.text;
82357                     case 8 /* NumericLiteral */:
82358                         checkGrammarNumericLiteral(expr);
82359                         return +expr.text;
82360                     case 211 /* ParenthesizedExpression */:
82361                         return evaluate(expr.expression);
82362                     case 79 /* Identifier */:
82363                         var identifier = expr;
82364                         if (ts.isInfinityOrNaNString(identifier.escapedText)) {
82365                             return +(identifier.escapedText);
82366                         }
82367                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
82368                     case 206 /* ElementAccessExpression */:
82369                     case 205 /* PropertyAccessExpression */:
82370                         var ex = expr;
82371                         if (isConstantMemberAccess(ex)) {
82372                             var type = getTypeOfExpression(ex.expression);
82373                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
82374                                 var name = void 0;
82375                                 if (ex.kind === 205 /* PropertyAccessExpression */) {
82376                                     name = ex.name.escapedText;
82377                                 }
82378                                 else {
82379                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
82380                                 }
82381                                 return evaluateEnumMember(expr, type.symbol, name);
82382                             }
82383                         }
82384                         break;
82385                 }
82386                 return undefined;
82387             }
82388             function evaluateEnumMember(expr, enumSymbol, name) {
82389                 var memberSymbol = enumSymbol.exports.get(name);
82390                 if (memberSymbol) {
82391                     var declaration = memberSymbol.valueDeclaration;
82392                     if (declaration !== member) {
82393                         if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
82394                             return getEnumMemberValue(declaration);
82395                         }
82396                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
82397                         return 0;
82398                     }
82399                     else {
82400                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
82401                     }
82402                 }
82403                 return undefined;
82404             }
82405         }
82406         function isConstantMemberAccess(node) {
82407             return node.kind === 79 /* Identifier */ ||
82408                 node.kind === 205 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
82409                 node.kind === 206 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
82410                     ts.isStringLiteralLike(node.argumentExpression);
82411         }
82412         function checkEnumDeclaration(node) {
82413             if (!produceDiagnostics) {
82414                 return;
82415             }
82416             // Grammar checking
82417             checkGrammarDecoratorsAndModifiers(node);
82418             checkCollisionsForDeclarationName(node, node.name);
82419             checkExportsOnMergedDeclarations(node);
82420             node.members.forEach(checkEnumMember);
82421             computeEnumMemberValues(node);
82422             // Spec 2014 - Section 9.3:
82423             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
82424             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
82425             // for the first member.
82426             //
82427             // Only perform this check once per symbol
82428             var enumSymbol = getSymbolOfNode(node);
82429             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
82430             if (node === firstDeclaration) {
82431                 if (enumSymbol.declarations && enumSymbol.declarations.length > 1) {
82432                     var enumIsConst_1 = ts.isEnumConst(node);
82433                     // check that const is placed\omitted on all enum declarations
82434                     ts.forEach(enumSymbol.declarations, function (decl) {
82435                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
82436                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
82437                         }
82438                     });
82439                 }
82440                 var seenEnumMissingInitialInitializer_1 = false;
82441                 ts.forEach(enumSymbol.declarations, function (declaration) {
82442                     // return true if we hit a violation of the rule, false otherwise
82443                     if (declaration.kind !== 259 /* EnumDeclaration */) {
82444                         return false;
82445                     }
82446                     var enumDeclaration = declaration;
82447                     if (!enumDeclaration.members.length) {
82448                         return false;
82449                     }
82450                     var firstEnumMember = enumDeclaration.members[0];
82451                     if (!firstEnumMember.initializer) {
82452                         if (seenEnumMissingInitialInitializer_1) {
82453                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
82454                         }
82455                         else {
82456                             seenEnumMissingInitialInitializer_1 = true;
82457                         }
82458                     }
82459                 });
82460             }
82461         }
82462         function checkEnumMember(node) {
82463             if (ts.isPrivateIdentifier(node.name)) {
82464                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
82465             }
82466         }
82467         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
82468             var declarations = symbol.declarations;
82469             if (declarations) {
82470                 for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
82471                     var declaration = declarations_8[_i];
82472                     if ((declaration.kind === 256 /* ClassDeclaration */ ||
82473                         (declaration.kind === 255 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
82474                         !(declaration.flags & 8388608 /* Ambient */)) {
82475                         return declaration;
82476                     }
82477                 }
82478             }
82479             return undefined;
82480         }
82481         function inSameLexicalScope(node1, node2) {
82482             var container1 = ts.getEnclosingBlockScopeContainer(node1);
82483             var container2 = ts.getEnclosingBlockScopeContainer(node2);
82484             if (isGlobalSourceFile(container1)) {
82485                 return isGlobalSourceFile(container2);
82486             }
82487             else if (isGlobalSourceFile(container2)) {
82488                 return false;
82489             }
82490             else {
82491                 return container1 === container2;
82492             }
82493         }
82494         function checkModuleDeclaration(node) {
82495             if (produceDiagnostics) {
82496                 // Grammar checking
82497                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
82498                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
82499                 if (isGlobalAugmentation && !inAmbientContext) {
82500                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
82501                 }
82502                 var isAmbientExternalModule = ts.isAmbientModule(node);
82503                 var contextErrorMessage = isAmbientExternalModule
82504                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
82505                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
82506                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
82507                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
82508                     return;
82509                 }
82510                 if (!checkGrammarDecoratorsAndModifiers(node)) {
82511                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
82512                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
82513                     }
82514                 }
82515                 if (ts.isIdentifier(node.name)) {
82516                     checkCollisionsForDeclarationName(node, node.name);
82517                 }
82518                 checkExportsOnMergedDeclarations(node);
82519                 var symbol = getSymbolOfNode(node);
82520                 // The following checks only apply on a non-ambient instantiated module declaration.
82521                 if (symbol.flags & 512 /* ValueModule */
82522                     && !inAmbientContext
82523                     && symbol.declarations
82524                     && symbol.declarations.length > 1
82525                     && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) {
82526                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
82527                     if (firstNonAmbientClassOrFunc) {
82528                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
82529                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
82530                         }
82531                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
82532                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
82533                         }
82534                     }
82535                     // if the module merges with a class declaration in the same lexical scope,
82536                     // we need to track this to ensure the correct emit.
82537                     var mergedClass = ts.getDeclarationOfKind(symbol, 256 /* ClassDeclaration */);
82538                     if (mergedClass &&
82539                         inSameLexicalScope(node, mergedClass)) {
82540                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
82541                     }
82542                 }
82543                 if (isAmbientExternalModule) {
82544                     if (ts.isExternalModuleAugmentation(node)) {
82545                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
82546                         // otherwise we'll be swamped in cascading errors.
82547                         // We can detect if augmentation was applied using following rules:
82548                         // - augmentation for a global scope is always applied
82549                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
82550                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
82551                         if (checkBody && node.body) {
82552                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
82553                                 var statement = _a[_i];
82554                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
82555                             }
82556                         }
82557                     }
82558                     else if (isGlobalSourceFile(node.parent)) {
82559                         if (isGlobalAugmentation) {
82560                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
82561                         }
82562                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
82563                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
82564                         }
82565                     }
82566                     else {
82567                         if (isGlobalAugmentation) {
82568                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
82569                         }
82570                         else {
82571                             // Node is not an augmentation and is not located on the script level.
82572                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
82573                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
82574                         }
82575                     }
82576                 }
82577             }
82578             if (node.body) {
82579                 checkSourceElement(node.body);
82580                 if (!ts.isGlobalScopeAugmentation(node)) {
82581                     registerForUnusedIdentifiersCheck(node);
82582                 }
82583             }
82584         }
82585         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
82586             var _a;
82587             switch (node.kind) {
82588                 case 236 /* VariableStatement */:
82589                     // error each individual name in variable statement instead of marking the entire variable statement
82590                     for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) {
82591                         var decl = _b[_i];
82592                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
82593                     }
82594                     break;
82595                 case 270 /* ExportAssignment */:
82596                 case 271 /* ExportDeclaration */:
82597                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
82598                     break;
82599                 case 264 /* ImportEqualsDeclaration */:
82600                 case 265 /* ImportDeclaration */:
82601                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
82602                     break;
82603                 case 202 /* BindingElement */:
82604                 case 253 /* VariableDeclaration */:
82605                     var name = node.name;
82606                     if (ts.isBindingPattern(name)) {
82607                         for (var _c = 0, _d = name.elements; _c < _d.length; _c++) {
82608                             var el = _d[_c];
82609                             // mark individual names in binding pattern
82610                             checkModuleAugmentationElement(el, isGlobalAugmentation);
82611                         }
82612                         break;
82613                     }
82614                 // falls through
82615                 case 256 /* ClassDeclaration */:
82616                 case 259 /* EnumDeclaration */:
82617                 case 255 /* FunctionDeclaration */:
82618                 case 257 /* InterfaceDeclaration */:
82619                 case 260 /* ModuleDeclaration */:
82620                 case 258 /* TypeAliasDeclaration */:
82621                     if (isGlobalAugmentation) {
82622                         return;
82623                     }
82624                     var symbol = getSymbolOfNode(node);
82625                     if (symbol) {
82626                         // module augmentations cannot introduce new names on the top level scope of the module
82627                         // this is done it two steps
82628                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
82629                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
82630                         var reportError = !(symbol.flags & 33554432 /* Transient */);
82631                         if (!reportError) {
82632                             // symbol should not originate in augmentation
82633                             reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
82634                         }
82635                     }
82636                     break;
82637             }
82638         }
82639         function getFirstNonModuleExportsIdentifier(node) {
82640             switch (node.kind) {
82641                 case 79 /* Identifier */:
82642                     return node;
82643                 case 160 /* QualifiedName */:
82644                     do {
82645                         node = node.left;
82646                     } while (node.kind !== 79 /* Identifier */);
82647                     return node;
82648                 case 205 /* PropertyAccessExpression */:
82649                     do {
82650                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
82651                             return node.name;
82652                         }
82653                         node = node.expression;
82654                     } while (node.kind !== 79 /* Identifier */);
82655                     return node;
82656             }
82657         }
82658         function checkExternalImportOrExportDeclaration(node) {
82659             var moduleName = ts.getExternalModuleName(node);
82660             if (!moduleName || ts.nodeIsMissing(moduleName)) {
82661                 // Should be a parse error.
82662                 return false;
82663             }
82664             if (!ts.isStringLiteral(moduleName)) {
82665                 error(moduleName, ts.Diagnostics.String_literal_expected);
82666                 return false;
82667             }
82668             var inAmbientExternalModule = node.parent.kind === 261 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
82669             if (node.parent.kind !== 303 /* SourceFile */ && !inAmbientExternalModule) {
82670                 error(moduleName, node.kind === 271 /* ExportDeclaration */ ?
82671                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
82672                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
82673                 return false;
82674             }
82675             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
82676                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
82677                 // no need to do this again.
82678                 if (!isTopLevelInExternalModuleAugmentation(node)) {
82679                     // TypeScript 1.0 spec (April 2013): 12.1.6
82680                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
82681                     // other external modules only through top - level external module names.
82682                     // Relative external module names are not permitted.
82683                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
82684                     return false;
82685                 }
82686             }
82687             return true;
82688         }
82689         function checkAliasSymbol(node) {
82690             var _a;
82691             var symbol = getSymbolOfNode(node);
82692             var target = resolveAlias(symbol);
82693             if (target !== unknownSymbol) {
82694                 // For external modules, `symbol` represents the local symbol for an alias.
82695                 // This local symbol will merge any other local declarations (excluding other aliases)
82696                 // and symbol.flags will contains combined representation for all merged declaration.
82697                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
82698                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
82699                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
82700                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
82701                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
82702                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
82703                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
82704                 if (target.flags & excludedMeanings) {
82705                     var message = node.kind === 274 /* ExportSpecifier */ ?
82706                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
82707                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
82708                     error(node, message, symbolToString(symbol));
82709                 }
82710                 if (compilerOptions.isolatedModules
82711                     && !ts.isTypeOnlyImportOrExportDeclaration(node)
82712                     && !(node.flags & 8388608 /* Ambient */)) {
82713                     var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol);
82714                     var isType = !(target.flags & 111551 /* Value */);
82715                     if (isType || typeOnlyAlias) {
82716                         switch (node.kind) {
82717                             case 266 /* ImportClause */:
82718                             case 269 /* ImportSpecifier */:
82719                             case 264 /* ImportEqualsDeclaration */: {
82720                                 if (compilerOptions.preserveValueImports) {
82721                                     ts.Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name");
82722                                     var message = isType
82723                                         ? ts.Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled
82724                                         : ts.Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled;
82725                                     var name = ts.idText(node.kind === 269 /* ImportSpecifier */ ? node.propertyName || node.name : node.name);
82726                                     addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name);
82727                                 }
82728                                 break;
82729                             }
82730                             case 274 /* ExportSpecifier */: {
82731                                 // Don't allow re-exporting an export that will be elided when `--isolatedModules` is set.
82732                                 // The exception is that `import type { A } from './a'; export { A }` is allowed
82733                                 // because single-file analysis can determine that the export should be dropped.
82734                                 if (ts.getSourceFileOfNode(typeOnlyAlias) !== ts.getSourceFileOfNode(node)) {
82735                                     var message = isType
82736                                         ? ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type
82737                                         : ts.Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_isolatedModules_is_enabled;
82738                                     var name = ts.idText(node.propertyName || node.name);
82739                                     addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name);
82740                                     return;
82741                                 }
82742                             }
82743                         }
82744                     }
82745                 }
82746                 if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) {
82747                     addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName);
82748                 }
82749             }
82750         }
82751         function checkImportBinding(node) {
82752             checkCollisionsForDeclarationName(node, node.name);
82753             checkAliasSymbol(node);
82754             if (node.kind === 269 /* ImportSpecifier */ &&
82755                 ts.idText(node.propertyName || node.name) === "default" &&
82756                 ts.getESModuleInterop(compilerOptions) &&
82757                 moduleKind !== ts.ModuleKind.System && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS)) {
82758                 checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
82759             }
82760         }
82761         function checkAssertClause(declaration) {
82762             var _a;
82763             if (declaration.assertClause) {
82764                 if (moduleKind !== ts.ModuleKind.ESNext) {
82765                     return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext);
82766                 }
82767                 if (ts.isImportDeclaration(declaration) ? (_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.isTypeOnly : declaration.isTypeOnly) {
82768                     return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports);
82769                 }
82770             }
82771         }
82772         function checkImportDeclaration(node) {
82773             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
82774                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
82775                 return;
82776             }
82777             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
82778                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
82779             }
82780             if (checkExternalImportOrExportDeclaration(node)) {
82781                 var importClause = node.importClause;
82782                 if (importClause && !checkGrammarImportClause(importClause)) {
82783                     if (importClause.name) {
82784                         checkImportBinding(importClause);
82785                     }
82786                     if (importClause.namedBindings) {
82787                         if (importClause.namedBindings.kind === 267 /* NamespaceImport */) {
82788                             checkImportBinding(importClause.namedBindings);
82789                             if (moduleKind !== ts.ModuleKind.System && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS) && ts.getESModuleInterop(compilerOptions)) {
82790                                 // import * as ns from "foo";
82791                                 checkExternalEmitHelpers(node, 65536 /* ImportStar */);
82792                             }
82793                         }
82794                         else {
82795                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
82796                             if (moduleExisted) {
82797                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
82798                             }
82799                         }
82800                     }
82801                 }
82802             }
82803             checkAssertClause(node);
82804         }
82805         function checkImportEqualsDeclaration(node) {
82806             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
82807                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
82808                 return;
82809             }
82810             checkGrammarDecoratorsAndModifiers(node);
82811             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
82812                 checkImportBinding(node);
82813                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
82814                     markExportAsReferenced(node);
82815                 }
82816                 if (node.moduleReference.kind !== 276 /* ExternalModuleReference */) {
82817                     var target = resolveAlias(getSymbolOfNode(node));
82818                     if (target !== unknownSymbol) {
82819                         if (target.flags & 111551 /* Value */) {
82820                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
82821                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
82822                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
82823                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
82824                             }
82825                         }
82826                         if (target.flags & 788968 /* Type */) {
82827                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
82828                         }
82829                     }
82830                     if (node.isTypeOnly) {
82831                         grammarErrorOnNode(node, ts.Diagnostics.An_import_alias_cannot_use_import_type);
82832                     }
82833                 }
82834                 else {
82835                     if (moduleKind >= ts.ModuleKind.ES2015 && ts.getSourceFileOfNode(node).impliedNodeFormat === undefined && !node.isTypeOnly && !(node.flags & 8388608 /* Ambient */)) {
82836                         // Import equals declaration is deprecated in es6 or above
82837                         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);
82838                     }
82839                 }
82840             }
82841         }
82842         function checkExportDeclaration(node) {
82843             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
82844                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
82845                 return;
82846             }
82847             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
82848                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
82849             }
82850             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
82851                 checkExternalEmitHelpers(node, 4194304 /* CreateBinding */);
82852             }
82853             checkGrammarExportDeclaration(node);
82854             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
82855                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
82856                     // export { x, y }
82857                     // export { x, y } from "foo"
82858                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
82859                     var inAmbientExternalModule = node.parent.kind === 261 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
82860                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 261 /* ModuleBlock */ &&
82861                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
82862                     if (node.parent.kind !== 303 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
82863                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
82864                     }
82865                 }
82866                 else {
82867                     // export * from "foo"
82868                     // export * as ns from "foo";
82869                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
82870                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
82871                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
82872                     }
82873                     else if (node.exportClause) {
82874                         checkAliasSymbol(node.exportClause);
82875                     }
82876                     if (moduleKind !== ts.ModuleKind.System && (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS)) {
82877                         if (node.exportClause) {
82878                             // export * as ns from "foo";
82879                             // 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.
82880                             // We only use the helper here when in esModuleInterop
82881                             if (ts.getESModuleInterop(compilerOptions)) {
82882                                 checkExternalEmitHelpers(node, 65536 /* ImportStar */);
82883                             }
82884                         }
82885                         else {
82886                             // export * from "foo"
82887                             checkExternalEmitHelpers(node, 32768 /* ExportStar */);
82888                         }
82889                     }
82890                 }
82891             }
82892             checkAssertClause(node);
82893         }
82894         function checkGrammarExportDeclaration(node) {
82895             var _a;
82896             if (node.isTypeOnly) {
82897                 if (((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) === 272 /* NamedExports */) {
82898                     return checkGrammarNamedImportsOrExports(node.exportClause);
82899                 }
82900                 else {
82901                     return grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
82902                 }
82903             }
82904             return false;
82905         }
82906         function checkGrammarModuleElementContext(node, errorMessage) {
82907             var isInAppropriateContext = node.parent.kind === 303 /* SourceFile */ || node.parent.kind === 261 /* ModuleBlock */ || node.parent.kind === 260 /* ModuleDeclaration */;
82908             if (!isInAppropriateContext) {
82909                 grammarErrorOnFirstToken(node, errorMessage);
82910             }
82911             return !isInAppropriateContext;
82912         }
82913         function importClauseContainsReferencedImport(importClause) {
82914             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
82915                 return !!getSymbolOfNode(declaration).isReferenced;
82916             });
82917         }
82918         function importClauseContainsConstEnumUsedAsValue(importClause) {
82919             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
82920                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
82921             });
82922         }
82923         function canConvertImportDeclarationToTypeOnly(statement) {
82924             return ts.isImportDeclaration(statement) &&
82925                 statement.importClause &&
82926                 !statement.importClause.isTypeOnly &&
82927                 importClauseContainsReferencedImport(statement.importClause) &&
82928                 !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
82929                 !importClauseContainsConstEnumUsedAsValue(statement.importClause);
82930         }
82931         function canConvertImportEqualsDeclarationToTypeOnly(statement) {
82932             return ts.isImportEqualsDeclaration(statement) &&
82933                 ts.isExternalModuleReference(statement.moduleReference) &&
82934                 !statement.isTypeOnly &&
82935                 getSymbolOfNode(statement).isReferenced &&
82936                 !isReferencedAliasDeclaration(statement, /*checkChildren*/ false) &&
82937                 !getSymbolLinks(getSymbolOfNode(statement)).constEnumReferenced;
82938         }
82939         function checkImportsForTypeOnlyConversion(sourceFile) {
82940             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
82941                 var statement = _a[_i];
82942                 if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) {
82943                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error);
82944                 }
82945             }
82946         }
82947         function checkExportSpecifier(node) {
82948             checkAliasSymbol(node);
82949             if (ts.getEmitDeclarations(compilerOptions)) {
82950                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
82951             }
82952             if (!node.parent.parent.moduleSpecifier) {
82953                 var exportedName = node.propertyName || node.name;
82954                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
82955                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
82956                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
82957                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
82958                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
82959                 }
82960                 else {
82961                     markExportAsReferenced(node);
82962                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
82963                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
82964                         checkExpressionCached(node.propertyName || node.name);
82965                     }
82966                 }
82967             }
82968             else {
82969                 if (ts.getESModuleInterop(compilerOptions) &&
82970                     moduleKind !== ts.ModuleKind.System &&
82971                     (moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS) &&
82972                     ts.idText(node.propertyName || node.name) === "default") {
82973                     checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
82974                 }
82975             }
82976         }
82977         function checkExportAssignment(node) {
82978             var illegalContextMessage = node.isExportEquals
82979                 ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration
82980                 : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration;
82981             if (checkGrammarModuleElementContext(node, illegalContextMessage)) {
82982                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
82983                 return;
82984             }
82985             var container = node.parent.kind === 303 /* SourceFile */ ? node.parent : node.parent.parent;
82986             if (container.kind === 260 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
82987                 if (node.isExportEquals) {
82988                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
82989                 }
82990                 else {
82991                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
82992                 }
82993                 return;
82994             }
82995             // Grammar checking
82996             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
82997                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
82998             }
82999             var typeAnnotationNode = ts.getEffectiveTypeAnnotationNode(node);
83000             if (typeAnnotationNode) {
83001                 checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression);
83002             }
83003             if (node.expression.kind === 79 /* Identifier */) {
83004                 var id = node.expression;
83005                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
83006                 if (sym) {
83007                     markAliasReferenced(sym, id);
83008                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
83009                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
83010                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
83011                         // However if it is a value, we need to check it's being used correctly
83012                         checkExpressionCached(node.expression);
83013                     }
83014                 }
83015                 else {
83016                     checkExpressionCached(node.expression); // doesn't resolve, check as expression to mark as error
83017                 }
83018                 if (ts.getEmitDeclarations(compilerOptions)) {
83019                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
83020                 }
83021             }
83022             else {
83023                 checkExpressionCached(node.expression);
83024             }
83025             checkExternalModuleExports(container);
83026             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
83027                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
83028             }
83029             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
83030                 if (moduleKind >= ts.ModuleKind.ES2015 && ts.getSourceFileOfNode(node).impliedNodeFormat !== ts.ModuleKind.CommonJS) {
83031                     // export assignment is not supported in es6 modules
83032                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
83033                 }
83034                 else if (moduleKind === ts.ModuleKind.System) {
83035                     // system modules does not support export assignment
83036                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
83037                 }
83038             }
83039         }
83040         function hasExportedMembers(moduleSymbol) {
83041             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
83042         }
83043         function checkExternalModuleExports(node) {
83044             var moduleSymbol = getSymbolOfNode(node);
83045             var links = getSymbolLinks(moduleSymbol);
83046             if (!links.exportsChecked) {
83047                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
83048                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
83049                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
83050                     if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
83051                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
83052                     }
83053                 }
83054                 // Checks for export * conflicts
83055                 var exports_2 = getExportsOfModule(moduleSymbol);
83056                 if (exports_2) {
83057                     exports_2.forEach(function (_a, id) {
83058                         var declarations = _a.declarations, flags = _a.flags;
83059                         if (id === "__export") {
83060                             return;
83061                         }
83062                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
83063                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
83064                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
83065                             return;
83066                         }
83067                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
83068                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
83069                             // it is legal to merge type alias with other values
83070                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
83071                             return;
83072                         }
83073                         if (exportedDeclarationsCount > 1) {
83074                             if (!isDuplicatedCommonJSExport(declarations)) {
83075                                 for (var _i = 0, _b = declarations; _i < _b.length; _i++) {
83076                                     var declaration = _b[_i];
83077                                     if (isNotOverload(declaration)) {
83078                                         diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
83079                                     }
83080                                 }
83081                             }
83082                         }
83083                     });
83084                 }
83085                 links.exportsChecked = true;
83086             }
83087         }
83088         function isDuplicatedCommonJSExport(declarations) {
83089             return declarations
83090                 && declarations.length > 1
83091                 && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); });
83092         }
83093         function checkSourceElement(node) {
83094             if (node) {
83095                 var saveCurrentNode = currentNode;
83096                 currentNode = node;
83097                 instantiationCount = 0;
83098                 checkSourceElementWorker(node);
83099                 currentNode = saveCurrentNode;
83100             }
83101         }
83102         function checkSourceElementWorker(node) {
83103             if (ts.isInJSFile(node)) {
83104                 ts.forEach(node.jsDoc, function (_a) {
83105                     var tags = _a.tags;
83106                     return ts.forEach(tags, checkSourceElement);
83107                 });
83108             }
83109             var kind = node.kind;
83110             if (cancellationToken) {
83111                 // Only bother checking on a few construct kinds.  We don't want to be excessively
83112                 // hitting the cancellation token on every node we check.
83113                 switch (kind) {
83114                     case 260 /* ModuleDeclaration */:
83115                     case 256 /* ClassDeclaration */:
83116                     case 257 /* InterfaceDeclaration */:
83117                     case 255 /* FunctionDeclaration */:
83118                         cancellationToken.throwIfCancellationRequested();
83119                 }
83120             }
83121             if (kind >= 236 /* FirstStatement */ && kind <= 252 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
83122                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
83123             }
83124             switch (kind) {
83125                 case 162 /* TypeParameter */:
83126                     return checkTypeParameter(node);
83127                 case 163 /* Parameter */:
83128                     return checkParameter(node);
83129                 case 166 /* PropertyDeclaration */:
83130                     return checkPropertyDeclaration(node);
83131                 case 165 /* PropertySignature */:
83132                     return checkPropertySignature(node);
83133                 case 179 /* ConstructorType */:
83134                 case 178 /* FunctionType */:
83135                 case 173 /* CallSignature */:
83136                 case 174 /* ConstructSignature */:
83137                 case 175 /* IndexSignature */:
83138                     return checkSignatureDeclaration(node);
83139                 case 168 /* MethodDeclaration */:
83140                 case 167 /* MethodSignature */:
83141                     return checkMethodDeclaration(node);
83142                 case 169 /* ClassStaticBlockDeclaration */:
83143                     return checkClassStaticBlockDeclaration(node);
83144                 case 170 /* Constructor */:
83145                     return checkConstructorDeclaration(node);
83146                 case 171 /* GetAccessor */:
83147                 case 172 /* SetAccessor */:
83148                     return checkAccessorDeclaration(node);
83149                 case 177 /* TypeReference */:
83150                     return checkTypeReferenceNode(node);
83151                 case 176 /* TypePredicate */:
83152                     return checkTypePredicate(node);
83153                 case 180 /* TypeQuery */:
83154                     return checkTypeQuery(node);
83155                 case 181 /* TypeLiteral */:
83156                     return checkTypeLiteral(node);
83157                 case 182 /* ArrayType */:
83158                     return checkArrayType(node);
83159                 case 183 /* TupleType */:
83160                     return checkTupleType(node);
83161                 case 186 /* UnionType */:
83162                 case 187 /* IntersectionType */:
83163                     return checkUnionOrIntersectionType(node);
83164                 case 190 /* ParenthesizedType */:
83165                 case 184 /* OptionalType */:
83166                 case 185 /* RestType */:
83167                     return checkSourceElement(node.type);
83168                 case 191 /* ThisType */:
83169                     return checkThisType(node);
83170                 case 192 /* TypeOperator */:
83171                     return checkTypeOperator(node);
83172                 case 188 /* ConditionalType */:
83173                     return checkConditionalType(node);
83174                 case 189 /* InferType */:
83175                     return checkInferType(node);
83176                 case 197 /* TemplateLiteralType */:
83177                     return checkTemplateLiteralType(node);
83178                 case 199 /* ImportType */:
83179                     return checkImportType(node);
83180                 case 196 /* NamedTupleMember */:
83181                     return checkNamedTupleMember(node);
83182                 case 326 /* JSDocAugmentsTag */:
83183                     return checkJSDocAugmentsTag(node);
83184                 case 327 /* JSDocImplementsTag */:
83185                     return checkJSDocImplementsTag(node);
83186                 case 343 /* JSDocTypedefTag */:
83187                 case 336 /* JSDocCallbackTag */:
83188                 case 337 /* JSDocEnumTag */:
83189                     return checkJSDocTypeAliasTag(node);
83190                 case 342 /* JSDocTemplateTag */:
83191                     return checkJSDocTemplateTag(node);
83192                 case 341 /* JSDocTypeTag */:
83193                     return checkJSDocTypeTag(node);
83194                 case 338 /* JSDocParameterTag */:
83195                     return checkJSDocParameterTag(node);
83196                 case 345 /* JSDocPropertyTag */:
83197                     return checkJSDocPropertyTag(node);
83198                 case 315 /* JSDocFunctionType */:
83199                     checkJSDocFunctionType(node);
83200                 // falls through
83201                 case 313 /* JSDocNonNullableType */:
83202                 case 312 /* JSDocNullableType */:
83203                 case 310 /* JSDocAllType */:
83204                 case 311 /* JSDocUnknownType */:
83205                 case 320 /* JSDocTypeLiteral */:
83206                     checkJSDocTypeIsInJsFile(node);
83207                     ts.forEachChild(node, checkSourceElement);
83208                     return;
83209                 case 316 /* JSDocVariadicType */:
83210                     checkJSDocVariadicType(node);
83211                     return;
83212                 case 307 /* JSDocTypeExpression */:
83213                     return checkSourceElement(node.type);
83214                 case 331 /* JSDocPublicTag */:
83215                 case 333 /* JSDocProtectedTag */:
83216                 case 332 /* JSDocPrivateTag */:
83217                     return checkJSDocAccessibilityModifiers(node);
83218                 case 193 /* IndexedAccessType */:
83219                     return checkIndexedAccessType(node);
83220                 case 194 /* MappedType */:
83221                     return checkMappedType(node);
83222                 case 255 /* FunctionDeclaration */:
83223                     return checkFunctionDeclaration(node);
83224                 case 234 /* Block */:
83225                 case 261 /* ModuleBlock */:
83226                     return checkBlock(node);
83227                 case 236 /* VariableStatement */:
83228                     return checkVariableStatement(node);
83229                 case 237 /* ExpressionStatement */:
83230                     return checkExpressionStatement(node);
83231                 case 238 /* IfStatement */:
83232                     return checkIfStatement(node);
83233                 case 239 /* DoStatement */:
83234                     return checkDoStatement(node);
83235                 case 240 /* WhileStatement */:
83236                     return checkWhileStatement(node);
83237                 case 241 /* ForStatement */:
83238                     return checkForStatement(node);
83239                 case 242 /* ForInStatement */:
83240                     return checkForInStatement(node);
83241                 case 243 /* ForOfStatement */:
83242                     return checkForOfStatement(node);
83243                 case 244 /* ContinueStatement */:
83244                 case 245 /* BreakStatement */:
83245                     return checkBreakOrContinueStatement(node);
83246                 case 246 /* ReturnStatement */:
83247                     return checkReturnStatement(node);
83248                 case 247 /* WithStatement */:
83249                     return checkWithStatement(node);
83250                 case 248 /* SwitchStatement */:
83251                     return checkSwitchStatement(node);
83252                 case 249 /* LabeledStatement */:
83253                     return checkLabeledStatement(node);
83254                 case 250 /* ThrowStatement */:
83255                     return checkThrowStatement(node);
83256                 case 251 /* TryStatement */:
83257                     return checkTryStatement(node);
83258                 case 253 /* VariableDeclaration */:
83259                     return checkVariableDeclaration(node);
83260                 case 202 /* BindingElement */:
83261                     return checkBindingElement(node);
83262                 case 256 /* ClassDeclaration */:
83263                     return checkClassDeclaration(node);
83264                 case 257 /* InterfaceDeclaration */:
83265                     return checkInterfaceDeclaration(node);
83266                 case 258 /* TypeAliasDeclaration */:
83267                     return checkTypeAliasDeclaration(node);
83268                 case 259 /* EnumDeclaration */:
83269                     return checkEnumDeclaration(node);
83270                 case 260 /* ModuleDeclaration */:
83271                     return checkModuleDeclaration(node);
83272                 case 265 /* ImportDeclaration */:
83273                     return checkImportDeclaration(node);
83274                 case 264 /* ImportEqualsDeclaration */:
83275                     return checkImportEqualsDeclaration(node);
83276                 case 271 /* ExportDeclaration */:
83277                     return checkExportDeclaration(node);
83278                 case 270 /* ExportAssignment */:
83279                     return checkExportAssignment(node);
83280                 case 235 /* EmptyStatement */:
83281                 case 252 /* DebuggerStatement */:
83282                     checkGrammarStatementInAmbientContext(node);
83283                     return;
83284                 case 275 /* MissingDeclaration */:
83285                     return checkMissingDeclaration(node);
83286             }
83287         }
83288         function checkJSDocTypeIsInJsFile(node) {
83289             if (!ts.isInJSFile(node)) {
83290                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
83291             }
83292         }
83293         function checkJSDocVariadicType(node) {
83294             checkJSDocTypeIsInJsFile(node);
83295             checkSourceElement(node.type);
83296             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
83297             var parent = node.parent;
83298             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
83299                 if (ts.last(parent.parent.parameters) !== parent) {
83300                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
83301                 }
83302                 return;
83303             }
83304             if (!ts.isJSDocTypeExpression(parent)) {
83305                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
83306             }
83307             var paramTag = node.parent.parent;
83308             if (!ts.isJSDocParameterTag(paramTag)) {
83309                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
83310                 return;
83311             }
83312             var param = ts.getParameterSymbolFromJSDoc(paramTag);
83313             if (!param) {
83314                 // We will error in `checkJSDocParameterTag`.
83315                 return;
83316             }
83317             var host = ts.getHostSignatureFromJSDoc(paramTag);
83318             if (!host || ts.last(host.parameters).symbol !== param) {
83319                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
83320             }
83321         }
83322         function getTypeFromJSDocVariadicType(node) {
83323             var type = getTypeFromTypeNode(node.type);
83324             var parent = node.parent;
83325             var paramTag = node.parent.parent;
83326             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
83327                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
83328                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
83329                 var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent);
83330                 if (host_1 || isCallbackTag) {
83331                     /*
83332                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
83333                     So in the following situation we will not create an array type:
83334                         /** @param {...number} a * /
83335                         function f(a) {}
83336                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
83337                     */
83338                     var lastParamDeclaration = isCallbackTag
83339                         ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters)
83340                         : ts.lastOrUndefined(host_1.parameters);
83341                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
83342                     if (!lastParamDeclaration ||
83343                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
83344                         return createArrayType(type);
83345                     }
83346                 }
83347             }
83348             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
83349                 return createArrayType(type);
83350             }
83351             return addOptionality(type);
83352         }
83353         // Function and class expression bodies are checked after all statements in the enclosing body. This is
83354         // to ensure constructs like the following are permitted:
83355         //     const foo = function () {
83356         //        const s = foo();
83357         //        return "hello";
83358         //     }
83359         // Here, performing a full type check of the body of the function expression whilst in the process of
83360         // determining the type of foo would cause foo to be given type any because of the recursive reference.
83361         // Delaying the type check of the body ensures foo has been assigned a type.
83362         function checkNodeDeferred(node) {
83363             var enclosingFile = ts.getSourceFileOfNode(node);
83364             var links = getNodeLinks(enclosingFile);
83365             if (!(links.flags & 1 /* TypeChecked */)) {
83366                 links.deferredNodes = links.deferredNodes || new ts.Map();
83367                 var id = getNodeId(node);
83368                 links.deferredNodes.set(id, node);
83369             }
83370         }
83371         function checkDeferredNodes(context) {
83372             var links = getNodeLinks(context);
83373             if (links.deferredNodes) {
83374                 links.deferredNodes.forEach(checkDeferredNode);
83375             }
83376         }
83377         function checkDeferredNode(node) {
83378             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end });
83379             var saveCurrentNode = currentNode;
83380             currentNode = node;
83381             instantiationCount = 0;
83382             switch (node.kind) {
83383                 case 207 /* CallExpression */:
83384                 case 208 /* NewExpression */:
83385                 case 209 /* TaggedTemplateExpression */:
83386                 case 164 /* Decorator */:
83387                 case 279 /* JsxOpeningElement */:
83388                     // These node kinds are deferred checked when overload resolution fails
83389                     // To save on work, we ensure the arguments are checked just once, in
83390                     // a deferred way
83391                     resolveUntypedCall(node);
83392                     break;
83393                 case 212 /* FunctionExpression */:
83394                 case 213 /* ArrowFunction */:
83395                 case 168 /* MethodDeclaration */:
83396                 case 167 /* MethodSignature */:
83397                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
83398                     break;
83399                 case 171 /* GetAccessor */:
83400                 case 172 /* SetAccessor */:
83401                     checkAccessorDeclaration(node);
83402                     break;
83403                 case 225 /* ClassExpression */:
83404                     checkClassExpressionDeferred(node);
83405                     break;
83406                 case 278 /* JsxSelfClosingElement */:
83407                     checkJsxSelfClosingElementDeferred(node);
83408                     break;
83409                 case 277 /* JsxElement */:
83410                     checkJsxElementDeferred(node);
83411                     break;
83412             }
83413             currentNode = saveCurrentNode;
83414             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
83415         }
83416         function checkSourceFile(node) {
83417             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true);
83418             ts.performance.mark("beforeCheck");
83419             checkSourceFileWorker(node);
83420             ts.performance.mark("afterCheck");
83421             ts.performance.measure("Check", "beforeCheck", "afterCheck");
83422             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
83423         }
83424         function unusedIsError(kind, isAmbient) {
83425             if (isAmbient) {
83426                 return false;
83427             }
83428             switch (kind) {
83429                 case 0 /* Local */:
83430                     return !!compilerOptions.noUnusedLocals;
83431                 case 1 /* Parameter */:
83432                     return !!compilerOptions.noUnusedParameters;
83433                 default:
83434                     return ts.Debug.assertNever(kind);
83435             }
83436         }
83437         function getPotentiallyUnusedIdentifiers(sourceFile) {
83438             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
83439         }
83440         // Fully type check a source file and collect the relevant diagnostics.
83441         function checkSourceFileWorker(node) {
83442             var links = getNodeLinks(node);
83443             if (!(links.flags & 1 /* TypeChecked */)) {
83444                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
83445                     return;
83446                 }
83447                 // Grammar checking
83448                 checkGrammarSourceFile(node);
83449                 ts.clear(potentialThisCollisions);
83450                 ts.clear(potentialNewTargetCollisions);
83451                 ts.clear(potentialWeakMapSetCollisions);
83452                 ts.clear(potentialReflectCollisions);
83453                 ts.forEach(node.statements, checkSourceElement);
83454                 checkSourceElement(node.endOfFileToken);
83455                 checkDeferredNodes(node);
83456                 if (ts.isExternalOrCommonJsModule(node)) {
83457                     registerForUnusedIdentifiersCheck(node);
83458                 }
83459                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
83460                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
83461                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
83462                             diagnostics.add(diag);
83463                         }
83464                     });
83465                 }
83466                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
83467                     !node.isDeclarationFile &&
83468                     ts.isExternalModule(node)) {
83469                     checkImportsForTypeOnlyConversion(node);
83470                 }
83471                 if (ts.isExternalOrCommonJsModule(node)) {
83472                     checkExternalModuleExports(node);
83473                 }
83474                 if (potentialThisCollisions.length) {
83475                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
83476                     ts.clear(potentialThisCollisions);
83477                 }
83478                 if (potentialNewTargetCollisions.length) {
83479                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
83480                     ts.clear(potentialNewTargetCollisions);
83481                 }
83482                 if (potentialWeakMapSetCollisions.length) {
83483                     ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision);
83484                     ts.clear(potentialWeakMapSetCollisions);
83485                 }
83486                 if (potentialReflectCollisions.length) {
83487                     ts.forEach(potentialReflectCollisions, checkReflectCollision);
83488                     ts.clear(potentialReflectCollisions);
83489                 }
83490                 links.flags |= 1 /* TypeChecked */;
83491             }
83492         }
83493         function getDiagnostics(sourceFile, ct) {
83494             try {
83495                 // Record the cancellation token so it can be checked later on during checkSourceElement.
83496                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
83497                 // this call is done.
83498                 cancellationToken = ct;
83499                 return getDiagnosticsWorker(sourceFile);
83500             }
83501             finally {
83502                 cancellationToken = undefined;
83503             }
83504         }
83505         function getDiagnosticsWorker(sourceFile) {
83506             throwIfNonDiagnosticsProducing();
83507             if (sourceFile) {
83508                 // Some global diagnostics are deferred until they are needed and
83509                 // may not be reported in the first call to getGlobalDiagnostics.
83510                 // We should catch these changes and report them.
83511                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
83512                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
83513                 checkSourceFile(sourceFile);
83514                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
83515                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
83516                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
83517                     // If the arrays are not the same reference, new diagnostics were added.
83518                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
83519                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
83520                 }
83521                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
83522                     // If the arrays are the same reference, but the length has changed, a single
83523                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
83524                     // same array.
83525                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
83526                 }
83527                 return semanticDiagnostics;
83528             }
83529             // Global diagnostics are always added when a file is not provided to
83530             // getDiagnostics
83531             ts.forEach(host.getSourceFiles(), checkSourceFile);
83532             return diagnostics.getDiagnostics();
83533         }
83534         function getGlobalDiagnostics() {
83535             throwIfNonDiagnosticsProducing();
83536             return diagnostics.getGlobalDiagnostics();
83537         }
83538         function throwIfNonDiagnosticsProducing() {
83539             if (!produceDiagnostics) {
83540                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
83541             }
83542         }
83543         // Language service support
83544         function getSymbolsInScope(location, meaning) {
83545             if (location.flags & 16777216 /* InWithStatement */) {
83546                 // We cannot answer semantic questions within a with block, do not proceed any further
83547                 return [];
83548             }
83549             var symbols = ts.createSymbolTable();
83550             var isStaticSymbol = false;
83551             populateSymbols();
83552             symbols.delete("this" /* This */); // Not a symbol, a keyword
83553             return symbolsToArray(symbols);
83554             function populateSymbols() {
83555                 while (location) {
83556                     if (location.locals && !isGlobalSourceFile(location)) {
83557                         copySymbols(location.locals, meaning);
83558                     }
83559                     switch (location.kind) {
83560                         case 303 /* SourceFile */:
83561                             if (!ts.isExternalModule(location))
83562                                 break;
83563                         // falls through
83564                         case 260 /* ModuleDeclaration */:
83565                             copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
83566                             break;
83567                         case 259 /* EnumDeclaration */:
83568                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
83569                             break;
83570                         case 225 /* ClassExpression */:
83571                             var className = location.name;
83572                             if (className) {
83573                                 copySymbol(location.symbol, meaning);
83574                             }
83575                         // this fall-through is necessary because we would like to handle
83576                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
83577                         // falls through
83578                         case 256 /* ClassDeclaration */:
83579                         case 257 /* InterfaceDeclaration */:
83580                             // If we didn't come from static member of class or interface,
83581                             // add the type parameters into the symbol table
83582                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
83583                             // Note: that the memberFlags come from previous iteration.
83584                             if (!isStaticSymbol) {
83585                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
83586                             }
83587                             break;
83588                         case 212 /* FunctionExpression */:
83589                             var funcName = location.name;
83590                             if (funcName) {
83591                                 copySymbol(location.symbol, meaning);
83592                             }
83593                             break;
83594                     }
83595                     if (ts.introducesArgumentsExoticObject(location)) {
83596                         copySymbol(argumentsSymbol, meaning);
83597                     }
83598                     isStaticSymbol = ts.isStatic(location);
83599                     location = location.parent;
83600                 }
83601                 copySymbols(globals, meaning);
83602             }
83603             /**
83604              * Copy the given symbol into symbol tables if the symbol has the given meaning
83605              * and it doesn't already existed in the symbol table
83606              * @param key a key for storing in symbol table; if undefined, use symbol.name
83607              * @param symbol the symbol to be added into symbol table
83608              * @param meaning meaning of symbol to filter by before adding to symbol table
83609              */
83610             function copySymbol(symbol, meaning) {
83611                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
83612                     var id = symbol.escapedName;
83613                     // We will copy all symbol regardless of its reserved name because
83614                     // symbolsToArray will check whether the key is a reserved name and
83615                     // it will not copy symbol with reserved name to the array
83616                     if (!symbols.has(id)) {
83617                         symbols.set(id, symbol);
83618                     }
83619                 }
83620             }
83621             function copySymbols(source, meaning) {
83622                 if (meaning) {
83623                     source.forEach(function (symbol) {
83624                         copySymbol(symbol, meaning);
83625                     });
83626                 }
83627             }
83628             function copyLocallyVisibleExportSymbols(source, meaning) {
83629                 if (meaning) {
83630                     source.forEach(function (symbol) {
83631                         // Similar condition as in `resolveNameHelper`
83632                         if (!ts.getDeclarationOfKind(symbol, 274 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 273 /* NamespaceExport */)) {
83633                             copySymbol(symbol, meaning);
83634                         }
83635                     });
83636                 }
83637             }
83638         }
83639         function isTypeDeclarationName(name) {
83640             return name.kind === 79 /* Identifier */ &&
83641                 isTypeDeclaration(name.parent) &&
83642                 ts.getNameOfDeclaration(name.parent) === name;
83643         }
83644         function isTypeDeclaration(node) {
83645             switch (node.kind) {
83646                 case 162 /* TypeParameter */:
83647                 case 256 /* ClassDeclaration */:
83648                 case 257 /* InterfaceDeclaration */:
83649                 case 258 /* TypeAliasDeclaration */:
83650                 case 259 /* EnumDeclaration */:
83651                 case 343 /* JSDocTypedefTag */:
83652                 case 336 /* JSDocCallbackTag */:
83653                 case 337 /* JSDocEnumTag */:
83654                     return true;
83655                 case 266 /* ImportClause */:
83656                     return node.isTypeOnly;
83657                 case 269 /* ImportSpecifier */:
83658                 case 274 /* ExportSpecifier */:
83659                     return node.parent.parent.isTypeOnly;
83660                 default:
83661                     return false;
83662             }
83663         }
83664         // True if the given identifier is part of a type reference
83665         function isTypeReferenceIdentifier(node) {
83666             while (node.parent.kind === 160 /* QualifiedName */) {
83667                 node = node.parent;
83668             }
83669             return node.parent.kind === 177 /* TypeReference */;
83670         }
83671         function isHeritageClauseElementIdentifier(node) {
83672             while (node.parent.kind === 205 /* PropertyAccessExpression */) {
83673                 node = node.parent;
83674             }
83675             return node.parent.kind === 227 /* ExpressionWithTypeArguments */;
83676         }
83677         function forEachEnclosingClass(node, callback) {
83678             var result;
83679             while (true) {
83680                 node = ts.getContainingClass(node);
83681                 if (!node)
83682                     break;
83683                 if (result = callback(node))
83684                     break;
83685             }
83686             return result;
83687         }
83688         function isNodeUsedDuringClassInitialization(node) {
83689             return !!ts.findAncestor(node, function (element) {
83690                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
83691                     return true;
83692                 }
83693                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
83694                     return "quit";
83695                 }
83696                 return false;
83697             });
83698         }
83699         function isNodeWithinClass(node, classDeclaration) {
83700             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
83701         }
83702         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
83703             while (nodeOnRightSide.parent.kind === 160 /* QualifiedName */) {
83704                 nodeOnRightSide = nodeOnRightSide.parent;
83705             }
83706             if (nodeOnRightSide.parent.kind === 264 /* ImportEqualsDeclaration */) {
83707                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
83708             }
83709             if (nodeOnRightSide.parent.kind === 270 /* ExportAssignment */) {
83710                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
83711             }
83712             return undefined;
83713         }
83714         function isInRightSideOfImportOrExportAssignment(node) {
83715             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
83716         }
83717         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
83718             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
83719             switch (specialPropertyAssignmentKind) {
83720                 case 1 /* ExportsProperty */:
83721                 case 3 /* PrototypeProperty */:
83722                     return getSymbolOfNode(entityName.parent);
83723                 case 4 /* ThisProperty */:
83724                 case 2 /* ModuleExports */:
83725                 case 5 /* Property */:
83726                     return getSymbolOfNode(entityName.parent.parent);
83727             }
83728         }
83729         function isImportTypeQualifierPart(node) {
83730             var parent = node.parent;
83731             while (ts.isQualifiedName(parent)) {
83732                 node = parent;
83733                 parent = parent.parent;
83734             }
83735             if (parent && parent.kind === 199 /* ImportType */ && parent.qualifier === node) {
83736                 return parent;
83737             }
83738             return undefined;
83739         }
83740         function getSymbolOfNameOrPropertyAccessExpression(name) {
83741             if (ts.isDeclarationName(name)) {
83742                 return getSymbolOfNode(name.parent);
83743             }
83744             if (ts.isInJSFile(name) &&
83745                 name.parent.kind === 205 /* PropertyAccessExpression */ &&
83746                 name.parent === name.parent.parent.left) {
83747                 // Check if this is a special property assignment
83748                 if (!ts.isPrivateIdentifier(name) && !ts.isJSDocMemberName(name)) {
83749                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
83750                     if (specialPropertyAssignmentSymbol) {
83751                         return specialPropertyAssignmentSymbol;
83752                     }
83753                 }
83754             }
83755             if (name.parent.kind === 270 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
83756                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
83757                 var success = resolveEntityName(name, 
83758                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
83759                 if (success && success !== unknownSymbol) {
83760                     return success;
83761                 }
83762             }
83763             else if (ts.isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) {
83764                 // Since we already checked for ExportAssignment, this really could only be an Import
83765                 var importEqualsDeclaration = ts.getAncestor(name, 264 /* ImportEqualsDeclaration */);
83766                 ts.Debug.assert(importEqualsDeclaration !== undefined);
83767                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
83768             }
83769             if (ts.isEntityName(name)) {
83770                 var possibleImportNode = isImportTypeQualifierPart(name);
83771                 if (possibleImportNode) {
83772                     getTypeFromTypeNode(possibleImportNode);
83773                     var sym = getNodeLinks(name).resolvedSymbol;
83774                     return sym === unknownSymbol ? undefined : sym;
83775                 }
83776             }
83777             while (ts.isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) {
83778                 name = name.parent;
83779             }
83780             if (isHeritageClauseElementIdentifier(name)) {
83781                 var meaning = 0 /* None */;
83782                 // In an interface or class, we're definitely interested in a type.
83783                 if (name.parent.kind === 227 /* ExpressionWithTypeArguments */) {
83784                     meaning = 788968 /* Type */;
83785                     // In a class 'extends' clause we are also looking for a value.
83786                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
83787                         meaning |= 111551 /* Value */;
83788                     }
83789                 }
83790                 else {
83791                     meaning = 1920 /* Namespace */;
83792                 }
83793                 meaning |= 2097152 /* Alias */;
83794                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
83795                 if (entityNameSymbol) {
83796                     return entityNameSymbol;
83797                 }
83798             }
83799             if (name.parent.kind === 338 /* JSDocParameterTag */) {
83800                 return ts.getParameterSymbolFromJSDoc(name.parent);
83801             }
83802             if (name.parent.kind === 162 /* TypeParameter */ && name.parent.parent.kind === 342 /* JSDocTemplateTag */) {
83803                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
83804                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
83805                 return typeParameter && typeParameter.symbol;
83806             }
83807             if (ts.isExpressionNode(name)) {
83808                 if (ts.nodeIsMissing(name)) {
83809                     // Missing entity name.
83810                     return undefined;
83811                 }
83812                 var isJSDoc_1 = ts.findAncestor(name, ts.or(ts.isJSDocLinkLike, ts.isJSDocNameReference, ts.isJSDocMemberName));
83813                 var meaning = isJSDoc_1 ? 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */ : 111551 /* Value */;
83814                 if (name.kind === 79 /* Identifier */) {
83815                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
83816                         var symbol = getIntrinsicTagSymbol(name.parent);
83817                         return symbol === unknownSymbol ? undefined : symbol;
83818                     }
83819                     var result = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ !isJSDoc_1, ts.getHostSignatureFromJSDoc(name));
83820                     if (!result && isJSDoc_1) {
83821                         var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration));
83822                         if (container) {
83823                             return resolveJSDocMemberName(name, getSymbolOfNode(container));
83824                         }
83825                     }
83826                     return result;
83827                 }
83828                 else if (ts.isPrivateIdentifier(name)) {
83829                     return getSymbolForPrivateIdentifierExpression(name);
83830                 }
83831                 else if (name.kind === 205 /* PropertyAccessExpression */ || name.kind === 160 /* QualifiedName */) {
83832                     var links = getNodeLinks(name);
83833                     if (links.resolvedSymbol) {
83834                         return links.resolvedSymbol;
83835                     }
83836                     if (name.kind === 205 /* PropertyAccessExpression */) {
83837                         checkPropertyAccessExpression(name, 0 /* Normal */);
83838                     }
83839                     else {
83840                         checkQualifiedName(name, 0 /* Normal */);
83841                     }
83842                     if (!links.resolvedSymbol && isJSDoc_1 && ts.isQualifiedName(name)) {
83843                         return resolveJSDocMemberName(name);
83844                     }
83845                     return links.resolvedSymbol;
83846                 }
83847                 else if (ts.isJSDocMemberName(name)) {
83848                     return resolveJSDocMemberName(name);
83849                 }
83850             }
83851             else if (isTypeReferenceIdentifier(name)) {
83852                 var meaning = name.parent.kind === 177 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
83853                 var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
83854                 return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name);
83855             }
83856             if (name.parent.kind === 176 /* TypePredicate */) {
83857                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
83858             }
83859             return undefined;
83860         }
83861         /**
83862          * Recursively resolve entity names and jsdoc instance references:
83863          * 1. K#m as K.prototype.m for a class (or other value) K
83864          * 2. K.m as K.prototype.m
83865          * 3. I.m as I.m for a type I, or any other I.m that fails to resolve in (1) or (2)
83866          *
83867          * For unqualified names, a container K may be provided as a second argument.
83868          */
83869         function resolveJSDocMemberName(name, container) {
83870             if (ts.isEntityName(name)) {
83871                 // resolve static values first
83872                 var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
83873                 var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name));
83874                 if (!symbol && ts.isIdentifier(name) && container) {
83875                     symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning));
83876                 }
83877                 if (symbol) {
83878                     return symbol;
83879                 }
83880             }
83881             var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left);
83882             var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText;
83883             if (left) {
83884                 var proto = left.flags & 111551 /* Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype");
83885                 var t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left);
83886                 return getPropertyOfType(t, right);
83887             }
83888         }
83889         function getSymbolAtLocation(node, ignoreErrors) {
83890             if (node.kind === 303 /* SourceFile */) {
83891                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
83892             }
83893             var parent = node.parent;
83894             var grandParent = parent.parent;
83895             if (node.flags & 16777216 /* InWithStatement */) {
83896                 // We cannot answer semantic questions within a with block, do not proceed any further
83897                 return undefined;
83898             }
83899             if (isDeclarationNameOrImportPropertyName(node)) {
83900                 // This is a declaration, call getSymbolOfNode
83901                 var parentSymbol = getSymbolOfNode(parent);
83902                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
83903                     ? getImmediateAliasedSymbol(parentSymbol)
83904                     : parentSymbol;
83905             }
83906             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
83907                 return getSymbolOfNode(parent.parent);
83908             }
83909             if (node.kind === 79 /* Identifier */) {
83910                 if (isInRightSideOfImportOrExportAssignment(node)) {
83911                     return getSymbolOfNameOrPropertyAccessExpression(node);
83912                 }
83913                 else if (parent.kind === 202 /* BindingElement */ &&
83914                     grandParent.kind === 200 /* ObjectBindingPattern */ &&
83915                     node === parent.propertyName) {
83916                     var typeOfPattern = getTypeOfNode(grandParent);
83917                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
83918                     if (propertyDeclaration) {
83919                         return propertyDeclaration;
83920                     }
83921                 }
83922                 else if (ts.isMetaProperty(parent)) {
83923                     var parentType = getTypeOfNode(parent);
83924                     var propertyDeclaration = getPropertyOfType(parentType, node.escapedText);
83925                     if (propertyDeclaration) {
83926                         return propertyDeclaration;
83927                     }
83928                     if (parent.keywordToken === 103 /* NewKeyword */) {
83929                         return checkNewTargetMetaProperty(parent).symbol;
83930                     }
83931                 }
83932             }
83933             switch (node.kind) {
83934                 case 79 /* Identifier */:
83935                 case 80 /* PrivateIdentifier */:
83936                 case 205 /* PropertyAccessExpression */:
83937                 case 160 /* QualifiedName */:
83938                     return getSymbolOfNameOrPropertyAccessExpression(node);
83939                 case 108 /* ThisKeyword */:
83940                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
83941                     if (ts.isFunctionLike(container)) {
83942                         var sig = getSignatureFromDeclaration(container);
83943                         if (sig.thisParameter) {
83944                             return sig.thisParameter;
83945                         }
83946                     }
83947                     if (ts.isInExpressionContext(node)) {
83948                         return checkExpression(node).symbol;
83949                     }
83950                 // falls through
83951                 case 191 /* ThisType */:
83952                     return getTypeFromThisTypeNode(node).symbol;
83953                 case 106 /* SuperKeyword */:
83954                     return checkExpression(node).symbol;
83955                 case 134 /* ConstructorKeyword */:
83956                     // constructor keyword for an overload, should take us to the definition if it exist
83957                     var constructorDeclaration = node.parent;
83958                     if (constructorDeclaration && constructorDeclaration.kind === 170 /* Constructor */) {
83959                         return constructorDeclaration.parent.symbol;
83960                     }
83961                     return undefined;
83962                 case 10 /* StringLiteral */:
83963                 case 14 /* NoSubstitutionTemplateLiteral */:
83964                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
83965                     // 2). External module name in an import declaration
83966                     // 3). Dynamic import call or require in javascript
83967                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
83968                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
83969                         ((node.parent.kind === 265 /* ImportDeclaration */ || node.parent.kind === 271 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
83970                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
83971                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
83972                         return resolveExternalModuleName(node, node, ignoreErrors);
83973                     }
83974                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
83975                         return getSymbolOfNode(parent);
83976                     }
83977                 // falls through
83978                 case 8 /* NumericLiteral */:
83979                     // index access
83980                     var objectType = ts.isElementAccessExpression(parent)
83981                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
83982                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
83983                             ? getTypeFromTypeNode(grandParent.objectType)
83984                             : undefined;
83985                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
83986                 case 88 /* DefaultKeyword */:
83987                 case 98 /* FunctionKeyword */:
83988                 case 38 /* EqualsGreaterThanToken */:
83989                 case 84 /* ClassKeyword */:
83990                     return getSymbolOfNode(node.parent);
83991                 case 199 /* ImportType */:
83992                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
83993                 case 93 /* ExportKeyword */:
83994                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
83995                 case 100 /* ImportKeyword */:
83996                 case 103 /* NewKeyword */:
83997                     return ts.isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : undefined;
83998                 case 230 /* MetaProperty */:
83999                     return checkExpression(node).symbol;
84000                 default:
84001                     return undefined;
84002             }
84003         }
84004         function getIndexInfosAtLocation(node) {
84005             if (ts.isIdentifier(node) && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) {
84006                 var keyType_1 = getLiteralTypeFromPropertyName(node);
84007                 var objectType = getTypeOfExpression(node.parent.expression);
84008                 var objectTypes = objectType.flags & 1048576 /* Union */ ? objectType.types : [objectType];
84009                 return ts.flatMap(objectTypes, function (t) { return ts.filter(getIndexInfosOfType(t), function (info) { return isApplicableIndexType(keyType_1, info.keyType); }); });
84010             }
84011             return undefined;
84012         }
84013         function getShorthandAssignmentValueSymbol(location) {
84014             if (location && location.kind === 295 /* ShorthandPropertyAssignment */) {
84015                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
84016             }
84017             return undefined;
84018         }
84019         /** Returns the target of an export specifier without following aliases */
84020         function getExportSpecifierLocalTargetSymbol(node) {
84021             if (ts.isExportSpecifier(node)) {
84022                 return node.parent.parent.moduleSpecifier ?
84023                     getExternalModuleMember(node.parent.parent, node) :
84024                     resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
84025             }
84026             else {
84027                 return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
84028             }
84029         }
84030         function getTypeOfNode(node) {
84031             if (ts.isSourceFile(node) && !ts.isExternalModule(node)) {
84032                 return errorType;
84033             }
84034             if (node.flags & 16777216 /* InWithStatement */) {
84035                 // We cannot answer semantic questions within a with block, do not proceed any further
84036                 return errorType;
84037             }
84038             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
84039             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
84040             if (ts.isPartOfTypeNode(node)) {
84041                 var typeFromTypeNode = getTypeFromTypeNode(node);
84042                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
84043             }
84044             if (ts.isExpressionNode(node)) {
84045                 return getRegularTypeOfExpression(node);
84046             }
84047             if (classType && !classDecl.isImplements) {
84048                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
84049                 // extends clause of a class. We handle that case here.
84050                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
84051                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
84052             }
84053             if (isTypeDeclaration(node)) {
84054                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
84055                 var symbol = getSymbolOfNode(node);
84056                 return getDeclaredTypeOfSymbol(symbol);
84057             }
84058             if (isTypeDeclarationName(node)) {
84059                 var symbol = getSymbolAtLocation(node);
84060                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
84061             }
84062             if (ts.isDeclaration(node)) {
84063                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
84064                 var symbol = getSymbolOfNode(node);
84065                 return getTypeOfSymbol(symbol);
84066             }
84067             if (isDeclarationNameOrImportPropertyName(node)) {
84068                 var symbol = getSymbolAtLocation(node);
84069                 if (symbol) {
84070                     return getTypeOfSymbol(symbol);
84071                 }
84072                 return errorType;
84073             }
84074             if (ts.isBindingPattern(node)) {
84075                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
84076             }
84077             if (isInRightSideOfImportOrExportAssignment(node)) {
84078                 var symbol = getSymbolAtLocation(node);
84079                 if (symbol) {
84080                     var declaredType = getDeclaredTypeOfSymbol(symbol);
84081                     return !isErrorType(declaredType) ? declaredType : getTypeOfSymbol(symbol);
84082                 }
84083             }
84084             if (ts.isMetaProperty(node.parent) && node.parent.keywordToken === node.kind) {
84085                 return checkMetaPropertyKeyword(node.parent);
84086             }
84087             return errorType;
84088         }
84089         // Gets the type of object literal or array literal of destructuring assignment.
84090         // { a } from
84091         //     for ( { a } of elems) {
84092         //     }
84093         // [ a ] from
84094         //     [a] = [ some array ...]
84095         function getTypeOfAssignmentPattern(expr) {
84096             ts.Debug.assert(expr.kind === 204 /* ObjectLiteralExpression */ || expr.kind === 203 /* ArrayLiteralExpression */);
84097             // If this is from "for of"
84098             //     for ( { a } of elems) {
84099             //     }
84100             if (expr.parent.kind === 243 /* ForOfStatement */) {
84101                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
84102                 return checkDestructuringAssignment(expr, iteratedType || errorType);
84103             }
84104             // If this is from "for" initializer
84105             //     for ({a } = elems[0];.....) { }
84106             if (expr.parent.kind === 220 /* BinaryExpression */) {
84107                 var iteratedType = getTypeOfExpression(expr.parent.right);
84108                 return checkDestructuringAssignment(expr, iteratedType || errorType);
84109             }
84110             // If this is from nested object binding pattern
84111             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
84112             if (expr.parent.kind === 294 /* PropertyAssignment */) {
84113                 var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
84114                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType;
84115                 var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent);
84116                 return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex);
84117             }
84118             // Array literal assignment - array destructuring pattern
84119             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
84120             //    [{ property1: p1, property2 }] = elems;
84121             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
84122             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
84123             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
84124         }
84125         // Gets the property symbol corresponding to the property in destructuring assignment
84126         // 'property1' from
84127         //     for ( { property1: a } of elems) {
84128         //     }
84129         // 'property1' at location 'a' from:
84130         //     [a] = [ property1, property2 ]
84131         function getPropertySymbolOfDestructuringAssignment(location) {
84132             // Get the type of the object or array literal and then look for property of given name in the type
84133             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
84134             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
84135         }
84136         function getRegularTypeOfExpression(expr) {
84137             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
84138                 expr = expr.parent;
84139             }
84140             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
84141         }
84142         /**
84143          * Gets either the static or instance type of a class element, based on
84144          * whether the element is declared as "static".
84145          */
84146         function getParentTypeOfClassElement(node) {
84147             var classSymbol = getSymbolOfNode(node.parent);
84148             return ts.isStatic(node)
84149                 ? getTypeOfSymbol(classSymbol)
84150                 : getDeclaredTypeOfSymbol(classSymbol);
84151         }
84152         function getClassElementPropertyKeyType(element) {
84153             var name = element.name;
84154             switch (name.kind) {
84155                 case 79 /* Identifier */:
84156                     return getStringLiteralType(ts.idText(name));
84157                 case 8 /* NumericLiteral */:
84158                 case 10 /* StringLiteral */:
84159                     return getStringLiteralType(name.text);
84160                 case 161 /* ComputedPropertyName */:
84161                     var nameType = checkComputedPropertyName(name);
84162                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
84163                 default:
84164                     return ts.Debug.fail("Unsupported property name.");
84165             }
84166         }
84167         // Return the list of properties of the given type, augmented with properties from Function
84168         // if the type has call or construct signatures
84169         function getAugmentedPropertiesOfType(type) {
84170             type = getApparentType(type);
84171             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
84172             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
84173                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
84174                     undefined;
84175             if (functionType) {
84176                 ts.forEach(getPropertiesOfType(functionType), function (p) {
84177                     if (!propsByName.has(p.escapedName)) {
84178                         propsByName.set(p.escapedName, p);
84179                     }
84180                 });
84181             }
84182             return getNamedMembers(propsByName);
84183         }
84184         function typeHasCallOrConstructSignatures(type) {
84185             return ts.typeHasCallOrConstructSignatures(type, checker);
84186         }
84187         function getRootSymbols(symbol) {
84188             var roots = getImmediateRootSymbols(symbol);
84189             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
84190         }
84191         function getImmediateRootSymbols(symbol) {
84192             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
84193                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
84194             }
84195             else if (symbol.flags & 33554432 /* Transient */) {
84196                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
84197                 return leftSpread ? [leftSpread, rightSpread]
84198                     : syntheticOrigin ? [syntheticOrigin]
84199                         : ts.singleElementArray(tryGetAliasTarget(symbol));
84200             }
84201             return undefined;
84202         }
84203         function tryGetAliasTarget(symbol) {
84204             var target;
84205             var next = symbol;
84206             while (next = getSymbolLinks(next).target) {
84207                 target = next;
84208             }
84209             return target;
84210         }
84211         // Emitter support
84212         function isArgumentsLocalBinding(nodeIn) {
84213             // Note: does not handle isShorthandPropertyAssignment (and probably a few more)
84214             if (ts.isGeneratedIdentifier(nodeIn))
84215                 return false;
84216             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
84217             if (!node)
84218                 return false;
84219             var parent = node.parent;
84220             if (!parent)
84221                 return false;
84222             var isPropertyName = ((ts.isPropertyAccessExpression(parent)
84223                 || ts.isPropertyAssignment(parent))
84224                 && parent.name === node);
84225             return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol;
84226         }
84227         function moduleExportsSomeValue(moduleReferenceExpression) {
84228             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
84229             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
84230                 // If the module is not found or is shorthand, assume that it may export a value.
84231                 return true;
84232             }
84233             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
84234             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
84235             // otherwise it will return moduleSymbol itself
84236             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
84237             var symbolLinks = getSymbolLinks(moduleSymbol);
84238             if (symbolLinks.exportsSomeValue === undefined) {
84239                 // for export assignments - check if resolved symbol for RHS is itself a value
84240                 // otherwise - check if at least one export is value
84241                 symbolLinks.exportsSomeValue = hasExportAssignment
84242                     ? !!(moduleSymbol.flags & 111551 /* Value */)
84243                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
84244             }
84245             return symbolLinks.exportsSomeValue;
84246             function isValue(s) {
84247                 s = resolveSymbol(s);
84248                 return s && !!(s.flags & 111551 /* Value */);
84249             }
84250         }
84251         function isNameOfModuleOrEnumDeclaration(node) {
84252             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
84253         }
84254         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
84255         // node of the exported entity's container. Otherwise, return undefined.
84256         function getReferencedExportContainer(nodeIn, prefixLocals) {
84257             var _a;
84258             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
84259             if (node) {
84260                 // When resolving the export container for the name of a module or enum
84261                 // declaration, we need to start resolution at the declaration's container.
84262                 // Otherwise, we could incorrectly resolve the export container as the
84263                 // declaration if it contains an exported member with the same name.
84264                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
84265                 if (symbol) {
84266                     if (symbol.flags & 1048576 /* ExportValue */) {
84267                         // If we reference an exported entity within the same module declaration, then whether
84268                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
84269                         // kinds that we do NOT prefix.
84270                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
84271                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
84272                             return undefined;
84273                         }
84274                         symbol = exportSymbol;
84275                     }
84276                     var parentSymbol_1 = getParentOfSymbol(symbol);
84277                     if (parentSymbol_1) {
84278                         if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 303 /* SourceFile */) {
84279                             var symbolFile = parentSymbol_1.valueDeclaration;
84280                             var referenceFile = ts.getSourceFileOfNode(node);
84281                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
84282                             var symbolIsUmdExport = symbolFile !== referenceFile;
84283                             return symbolIsUmdExport ? undefined : symbolFile;
84284                         }
84285                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
84286                     }
84287                 }
84288             }
84289         }
84290         // When resolved as an expression identifier, if the given node references an import, return the declaration of
84291         // that import. Otherwise, return undefined.
84292         function getReferencedImportDeclaration(nodeIn) {
84293             if (nodeIn.generatedImportReference) {
84294                 return nodeIn.generatedImportReference;
84295             }
84296             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
84297             if (node) {
84298                 var symbol = getReferencedValueSymbol(node);
84299                 // We should only get the declaration of an alias if there isn't a local value
84300                 // declaration for the symbol
84301                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
84302                     return getDeclarationOfAliasSymbol(symbol);
84303                 }
84304             }
84305             return undefined;
84306         }
84307         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
84308             return symbol.valueDeclaration
84309                 && ts.isBindingElement(symbol.valueDeclaration)
84310                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 291 /* CatchClause */;
84311         }
84312         function isSymbolOfDeclarationWithCollidingName(symbol) {
84313             if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) {
84314                 var links = getSymbolLinks(symbol);
84315                 if (links.isDeclarationWithCollidingName === undefined) {
84316                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
84317                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
84318                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
84319                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
84320                             // redeclaration - always should be renamed
84321                             links.isDeclarationWithCollidingName = true;
84322                         }
84323                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
84324                             // binding is captured in the function
84325                             // should be renamed if:
84326                             // - binding is not top level - top level bindings never collide with anything
84327                             // AND
84328                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
84329                             //     let a, b
84330                             //     { let x = 1; a = () => x; }
84331                             //     { let x = 100; b = () => x; }
84332                             //     console.log(a()); // should print '1'
84333                             //     console.log(b()); // should print '100'
84334                             //     OR
84335                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
84336                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
84337                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
84338                             //       they will not collide with anything
84339                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
84340                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
84341                             var inLoopBodyBlock = container.kind === 234 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
84342                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
84343                         }
84344                         else {
84345                             links.isDeclarationWithCollidingName = false;
84346                         }
84347                     }
84348                 }
84349                 return links.isDeclarationWithCollidingName;
84350             }
84351             return false;
84352         }
84353         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
84354         // a name that either hides an existing name or might hide it when compiled downlevel,
84355         // return the declaration of that entity. Otherwise, return undefined.
84356         function getReferencedDeclarationWithCollidingName(nodeIn) {
84357             if (!ts.isGeneratedIdentifier(nodeIn)) {
84358                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
84359                 if (node) {
84360                     var symbol = getReferencedValueSymbol(node);
84361                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
84362                         return symbol.valueDeclaration;
84363                     }
84364                 }
84365             }
84366             return undefined;
84367         }
84368         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
84369         // existing name or might hide a name when compiled downlevel
84370         function isDeclarationWithCollidingName(nodeIn) {
84371             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
84372             if (node) {
84373                 var symbol = getSymbolOfNode(node);
84374                 if (symbol) {
84375                     return isSymbolOfDeclarationWithCollidingName(symbol);
84376                 }
84377             }
84378             return false;
84379         }
84380         function isValueAliasDeclaration(node) {
84381             switch (node.kind) {
84382                 case 264 /* ImportEqualsDeclaration */:
84383                     return isAliasResolvedToValue(getSymbolOfNode(node));
84384                 case 266 /* ImportClause */:
84385                 case 267 /* NamespaceImport */:
84386                 case 269 /* ImportSpecifier */:
84387                 case 274 /* ExportSpecifier */:
84388                     var symbol = getSymbolOfNode(node);
84389                     return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
84390                 case 271 /* ExportDeclaration */:
84391                     var exportClause = node.exportClause;
84392                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
84393                         ts.some(exportClause.elements, isValueAliasDeclaration));
84394                 case 270 /* ExportAssignment */:
84395                     return node.expression && node.expression.kind === 79 /* Identifier */ ?
84396                         isAliasResolvedToValue(getSymbolOfNode(node)) :
84397                         true;
84398             }
84399             return false;
84400         }
84401         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
84402             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
84403             if (node === undefined || node.parent.kind !== 303 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
84404                 // parent is not source file or it is not reference to internal module
84405                 return false;
84406             }
84407             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
84408             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
84409         }
84410         function isAliasResolvedToValue(symbol) {
84411             if (!symbol) {
84412                 return false;
84413             }
84414             var target = resolveAlias(symbol);
84415             if (target === unknownSymbol) {
84416                 return true;
84417             }
84418             // const enums and modules that contain only const enums are not considered values from the emit perspective
84419             // unless 'preserveConstEnums' option is set to true
84420             return !!(target.flags & 111551 /* Value */) &&
84421                 (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
84422         }
84423         function isConstEnumOrConstEnumOnlyModule(s) {
84424             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
84425         }
84426         function isReferencedAliasDeclaration(node, checkChildren) {
84427             if (isAliasSymbolDeclaration(node)) {
84428                 var symbol = getSymbolOfNode(node);
84429                 var links = symbol && getSymbolLinks(symbol);
84430                 if (links === null || links === void 0 ? void 0 : links.referenced) {
84431                     return true;
84432                 }
84433                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
84434                 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
84435                     target.flags & 111551 /* Value */ &&
84436                     (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
84437                     // An `export import ... =` of a value symbol is always considered referenced
84438                     return true;
84439                 }
84440             }
84441             if (checkChildren) {
84442                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
84443             }
84444             return false;
84445         }
84446         function isImplementationOfOverload(node) {
84447             if (ts.nodeIsPresent(node.body)) {
84448                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
84449                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
84450                 var symbol = getSymbolOfNode(node);
84451                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
84452                 // If this function body corresponds to function with multiple signature, it is implementation of overload
84453                 // e.g.: function foo(a: string): string;
84454                 //       function foo(a: number): number;
84455                 //       function foo(a: any) { // This is implementation of the overloads
84456                 //           return a;
84457                 //       }
84458                 return signaturesOfSymbol.length > 1 ||
84459                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
84460                     // e.g.: function foo(a: string): string;
84461                     //       function foo(a: any) { // This is implementation of the overloads
84462                     //           return a;
84463                     //       }
84464                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
84465             }
84466             return false;
84467         }
84468         function isRequiredInitializedParameter(parameter) {
84469             return !!strictNullChecks &&
84470                 !isOptionalParameter(parameter) &&
84471                 !ts.isJSDocParameterTag(parameter) &&
84472                 !!parameter.initializer &&
84473                 !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */);
84474         }
84475         function isOptionalUninitializedParameterProperty(parameter) {
84476             return strictNullChecks &&
84477                 isOptionalParameter(parameter) &&
84478                 !parameter.initializer &&
84479                 ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */);
84480         }
84481         function isOptionalUninitializedParameter(parameter) {
84482             return !!strictNullChecks &&
84483                 isOptionalParameter(parameter) &&
84484                 !parameter.initializer;
84485         }
84486         function isExpandoFunctionDeclaration(node) {
84487             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
84488             if (!declaration) {
84489                 return false;
84490             }
84491             var symbol = getSymbolOfNode(declaration);
84492             if (!symbol || !(symbol.flags & 16 /* Function */)) {
84493                 return false;
84494             }
84495             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
84496         }
84497         function getPropertiesOfContainerFunction(node) {
84498             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
84499             if (!declaration) {
84500                 return ts.emptyArray;
84501             }
84502             var symbol = getSymbolOfNode(declaration);
84503             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
84504         }
84505         function getNodeCheckFlags(node) {
84506             var _a;
84507             var nodeId = node.id || 0;
84508             if (nodeId < 0 || nodeId >= nodeLinks.length)
84509                 return 0;
84510             return ((_a = nodeLinks[nodeId]) === null || _a === void 0 ? void 0 : _a.flags) || 0;
84511         }
84512         function getEnumMemberValue(node) {
84513             computeEnumMemberValues(node.parent);
84514             return getNodeLinks(node).enumMemberValue;
84515         }
84516         function canHaveConstantValue(node) {
84517             switch (node.kind) {
84518                 case 297 /* EnumMember */:
84519                 case 205 /* PropertyAccessExpression */:
84520                 case 206 /* ElementAccessExpression */:
84521                     return true;
84522             }
84523             return false;
84524         }
84525         function getConstantValue(node) {
84526             if (node.kind === 297 /* EnumMember */) {
84527                 return getEnumMemberValue(node);
84528             }
84529             var symbol = getNodeLinks(node).resolvedSymbol;
84530             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
84531                 // inline property\index accesses only for const enums
84532                 var member = symbol.valueDeclaration;
84533                 if (ts.isEnumConst(member.parent)) {
84534                     return getEnumMemberValue(member);
84535                 }
84536             }
84537             return undefined;
84538         }
84539         function isFunctionType(type) {
84540             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
84541         }
84542         function getTypeReferenceSerializationKind(typeNameIn, location) {
84543             var _a, _b;
84544             // ensure both `typeName` and `location` are parse tree nodes.
84545             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
84546             if (!typeName)
84547                 return ts.TypeReferenceSerializationKind.Unknown;
84548             if (location) {
84549                 location = ts.getParseTreeNode(location);
84550                 if (!location)
84551                     return ts.TypeReferenceSerializationKind.Unknown;
84552             }
84553             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
84554             var isTypeOnly = false;
84555             if (ts.isQualifiedName(typeName)) {
84556                 var rootValueSymbol = resolveEntityName(ts.getFirstIdentifier(typeName), 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
84557                 isTypeOnly = !!((_a = rootValueSymbol === null || rootValueSymbol === void 0 ? void 0 : rootValueSymbol.declarations) === null || _a === void 0 ? void 0 : _a.every(ts.isTypeOnlyImportOrExportDeclaration));
84558             }
84559             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
84560             var resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
84561             isTypeOnly || (isTypeOnly = !!((_b = valueSymbol === null || valueSymbol === void 0 ? void 0 : valueSymbol.declarations) === null || _b === void 0 ? void 0 : _b.every(ts.isTypeOnlyImportOrExportDeclaration)));
84562             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
84563             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
84564             if (resolvedSymbol && resolvedSymbol === typeSymbol) {
84565                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
84566                 if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) {
84567                     return ts.TypeReferenceSerializationKind.Promise;
84568                 }
84569                 var constructorType = getTypeOfSymbol(resolvedSymbol);
84570                 if (constructorType && isConstructorType(constructorType)) {
84571                     return isTypeOnly ? ts.TypeReferenceSerializationKind.TypeWithCallSignature : ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
84572                 }
84573             }
84574             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
84575             if (!typeSymbol) {
84576                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
84577             }
84578             var type = getDeclaredTypeOfSymbol(typeSymbol);
84579             if (isErrorType(type)) {
84580                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
84581             }
84582             else if (type.flags & 3 /* AnyOrUnknown */) {
84583                 return ts.TypeReferenceSerializationKind.ObjectType;
84584             }
84585             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
84586                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
84587             }
84588             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
84589                 return ts.TypeReferenceSerializationKind.BooleanType;
84590             }
84591             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
84592                 return ts.TypeReferenceSerializationKind.NumberLikeType;
84593             }
84594             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
84595                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
84596             }
84597             else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
84598                 return ts.TypeReferenceSerializationKind.StringLikeType;
84599             }
84600             else if (isTupleType(type)) {
84601                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
84602             }
84603             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
84604                 return ts.TypeReferenceSerializationKind.ESSymbolType;
84605             }
84606             else if (isFunctionType(type)) {
84607                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
84608             }
84609             else if (isArrayType(type)) {
84610                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
84611             }
84612             else {
84613                 return ts.TypeReferenceSerializationKind.ObjectType;
84614             }
84615         }
84616         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
84617             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
84618             if (!declaration) {
84619                 return ts.factory.createToken(130 /* AnyKeyword */);
84620             }
84621             // Get type of the symbol if this is the valid symbol otherwise get type at location
84622             var symbol = getSymbolOfNode(declaration);
84623             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
84624                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
84625                 : errorType;
84626             if (type.flags & 8192 /* UniqueESSymbol */ &&
84627                 type.symbol === symbol) {
84628                 flags |= 1048576 /* AllowUniqueESSymbolType */;
84629             }
84630             if (addUndefined) {
84631                 type = getOptionalType(type);
84632             }
84633             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
84634         }
84635         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
84636             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
84637             if (!signatureDeclaration) {
84638                 return ts.factory.createToken(130 /* AnyKeyword */);
84639             }
84640             var signature = getSignatureFromDeclaration(signatureDeclaration);
84641             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
84642         }
84643         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
84644             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
84645             if (!expr) {
84646                 return ts.factory.createToken(130 /* AnyKeyword */);
84647             }
84648             var type = getWidenedType(getRegularTypeOfExpression(expr));
84649             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
84650         }
84651         function hasGlobalName(name) {
84652             return globals.has(ts.escapeLeadingUnderscores(name));
84653         }
84654         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
84655             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
84656             if (resolvedSymbol) {
84657                 return resolvedSymbol;
84658             }
84659             var location = reference;
84660             if (startInDeclarationContainer) {
84661                 // When resolving the name of a declaration as a value, we need to start resolution
84662                 // at a point outside of the declaration.
84663                 var parent = reference.parent;
84664                 if (ts.isDeclaration(parent) && reference === parent.name) {
84665                     location = getDeclarationContainer(parent);
84666                 }
84667             }
84668             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
84669         }
84670         function getReferencedValueDeclaration(referenceIn) {
84671             if (!ts.isGeneratedIdentifier(referenceIn)) {
84672                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
84673                 if (reference) {
84674                     var symbol = getReferencedValueSymbol(reference);
84675                     if (symbol) {
84676                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
84677                     }
84678                 }
84679             }
84680             return undefined;
84681         }
84682         function isLiteralConstDeclaration(node) {
84683             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
84684                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
84685             }
84686             return false;
84687         }
84688         function literalTypeToNode(type, enclosing, tracker) {
84689             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
84690                 : type === trueType ? ts.factory.createTrue() : type === falseType && ts.factory.createFalse();
84691             if (enumResult)
84692                 return enumResult;
84693             var literalValue = type.value;
84694             return typeof literalValue === "object" ? ts.factory.createBigIntLiteral(literalValue) :
84695                 typeof literalValue === "number" ? ts.factory.createNumericLiteral(literalValue) :
84696                     ts.factory.createStringLiteral(literalValue);
84697         }
84698         function createLiteralConstValue(node, tracker) {
84699             var type = getTypeOfSymbol(getSymbolOfNode(node));
84700             return literalTypeToNode(type, node, tracker);
84701         }
84702         function getJsxFactoryEntity(location) {
84703             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
84704         }
84705         function getJsxFragmentFactoryEntity(location) {
84706             if (location) {
84707                 var file = ts.getSourceFileOfNode(location);
84708                 if (file) {
84709                     if (file.localJsxFragmentFactory) {
84710                         return file.localJsxFragmentFactory;
84711                     }
84712                     var jsxFragPragmas = file.pragmas.get("jsxfrag");
84713                     var jsxFragPragma = ts.isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
84714                     if (jsxFragPragma) {
84715                         file.localJsxFragmentFactory = ts.parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
84716                         return file.localJsxFragmentFactory;
84717                     }
84718                 }
84719             }
84720             if (compilerOptions.jsxFragmentFactory) {
84721                 return ts.parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
84722             }
84723         }
84724         function createResolver() {
84725             // this variable and functions that use it are deliberately moved here from the outer scope
84726             // to avoid scope pollution
84727             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
84728             var fileToDirective;
84729             if (resolvedTypeReferenceDirectives) {
84730                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
84731                 fileToDirective = new ts.Map();
84732                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
84733                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
84734                         return;
84735                     }
84736                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
84737                     if (file) {
84738                         // Add the transitive closure of path references loaded by this file (as long as they are not)
84739                         // part of an existing type reference.
84740                         addReferencedFilesToTypeDirective(file, key);
84741                     }
84742                 });
84743             }
84744             return {
84745                 getReferencedExportContainer: getReferencedExportContainer,
84746                 getReferencedImportDeclaration: getReferencedImportDeclaration,
84747                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
84748                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
84749                 isValueAliasDeclaration: function (nodeIn) {
84750                     var node = ts.getParseTreeNode(nodeIn);
84751                     // Synthesized nodes are always treated like values.
84752                     return node ? isValueAliasDeclaration(node) : true;
84753                 },
84754                 hasGlobalName: hasGlobalName,
84755                 isReferencedAliasDeclaration: function (nodeIn, checkChildren) {
84756                     var node = ts.getParseTreeNode(nodeIn);
84757                     // Synthesized nodes are always treated as referenced.
84758                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
84759                 },
84760                 getNodeCheckFlags: function (nodeIn) {
84761                     var node = ts.getParseTreeNode(nodeIn);
84762                     return node ? getNodeCheckFlags(node) : 0;
84763                 },
84764                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
84765                 isDeclarationVisible: isDeclarationVisible,
84766                 isImplementationOfOverload: isImplementationOfOverload,
84767                 isRequiredInitializedParameter: isRequiredInitializedParameter,
84768                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
84769                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
84770                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
84771                 createTypeOfDeclaration: createTypeOfDeclaration,
84772                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
84773                 createTypeOfExpression: createTypeOfExpression,
84774                 createLiteralConstValue: createLiteralConstValue,
84775                 isSymbolAccessible: isSymbolAccessible,
84776                 isEntityNameVisible: isEntityNameVisible,
84777                 getConstantValue: function (nodeIn) {
84778                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
84779                     return node ? getConstantValue(node) : undefined;
84780                 },
84781                 collectLinkedAliases: collectLinkedAliases,
84782                 getReferencedValueDeclaration: getReferencedValueDeclaration,
84783                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
84784                 isOptionalParameter: isOptionalParameter,
84785                 moduleExportsSomeValue: moduleExportsSomeValue,
84786                 isArgumentsLocalBinding: isArgumentsLocalBinding,
84787                 getExternalModuleFileFromDeclaration: function (nodeIn) {
84788                     var node = ts.getParseTreeNode(nodeIn, ts.hasPossibleExternalModuleReference);
84789                     return node && getExternalModuleFileFromDeclaration(node);
84790                 },
84791                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
84792                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
84793                 isLiteralConstDeclaration: isLiteralConstDeclaration,
84794                 isLateBound: function (nodeIn) {
84795                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
84796                     var symbol = node && getSymbolOfNode(node);
84797                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
84798                 },
84799                 getJsxFactoryEntity: getJsxFactoryEntity,
84800                 getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity,
84801                 getAllAccessorDeclarations: function (accessor) {
84802                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
84803                     var otherKind = accessor.kind === 172 /* SetAccessor */ ? 171 /* GetAccessor */ : 172 /* SetAccessor */;
84804                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
84805                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
84806                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
84807                     var setAccessor = accessor.kind === 172 /* SetAccessor */ ? accessor : otherAccessor;
84808                     var getAccessor = accessor.kind === 171 /* GetAccessor */ ? accessor : otherAccessor;
84809                     return {
84810                         firstAccessor: firstAccessor,
84811                         secondAccessor: secondAccessor,
84812                         setAccessor: setAccessor,
84813                         getAccessor: getAccessor
84814                     };
84815                 },
84816                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
84817                 isBindingCapturedByNode: function (node, decl) {
84818                     var parseNode = ts.getParseTreeNode(node);
84819                     var parseDecl = ts.getParseTreeNode(decl);
84820                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
84821                 },
84822                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
84823                     var n = ts.getParseTreeNode(node);
84824                     ts.Debug.assert(n && n.kind === 303 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
84825                     var sym = getSymbolOfNode(node);
84826                     if (!sym) {
84827                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
84828                     }
84829                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
84830                 },
84831                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
84832             };
84833             function isImportRequiredByAugmentation(node) {
84834                 var file = ts.getSourceFileOfNode(node);
84835                 if (!file.symbol)
84836                     return false;
84837                 var importTarget = getExternalModuleFileFromDeclaration(node);
84838                 if (!importTarget)
84839                     return false;
84840                 if (importTarget === file)
84841                     return false;
84842                 var exports = getExportsOfModule(file.symbol);
84843                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
84844                     var s = _a[_i];
84845                     if (s.mergeId) {
84846                         var merged = getMergedSymbol(s);
84847                         if (merged.declarations) {
84848                             for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
84849                                 var d = _c[_b];
84850                                 var declFile = ts.getSourceFileOfNode(d);
84851                                 if (declFile === importTarget) {
84852                                     return true;
84853                                 }
84854                             }
84855                         }
84856                     }
84857                 }
84858                 return false;
84859             }
84860             function isInHeritageClause(node) {
84861                 return node.parent && node.parent.kind === 227 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 290 /* HeritageClause */;
84862             }
84863             // defined here to avoid outer scope pollution
84864             function getTypeReferenceDirectivesForEntityName(node) {
84865                 // program does not have any files with type reference directives - bail out
84866                 if (!fileToDirective) {
84867                     return undefined;
84868                 }
84869                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
84870                 // qualified names can only be used as types\namespaces
84871                 // identifiers are treated as values only if they appear in type queries
84872                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
84873                 if ((node.kind === 79 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 205 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
84874                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
84875                 }
84876                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
84877                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
84878             }
84879             // defined here to avoid outer scope pollution
84880             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
84881                 // program does not have any files with type reference directives - bail out
84882                 if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) {
84883                     return undefined;
84884                 }
84885                 // check what declarations in the symbol can contribute to the target meaning
84886                 var typeReferenceDirectives;
84887                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
84888                     var decl = _a[_i];
84889                     // check meaning of the local symbol to see if declaration needs to be analyzed further
84890                     if (decl.symbol && decl.symbol.flags & meaning) {
84891                         var file = ts.getSourceFileOfNode(decl);
84892                         var typeReferenceDirective = fileToDirective.get(file.path);
84893                         if (typeReferenceDirective) {
84894                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
84895                         }
84896                         else {
84897                             // found at least one entry that does not originate from type reference directive
84898                             return undefined;
84899                         }
84900                     }
84901                 }
84902                 return typeReferenceDirectives;
84903             }
84904             function isSymbolFromTypeDeclarationFile(symbol) {
84905                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
84906                 if (!symbol.declarations) {
84907                     return false;
84908                 }
84909                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
84910                 // external modules cannot define or contribute to type declaration files
84911                 var current = symbol;
84912                 while (true) {
84913                     var parent = getParentOfSymbol(current);
84914                     if (parent) {
84915                         current = parent;
84916                     }
84917                     else {
84918                         break;
84919                     }
84920                 }
84921                 if (current.valueDeclaration && current.valueDeclaration.kind === 303 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
84922                     return false;
84923                 }
84924                 // check that at least one declaration of top level symbol originates from type declaration file
84925                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
84926                     var decl = _a[_i];
84927                     var file = ts.getSourceFileOfNode(decl);
84928                     if (fileToDirective.has(file.path)) {
84929                         return true;
84930                     }
84931                 }
84932                 return false;
84933             }
84934             function addReferencedFilesToTypeDirective(file, key) {
84935                 if (fileToDirective.has(file.path))
84936                     return;
84937                 fileToDirective.set(file.path, key);
84938                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
84939                     var fileName = _a[_i].fileName;
84940                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
84941                     var referencedFile = host.getSourceFile(resolvedFile);
84942                     if (referencedFile) {
84943                         addReferencedFilesToTypeDirective(referencedFile, key);
84944                     }
84945                 }
84946             }
84947         }
84948         function getExternalModuleFileFromDeclaration(declaration) {
84949             var specifier = declaration.kind === 260 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
84950             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
84951             if (!moduleSymbol) {
84952                 return undefined;
84953             }
84954             return ts.getDeclarationOfKind(moduleSymbol, 303 /* SourceFile */);
84955         }
84956         function initializeTypeChecker() {
84957             // Bind all source files and propagate errors
84958             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
84959                 var file = _a[_i];
84960                 ts.bindSourceFile(file, compilerOptions);
84961             }
84962             amalgamatedDuplicates = new ts.Map();
84963             // Initialize global symbol table
84964             var augmentations;
84965             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
84966                 var file = _c[_b];
84967                 if (file.redirectInfo) {
84968                     continue;
84969                 }
84970                 if (!ts.isExternalOrCommonJsModule(file)) {
84971                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
84972                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
84973                     var fileGlobalThisSymbol = file.locals.get("globalThis");
84974                     if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) {
84975                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
84976                             var declaration = _e[_d];
84977                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
84978                         }
84979                     }
84980                     mergeSymbolTable(globals, file.locals);
84981                 }
84982                 if (file.jsGlobalAugmentations) {
84983                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
84984                 }
84985                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
84986                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
84987                 }
84988                 if (file.moduleAugmentations.length) {
84989                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
84990                 }
84991                 if (file.symbol && file.symbol.globalExports) {
84992                     // Merge in UMD exports with first-in-wins semantics (see #9771)
84993                     var source = file.symbol.globalExports;
84994                     source.forEach(function (sourceSymbol, id) {
84995                         if (!globals.has(id)) {
84996                             globals.set(id, sourceSymbol);
84997                         }
84998                     });
84999                 }
85000             }
85001             // We do global augmentations separately from module augmentations (and before creating global types) because they
85002             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
85003             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
85004             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
85005             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
85006             //       did module augmentations prior to finalizing the global types.
85007             if (augmentations) {
85008                 // merge _global_ module augmentations.
85009                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
85010                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
85011                     var list = augmentations_1[_f];
85012                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
85013                         var augmentation = list_1[_g];
85014                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
85015                             continue;
85016                         mergeModuleAugmentation(augmentation);
85017                     }
85018                 }
85019             }
85020             // Setup global builtins
85021             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
85022             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
85023             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
85024             getSymbolLinks(unknownSymbol).type = errorType;
85025             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
85026             // Initialize special types
85027             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
85028             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
85029             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
85030             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
85031             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
85032             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
85033             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
85034             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
85035             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
85036             anyArrayType = createArrayType(anyType);
85037             autoArrayType = createArrayType(autoType);
85038             if (autoArrayType === emptyObjectType) {
85039                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
85040                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray);
85041             }
85042             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
85043             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
85044             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
85045             if (augmentations) {
85046                 // merge _nonglobal_ module augmentations.
85047                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
85048                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
85049                     var list = augmentations_2[_h];
85050                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
85051                         var augmentation = list_2[_j];
85052                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
85053                             continue;
85054                         mergeModuleAugmentation(augmentation);
85055                     }
85056                 }
85057             }
85058             amalgamatedDuplicates.forEach(function (_a) {
85059                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
85060                 // If not many things conflict, issue individual errors
85061                 if (conflictingSymbols.size < 8) {
85062                     conflictingSymbols.forEach(function (_a, symbolName) {
85063                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
85064                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
85065                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
85066                             var node = firstFileLocations_1[_i];
85067                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
85068                         }
85069                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
85070                             var node = secondFileLocations_1[_b];
85071                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
85072                         }
85073                     });
85074                 }
85075                 else {
85076                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
85077                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
85078                     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)));
85079                     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)));
85080                 }
85081             });
85082             amalgamatedDuplicates = undefined;
85083         }
85084         function checkExternalEmitHelpers(location, helpers) {
85085             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
85086                 var sourceFile = ts.getSourceFileOfNode(location);
85087                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
85088                     var helpersModule = resolveHelpersModule(sourceFile, location);
85089                     if (helpersModule !== unknownSymbol) {
85090                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
85091                         for (var helper = 1 /* FirstEmitHelper */; helper <= 4194304 /* LastEmitHelper */; helper <<= 1) {
85092                             if (uncheckedHelpers & helper) {
85093                                 var name = getHelperName(helper);
85094                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
85095                                 if (!symbol) {
85096                                     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);
85097                                 }
85098                                 else if (helper & 524288 /* ClassPrivateFieldGet */) {
85099                                     if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) {
85100                                         error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4);
85101                                     }
85102                                 }
85103                                 else if (helper & 1048576 /* ClassPrivateFieldSet */) {
85104                                     if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) {
85105                                         error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5);
85106                                     }
85107                                 }
85108                                 else if (helper & 1024 /* SpreadArray */) {
85109                                     if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 2; })) {
85110                                         error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 3);
85111                                     }
85112                                 }
85113                             }
85114                         }
85115                     }
85116                     requestedExternalEmitHelpers |= helpers;
85117                 }
85118             }
85119         }
85120         function getHelperName(helper) {
85121             switch (helper) {
85122                 case 1 /* Extends */: return "__extends";
85123                 case 2 /* Assign */: return "__assign";
85124                 case 4 /* Rest */: return "__rest";
85125                 case 8 /* Decorate */: return "__decorate";
85126                 case 16 /* Metadata */: return "__metadata";
85127                 case 32 /* Param */: return "__param";
85128                 case 64 /* Awaiter */: return "__awaiter";
85129                 case 128 /* Generator */: return "__generator";
85130                 case 256 /* Values */: return "__values";
85131                 case 512 /* Read */: return "__read";
85132                 case 1024 /* SpreadArray */: return "__spreadArray";
85133                 case 2048 /* Await */: return "__await";
85134                 case 4096 /* AsyncGenerator */: return "__asyncGenerator";
85135                 case 8192 /* AsyncDelegator */: return "__asyncDelegator";
85136                 case 16384 /* AsyncValues */: return "__asyncValues";
85137                 case 32768 /* ExportStar */: return "__exportStar";
85138                 case 65536 /* ImportStar */: return "__importStar";
85139                 case 131072 /* ImportDefault */: return "__importDefault";
85140                 case 262144 /* MakeTemplateObject */: return "__makeTemplateObject";
85141                 case 524288 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
85142                 case 1048576 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
85143                 case 2097152 /* ClassPrivateFieldIn */: return "__classPrivateFieldIn";
85144                 case 4194304 /* CreateBinding */: return "__createBinding";
85145                 default: return ts.Debug.fail("Unrecognized helper");
85146             }
85147         }
85148         function resolveHelpersModule(node, errorNode) {
85149             if (!externalHelpersModule) {
85150                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
85151             }
85152             return externalHelpersModule;
85153         }
85154         // GRAMMAR CHECKING
85155         function checkGrammarDecoratorsAndModifiers(node) {
85156             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
85157         }
85158         function checkGrammarDecorators(node) {
85159             if (!node.decorators) {
85160                 return false;
85161             }
85162             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
85163                 if (node.kind === 168 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
85164                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
85165                 }
85166                 else {
85167                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
85168                 }
85169             }
85170             else if (node.kind === 171 /* GetAccessor */ || node.kind === 172 /* SetAccessor */) {
85171                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
85172                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
85173                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
85174                 }
85175             }
85176             return false;
85177         }
85178         function checkGrammarModifiers(node) {
85179             var quickResult = reportObviousModifierErrors(node);
85180             if (quickResult !== undefined) {
85181                 return quickResult;
85182             }
85183             var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride;
85184             var flags = 0 /* None */;
85185             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
85186                 var modifier = _a[_i];
85187                 if (modifier.kind !== 144 /* ReadonlyKeyword */) {
85188                     if (node.kind === 165 /* PropertySignature */ || node.kind === 167 /* MethodSignature */) {
85189                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
85190                     }
85191                     if (node.kind === 175 /* IndexSignature */ && (modifier.kind !== 124 /* StaticKeyword */ || !ts.isClassLike(node.parent))) {
85192                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
85193                     }
85194                 }
85195                 switch (modifier.kind) {
85196                     case 85 /* ConstKeyword */:
85197                         if (node.kind !== 259 /* EnumDeclaration */) {
85198                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(85 /* ConstKeyword */));
85199                         }
85200                         break;
85201                     case 158 /* OverrideKeyword */:
85202                         // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property.
85203                         if (flags & 16384 /* Override */) {
85204                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override");
85205                         }
85206                         else if (flags & 2 /* Ambient */) {
85207                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare");
85208                         }
85209                         else if (flags & 64 /* Readonly */) {
85210                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly");
85211                         }
85212                         else if (flags & 256 /* Async */) {
85213                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async");
85214                         }
85215                         flags |= 16384 /* Override */;
85216                         lastOverride = modifier;
85217                         break;
85218                     case 123 /* PublicKeyword */:
85219                     case 122 /* ProtectedKeyword */:
85220                     case 121 /* PrivateKeyword */:
85221                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
85222                         if (flags & 28 /* AccessibilityModifier */) {
85223                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
85224                         }
85225                         else if (flags & 16384 /* Override */) {
85226                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override");
85227                         }
85228                         else if (flags & 32 /* Static */) {
85229                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
85230                         }
85231                         else if (flags & 64 /* Readonly */) {
85232                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
85233                         }
85234                         else if (flags & 256 /* Async */) {
85235                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
85236                         }
85237                         else if (node.parent.kind === 261 /* ModuleBlock */ || node.parent.kind === 303 /* SourceFile */) {
85238                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
85239                         }
85240                         else if (flags & 128 /* Abstract */) {
85241                             if (modifier.kind === 121 /* PrivateKeyword */) {
85242                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
85243                             }
85244                             else {
85245                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
85246                             }
85247                         }
85248                         else if (ts.isPrivateIdentifierClassElementDeclaration(node)) {
85249                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
85250                         }
85251                         flags |= ts.modifierToFlag(modifier.kind);
85252                         break;
85253                     case 124 /* StaticKeyword */:
85254                         if (flags & 32 /* Static */) {
85255                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
85256                         }
85257                         else if (flags & 64 /* Readonly */) {
85258                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
85259                         }
85260                         else if (flags & 256 /* Async */) {
85261                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
85262                         }
85263                         else if (node.parent.kind === 261 /* ModuleBlock */ || node.parent.kind === 303 /* SourceFile */) {
85264                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
85265                         }
85266                         else if (node.kind === 163 /* Parameter */) {
85267                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
85268                         }
85269                         else if (flags & 128 /* Abstract */) {
85270                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
85271                         }
85272                         else if (flags & 16384 /* Override */) {
85273                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override");
85274                         }
85275                         flags |= 32 /* Static */;
85276                         lastStatic = modifier;
85277                         break;
85278                     case 144 /* ReadonlyKeyword */:
85279                         if (flags & 64 /* Readonly */) {
85280                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
85281                         }
85282                         else if (node.kind !== 166 /* PropertyDeclaration */ && node.kind !== 165 /* PropertySignature */ && node.kind !== 175 /* IndexSignature */ && node.kind !== 163 /* Parameter */) {
85283                             // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property.
85284                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
85285                         }
85286                         flags |= 64 /* Readonly */;
85287                         lastReadonly = modifier;
85288                         break;
85289                     case 93 /* ExportKeyword */:
85290                         if (flags & 1 /* Export */) {
85291                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
85292                         }
85293                         else if (flags & 2 /* Ambient */) {
85294                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
85295                         }
85296                         else if (flags & 128 /* Abstract */) {
85297                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
85298                         }
85299                         else if (flags & 256 /* Async */) {
85300                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
85301                         }
85302                         else if (ts.isClassLike(node.parent)) {
85303                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
85304                         }
85305                         else if (node.kind === 163 /* Parameter */) {
85306                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
85307                         }
85308                         flags |= 1 /* Export */;
85309                         break;
85310                     case 88 /* DefaultKeyword */:
85311                         var container = node.parent.kind === 303 /* SourceFile */ ? node.parent : node.parent.parent;
85312                         if (container.kind === 260 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
85313                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
85314                         }
85315                         else if (!(flags & 1 /* Export */)) {
85316                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "default");
85317                         }
85318                         flags |= 512 /* Default */;
85319                         break;
85320                     case 135 /* DeclareKeyword */:
85321                         if (flags & 2 /* Ambient */) {
85322                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
85323                         }
85324                         else if (flags & 256 /* Async */) {
85325                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
85326                         }
85327                         else if (flags & 16384 /* Override */) {
85328                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override");
85329                         }
85330                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
85331                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
85332                         }
85333                         else if (node.kind === 163 /* Parameter */) {
85334                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
85335                         }
85336                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 261 /* ModuleBlock */) {
85337                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
85338                         }
85339                         else if (ts.isPrivateIdentifierClassElementDeclaration(node)) {
85340                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
85341                         }
85342                         flags |= 2 /* Ambient */;
85343                         lastDeclare = modifier;
85344                         break;
85345                     case 126 /* AbstractKeyword */:
85346                         if (flags & 128 /* Abstract */) {
85347                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
85348                         }
85349                         if (node.kind !== 256 /* ClassDeclaration */ &&
85350                             node.kind !== 179 /* ConstructorType */) {
85351                             if (node.kind !== 168 /* MethodDeclaration */ &&
85352                                 node.kind !== 166 /* PropertyDeclaration */ &&
85353                                 node.kind !== 171 /* GetAccessor */ &&
85354                                 node.kind !== 172 /* SetAccessor */) {
85355                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
85356                             }
85357                             if (!(node.parent.kind === 256 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) {
85358                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
85359                             }
85360                             if (flags & 32 /* Static */) {
85361                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
85362                             }
85363                             if (flags & 8 /* Private */) {
85364                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
85365                             }
85366                             if (flags & 256 /* Async */ && lastAsync) {
85367                                 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
85368                             }
85369                             if (flags & 16384 /* Override */) {
85370                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override");
85371                             }
85372                         }
85373                         if (ts.isNamedDeclaration(node) && node.name.kind === 80 /* PrivateIdentifier */) {
85374                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
85375                         }
85376                         flags |= 128 /* Abstract */;
85377                         break;
85378                     case 131 /* AsyncKeyword */:
85379                         if (flags & 256 /* Async */) {
85380                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
85381                         }
85382                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
85383                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
85384                         }
85385                         else if (node.kind === 163 /* Parameter */) {
85386                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
85387                         }
85388                         if (flags & 128 /* Abstract */) {
85389                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
85390                         }
85391                         flags |= 256 /* Async */;
85392                         lastAsync = modifier;
85393                         break;
85394                 }
85395             }
85396             if (node.kind === 170 /* Constructor */) {
85397                 if (flags & 32 /* Static */) {
85398                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
85399                 }
85400                 if (flags & 128 /* Abstract */) {
85401                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
85402                 }
85403                 if (flags & 16384 /* Override */) {
85404                     return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217
85405                 }
85406                 else if (flags & 256 /* Async */) {
85407                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
85408                 }
85409                 else if (flags & 64 /* Readonly */) {
85410                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
85411                 }
85412                 return false;
85413             }
85414             else if ((node.kind === 265 /* ImportDeclaration */ || node.kind === 264 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
85415                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
85416             }
85417             else if (node.kind === 163 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
85418                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
85419             }
85420             else if (node.kind === 163 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
85421                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
85422             }
85423             if (flags & 256 /* Async */) {
85424                 return checkGrammarAsyncModifier(node, lastAsync);
85425             }
85426             return false;
85427         }
85428         /**
85429          * true | false: Early return this value from checkGrammarModifiers.
85430          * undefined: Need to do full checking on the modifiers.
85431          */
85432         function reportObviousModifierErrors(node) {
85433             return !node.modifiers
85434                 ? false
85435                 : shouldReportBadModifier(node)
85436                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
85437                     : undefined;
85438         }
85439         function shouldReportBadModifier(node) {
85440             switch (node.kind) {
85441                 case 171 /* GetAccessor */:
85442                 case 172 /* SetAccessor */:
85443                 case 170 /* Constructor */:
85444                 case 166 /* PropertyDeclaration */:
85445                 case 165 /* PropertySignature */:
85446                 case 168 /* MethodDeclaration */:
85447                 case 167 /* MethodSignature */:
85448                 case 175 /* IndexSignature */:
85449                 case 260 /* ModuleDeclaration */:
85450                 case 265 /* ImportDeclaration */:
85451                 case 264 /* ImportEqualsDeclaration */:
85452                 case 271 /* ExportDeclaration */:
85453                 case 270 /* ExportAssignment */:
85454                 case 212 /* FunctionExpression */:
85455                 case 213 /* ArrowFunction */:
85456                 case 163 /* Parameter */:
85457                     return false;
85458                 default:
85459                     if (node.parent.kind === 261 /* ModuleBlock */ || node.parent.kind === 303 /* SourceFile */) {
85460                         return false;
85461                     }
85462                     switch (node.kind) {
85463                         case 255 /* FunctionDeclaration */:
85464                             return nodeHasAnyModifiersExcept(node, 131 /* AsyncKeyword */);
85465                         case 256 /* ClassDeclaration */:
85466                         case 179 /* ConstructorType */:
85467                             return nodeHasAnyModifiersExcept(node, 126 /* AbstractKeyword */);
85468                         case 257 /* InterfaceDeclaration */:
85469                         case 236 /* VariableStatement */:
85470                         case 258 /* TypeAliasDeclaration */:
85471                         case 169 /* ClassStaticBlockDeclaration */:
85472                             return true;
85473                         case 259 /* EnumDeclaration */:
85474                             return nodeHasAnyModifiersExcept(node, 85 /* ConstKeyword */);
85475                         default:
85476                             ts.Debug.fail();
85477                     }
85478             }
85479         }
85480         function nodeHasAnyModifiersExcept(node, allowedModifier) {
85481             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
85482         }
85483         function checkGrammarAsyncModifier(node, asyncModifier) {
85484             switch (node.kind) {
85485                 case 168 /* MethodDeclaration */:
85486                 case 255 /* FunctionDeclaration */:
85487                 case 212 /* FunctionExpression */:
85488                 case 213 /* ArrowFunction */:
85489                     return false;
85490             }
85491             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
85492         }
85493         function checkGrammarForDisallowedTrailingComma(list, diag) {
85494             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
85495             if (list && list.hasTrailingComma) {
85496                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
85497             }
85498             return false;
85499         }
85500         function checkGrammarTypeParameterList(typeParameters, file) {
85501             if (typeParameters && typeParameters.length === 0) {
85502                 var start = typeParameters.pos - "<".length;
85503                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
85504                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
85505             }
85506             return false;
85507         }
85508         function checkGrammarParameterList(parameters) {
85509             var seenOptionalParameter = false;
85510             var parameterCount = parameters.length;
85511             for (var i = 0; i < parameterCount; i++) {
85512                 var parameter = parameters[i];
85513                 if (parameter.dotDotDotToken) {
85514                     if (i !== (parameterCount - 1)) {
85515                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
85516                     }
85517                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
85518                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
85519                     }
85520                     if (parameter.questionToken) {
85521                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
85522                     }
85523                     if (parameter.initializer) {
85524                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
85525                     }
85526                 }
85527                 else if (isOptionalParameter(parameter)) {
85528                     seenOptionalParameter = true;
85529                     if (parameter.questionToken && parameter.initializer) {
85530                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
85531                     }
85532                 }
85533                 else if (seenOptionalParameter && !parameter.initializer) {
85534                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
85535                 }
85536             }
85537         }
85538         function getNonSimpleParameters(parameters) {
85539             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
85540         }
85541         function checkGrammarForUseStrictSimpleParameterList(node) {
85542             if (languageVersion >= 3 /* ES2016 */) {
85543                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
85544                 if (useStrictDirective_1) {
85545                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
85546                     if (ts.length(nonSimpleParameters)) {
85547                         ts.forEach(nonSimpleParameters, function (parameter) {
85548                             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));
85549                         });
85550                         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)); });
85551                         ts.addRelatedInfo.apply(void 0, __spreadArray([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2, false));
85552                         return true;
85553                     }
85554                 }
85555             }
85556             return false;
85557         }
85558         function checkGrammarFunctionLikeDeclaration(node) {
85559             // Prevent cascading error by short-circuit
85560             var file = ts.getSourceFileOfNode(node);
85561             return checkGrammarDecoratorsAndModifiers(node) ||
85562                 checkGrammarTypeParameterList(node.typeParameters, file) ||
85563                 checkGrammarParameterList(node.parameters) ||
85564                 checkGrammarArrowFunction(node, file) ||
85565                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
85566         }
85567         function checkGrammarClassLikeDeclaration(node) {
85568             var file = ts.getSourceFileOfNode(node);
85569             return checkGrammarClassDeclarationHeritageClauses(node) ||
85570                 checkGrammarTypeParameterList(node.typeParameters, file);
85571         }
85572         function checkGrammarArrowFunction(node, file) {
85573             if (!ts.isArrowFunction(node)) {
85574                 return false;
85575             }
85576             if (node.typeParameters && !(ts.length(node.typeParameters) > 1 || node.typeParameters.hasTrailingComma || node.typeParameters[0].constraint)) {
85577                 if (file && ts.fileExtensionIsOneOf(file.fileName, [".mts" /* Mts */, ".cts" /* Cts */])) {
85578                     grammarErrorOnNode(node.typeParameters[0], ts.Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint);
85579                 }
85580             }
85581             var equalsGreaterThanToken = node.equalsGreaterThanToken;
85582             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
85583             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
85584             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
85585         }
85586         function checkGrammarIndexSignatureParameters(node) {
85587             var parameter = node.parameters[0];
85588             if (node.parameters.length !== 1) {
85589                 if (parameter) {
85590                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
85591                 }
85592                 else {
85593                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
85594                 }
85595             }
85596             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
85597             if (parameter.dotDotDotToken) {
85598                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
85599             }
85600             if (ts.hasEffectiveModifiers(parameter)) {
85601                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
85602             }
85603             if (parameter.questionToken) {
85604                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
85605             }
85606             if (parameter.initializer) {
85607                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
85608             }
85609             if (!parameter.type) {
85610                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
85611             }
85612             var type = getTypeFromTypeNode(parameter.type);
85613             if (someType(type, function (t) { return !!(t.flags & 8576 /* StringOrNumberLiteralOrUnique */); }) || isGenericType(type)) {
85614                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead);
85615             }
85616             if (!everyType(type, isValidIndexKeyType)) {
85617                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type);
85618             }
85619             if (!node.type) {
85620                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
85621             }
85622             return false;
85623         }
85624         function checkGrammarIndexSignature(node) {
85625             // Prevent cascading error by short-circuit
85626             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
85627         }
85628         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
85629             if (typeArguments && typeArguments.length === 0) {
85630                 var sourceFile = ts.getSourceFileOfNode(node);
85631                 var start = typeArguments.pos - "<".length;
85632                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
85633                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
85634             }
85635             return false;
85636         }
85637         function checkGrammarTypeArguments(node, typeArguments) {
85638             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
85639                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
85640         }
85641         function checkGrammarTaggedTemplateChain(node) {
85642             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
85643                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
85644             }
85645             return false;
85646         }
85647         function checkGrammarForOmittedArgument(args) {
85648             if (args) {
85649                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
85650                     var arg = args_4[_i];
85651                     if (arg.kind === 226 /* OmittedExpression */) {
85652                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
85653                     }
85654                 }
85655             }
85656             return false;
85657         }
85658         function checkGrammarArguments(args) {
85659             return checkGrammarForOmittedArgument(args);
85660         }
85661         function checkGrammarHeritageClause(node) {
85662             var types = node.types;
85663             if (checkGrammarForDisallowedTrailingComma(types)) {
85664                 return true;
85665             }
85666             if (types && types.length === 0) {
85667                 var listType = ts.tokenToString(node.token);
85668                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
85669             }
85670             return ts.some(types, checkGrammarExpressionWithTypeArguments);
85671         }
85672         function checkGrammarExpressionWithTypeArguments(node) {
85673             return checkGrammarTypeArguments(node, node.typeArguments);
85674         }
85675         function checkGrammarClassDeclarationHeritageClauses(node) {
85676             var seenExtendsClause = false;
85677             var seenImplementsClause = false;
85678             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
85679                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
85680                     var heritageClause = _a[_i];
85681                     if (heritageClause.token === 94 /* ExtendsKeyword */) {
85682                         if (seenExtendsClause) {
85683                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
85684                         }
85685                         if (seenImplementsClause) {
85686                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
85687                         }
85688                         if (heritageClause.types.length > 1) {
85689                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
85690                         }
85691                         seenExtendsClause = true;
85692                     }
85693                     else {
85694                         ts.Debug.assert(heritageClause.token === 117 /* ImplementsKeyword */);
85695                         if (seenImplementsClause) {
85696                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
85697                         }
85698                         seenImplementsClause = true;
85699                     }
85700                     // Grammar checking heritageClause inside class declaration
85701                     checkGrammarHeritageClause(heritageClause);
85702                 }
85703             }
85704         }
85705         function checkGrammarInterfaceDeclaration(node) {
85706             var seenExtendsClause = false;
85707             if (node.heritageClauses) {
85708                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
85709                     var heritageClause = _a[_i];
85710                     if (heritageClause.token === 94 /* ExtendsKeyword */) {
85711                         if (seenExtendsClause) {
85712                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
85713                         }
85714                         seenExtendsClause = true;
85715                     }
85716                     else {
85717                         ts.Debug.assert(heritageClause.token === 117 /* ImplementsKeyword */);
85718                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
85719                     }
85720                     // Grammar checking heritageClause inside class declaration
85721                     checkGrammarHeritageClause(heritageClause);
85722                 }
85723             }
85724             return false;
85725         }
85726         function checkGrammarComputedPropertyName(node) {
85727             // If node is not a computedPropertyName, just skip the grammar checking
85728             if (node.kind !== 161 /* ComputedPropertyName */) {
85729                 return false;
85730             }
85731             var computedPropertyName = node;
85732             if (computedPropertyName.expression.kind === 220 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
85733                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
85734             }
85735             return false;
85736         }
85737         function checkGrammarForGenerator(node) {
85738             if (node.asteriskToken) {
85739                 ts.Debug.assert(node.kind === 255 /* FunctionDeclaration */ ||
85740                     node.kind === 212 /* FunctionExpression */ ||
85741                     node.kind === 168 /* MethodDeclaration */);
85742                 if (node.flags & 8388608 /* Ambient */) {
85743                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
85744                 }
85745                 if (!node.body) {
85746                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
85747                 }
85748             }
85749         }
85750         function checkGrammarForInvalidQuestionMark(questionToken, message) {
85751             return !!questionToken && grammarErrorOnNode(questionToken, message);
85752         }
85753         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
85754             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
85755         }
85756         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
85757             var seen = new ts.Map();
85758             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
85759                 var prop = _a[_i];
85760                 if (prop.kind === 296 /* SpreadAssignment */) {
85761                     if (inDestructuring) {
85762                         // a rest property cannot be destructured any further
85763                         var expression = ts.skipParentheses(prop.expression);
85764                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
85765                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
85766                         }
85767                     }
85768                     continue;
85769                 }
85770                 var name = prop.name;
85771                 if (name.kind === 161 /* ComputedPropertyName */) {
85772                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
85773                     checkGrammarComputedPropertyName(name);
85774                 }
85775                 if (prop.kind === 295 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
85776                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
85777                     // outside of destructuring it is a syntax error
85778                     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);
85779                 }
85780                 if (name.kind === 80 /* PrivateIdentifier */) {
85781                     grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
85782                 }
85783                 // Modifiers are never allowed on properties except for 'async' on a method declaration
85784                 if (prop.modifiers) {
85785                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
85786                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
85787                         var mod = _c[_b];
85788                         if (mod.kind !== 131 /* AsyncKeyword */ || prop.kind !== 168 /* MethodDeclaration */) {
85789                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
85790                         }
85791                     }
85792                 }
85793                 // ECMA-262 11.1.5 Object Initializer
85794                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
85795                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
85796                 // IsDataDescriptor(propId.descriptor) is true.
85797                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
85798                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
85799                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
85800                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
85801                 var currentKind = void 0;
85802                 switch (prop.kind) {
85803                     case 295 /* ShorthandPropertyAssignment */:
85804                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
85805                     // falls through
85806                     case 294 /* PropertyAssignment */:
85807                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
85808                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
85809                         if (name.kind === 8 /* NumericLiteral */) {
85810                             checkGrammarNumericLiteral(name);
85811                         }
85812                         currentKind = 4 /* PropertyAssignment */;
85813                         break;
85814                     case 168 /* MethodDeclaration */:
85815                         currentKind = 8 /* Method */;
85816                         break;
85817                     case 171 /* GetAccessor */:
85818                         currentKind = 1 /* GetAccessor */;
85819                         break;
85820                     case 172 /* SetAccessor */:
85821                         currentKind = 2 /* SetAccessor */;
85822                         break;
85823                     default:
85824                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
85825                 }
85826                 if (!inDestructuring) {
85827                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
85828                     if (effectiveName === undefined) {
85829                         continue;
85830                     }
85831                     var existingKind = seen.get(effectiveName);
85832                     if (!existingKind) {
85833                         seen.set(effectiveName, currentKind);
85834                     }
85835                     else {
85836                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
85837                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
85838                         }
85839                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
85840                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
85841                                 seen.set(effectiveName, currentKind | existingKind);
85842                             }
85843                             else {
85844                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
85845                             }
85846                         }
85847                         else {
85848                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
85849                         }
85850                     }
85851                 }
85852             }
85853         }
85854         function checkGrammarJsxElement(node) {
85855             checkGrammarJsxName(node.tagName);
85856             checkGrammarTypeArguments(node, node.typeArguments);
85857             var seen = new ts.Map();
85858             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
85859                 var attr = _a[_i];
85860                 if (attr.kind === 286 /* JsxSpreadAttribute */) {
85861                     continue;
85862                 }
85863                 var name = attr.name, initializer = attr.initializer;
85864                 if (!seen.get(name.escapedText)) {
85865                     seen.set(name.escapedText, true);
85866                 }
85867                 else {
85868                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
85869                 }
85870                 if (initializer && initializer.kind === 287 /* JsxExpression */ && !initializer.expression) {
85871                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
85872                 }
85873             }
85874         }
85875         function checkGrammarJsxName(node) {
85876             if (ts.isPropertyAccessExpression(node)) {
85877                 var propName = node;
85878                 do {
85879                     var check_1 = checkGrammarJsxNestedIdentifier(propName.name);
85880                     if (check_1) {
85881                         return check_1;
85882                     }
85883                     propName = propName.expression;
85884                 } while (ts.isPropertyAccessExpression(propName));
85885                 var check = checkGrammarJsxNestedIdentifier(propName);
85886                 if (check) {
85887                     return check;
85888                 }
85889             }
85890             function checkGrammarJsxNestedIdentifier(name) {
85891                 if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) {
85892                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names);
85893                 }
85894             }
85895         }
85896         function checkGrammarJsxExpression(node) {
85897             if (node.expression && ts.isCommaSequence(node.expression)) {
85898                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
85899             }
85900         }
85901         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
85902             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
85903                 return true;
85904             }
85905             if (forInOrOfStatement.kind === 243 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
85906                 if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) {
85907                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
85908                     if (ts.isInTopLevelContext(forInOrOfStatement)) {
85909                         if (!hasParseDiagnostics(sourceFile)) {
85910                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
85911                                 diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_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));
85912                             }
85913                             if ((moduleKind !== ts.ModuleKind.ES2022 && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System && !(moduleKind === ts.ModuleKind.NodeNext && ts.getSourceFileOfNode(forInOrOfStatement).impliedNodeFormat === ts.ModuleKind.ESNext)) || languageVersion < 4 /* ES2017 */) {
85914                                 diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher));
85915                             }
85916                         }
85917                     }
85918                     else {
85919                         // use of 'for-await-of' in non-async function
85920                         if (!hasParseDiagnostics(sourceFile)) {
85921                             var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
85922                             var func = ts.getContainingFunction(forInOrOfStatement);
85923                             if (func && func.kind !== 170 /* Constructor */) {
85924                                 ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
85925                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
85926                                 ts.addRelatedInfo(diagnostic, relatedInfo);
85927                             }
85928                             diagnostics.add(diagnostic);
85929                             return true;
85930                         }
85931                     }
85932                     return false;
85933                 }
85934             }
85935             if (ts.isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 32768 /* AwaitContext */) &&
85936                 ts.isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") {
85937                 grammarErrorOnNode(forInOrOfStatement.initializer, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async);
85938                 return false;
85939             }
85940             if (forInOrOfStatement.initializer.kind === 254 /* VariableDeclarationList */) {
85941                 var variableList = forInOrOfStatement.initializer;
85942                 if (!checkGrammarVariableDeclarationList(variableList)) {
85943                     var declarations = variableList.declarations;
85944                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
85945                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
85946                     // For example:
85947                     //      var let = 10;
85948                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
85949                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
85950                     // We will then want to skip on grammar checking on variableList declaration
85951                     if (!declarations.length) {
85952                         return false;
85953                     }
85954                     if (declarations.length > 1) {
85955                         var diagnostic = forInOrOfStatement.kind === 242 /* ForInStatement */
85956                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
85957                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
85958                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
85959                     }
85960                     var firstDeclaration = declarations[0];
85961                     if (firstDeclaration.initializer) {
85962                         var diagnostic = forInOrOfStatement.kind === 242 /* ForInStatement */
85963                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
85964                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
85965                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
85966                     }
85967                     if (firstDeclaration.type) {
85968                         var diagnostic = forInOrOfStatement.kind === 242 /* ForInStatement */
85969                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
85970                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
85971                         return grammarErrorOnNode(firstDeclaration, diagnostic);
85972                     }
85973                 }
85974             }
85975             return false;
85976         }
85977         function checkGrammarAccessor(accessor) {
85978             if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 181 /* TypeLiteral */) && (accessor.parent.kind !== 257 /* InterfaceDeclaration */)) {
85979                 if (languageVersion < 1 /* ES5 */) {
85980                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
85981                 }
85982                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) {
85983                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
85984                 }
85985                 if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
85986                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
85987                 }
85988             }
85989             if (accessor.body) {
85990                 if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
85991                     return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
85992                 }
85993                 if (accessor.parent.kind === 181 /* TypeLiteral */ || accessor.parent.kind === 257 /* InterfaceDeclaration */) {
85994                     return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
85995                 }
85996             }
85997             if (accessor.typeParameters) {
85998                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
85999             }
86000             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
86001                 return grammarErrorOnNode(accessor.name, accessor.kind === 171 /* GetAccessor */ ?
86002                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
86003                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
86004             }
86005             if (accessor.kind === 172 /* SetAccessor */) {
86006                 if (accessor.type) {
86007                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
86008                 }
86009                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
86010                 if (parameter.dotDotDotToken) {
86011                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
86012                 }
86013                 if (parameter.questionToken) {
86014                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
86015                 }
86016                 if (parameter.initializer) {
86017                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
86018                 }
86019             }
86020             return false;
86021         }
86022         /** Does the accessor have the right number of parameters?
86023          * A get accessor has no parameters or a single `this` parameter.
86024          * A set accessor has one parameter or a `this` parameter and one more parameter.
86025          */
86026         function doesAccessorHaveCorrectParameterCount(accessor) {
86027             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 171 /* GetAccessor */ ? 0 : 1);
86028         }
86029         function getAccessorThisParameter(accessor) {
86030             if (accessor.parameters.length === (accessor.kind === 171 /* GetAccessor */ ? 1 : 2)) {
86031                 return ts.getThisParameter(accessor);
86032             }
86033         }
86034         function checkGrammarTypeOperatorNode(node) {
86035             if (node.operator === 153 /* UniqueKeyword */) {
86036                 if (node.type.kind !== 150 /* SymbolKeyword */) {
86037                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(150 /* SymbolKeyword */));
86038                 }
86039                 var parent = ts.walkUpParenthesizedTypes(node.parent);
86040                 if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) {
86041                     parent = parent.parent;
86042                     if (ts.isJSDocTypeTag(parent)) {
86043                         // walk up past JSDoc comment node
86044                         parent = parent.parent.parent;
86045                     }
86046                 }
86047                 switch (parent.kind) {
86048                     case 253 /* VariableDeclaration */:
86049                         var decl = parent;
86050                         if (decl.name.kind !== 79 /* Identifier */) {
86051                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
86052                         }
86053                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
86054                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
86055                         }
86056                         if (!(decl.parent.flags & 2 /* Const */)) {
86057                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
86058                         }
86059                         break;
86060                     case 166 /* PropertyDeclaration */:
86061                         if (!ts.isStatic(parent) ||
86062                             !ts.hasEffectiveReadonlyModifier(parent)) {
86063                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
86064                         }
86065                         break;
86066                     case 165 /* PropertySignature */:
86067                         if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) {
86068                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
86069                         }
86070                         break;
86071                     default:
86072                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
86073                 }
86074             }
86075             else if (node.operator === 144 /* ReadonlyKeyword */) {
86076                 if (node.type.kind !== 182 /* ArrayType */ && node.type.kind !== 183 /* TupleType */) {
86077                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(150 /* SymbolKeyword */));
86078                 }
86079             }
86080         }
86081         function checkGrammarForInvalidDynamicName(node, message) {
86082             if (isNonBindableDynamicName(node)) {
86083                 return grammarErrorOnNode(node, message);
86084             }
86085         }
86086         function checkGrammarMethod(node) {
86087             if (checkGrammarFunctionLikeDeclaration(node)) {
86088                 return true;
86089             }
86090             if (node.kind === 168 /* MethodDeclaration */) {
86091                 if (node.parent.kind === 204 /* ObjectLiteralExpression */) {
86092                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
86093                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 131 /* AsyncKeyword */)) {
86094                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
86095                     }
86096                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
86097                         return true;
86098                     }
86099                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
86100                         return true;
86101                     }
86102                     else if (node.body === undefined) {
86103                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
86104                     }
86105                 }
86106                 if (checkGrammarForGenerator(node)) {
86107                     return true;
86108                 }
86109             }
86110             if (ts.isClassLike(node.parent)) {
86111                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
86112                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
86113                 }
86114                 // Technically, computed properties in ambient contexts is disallowed
86115                 // for property declarations and accessors too, not just methods.
86116                 // However, property declarations disallow computed names in general,
86117                 // and accessors are not allowed in ambient contexts in general,
86118                 // so this error only really matters for methods.
86119                 if (node.flags & 8388608 /* Ambient */) {
86120                     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);
86121                 }
86122                 else if (node.kind === 168 /* MethodDeclaration */ && !node.body) {
86123                     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);
86124                 }
86125             }
86126             else if (node.parent.kind === 257 /* InterfaceDeclaration */) {
86127                 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);
86128             }
86129             else if (node.parent.kind === 181 /* TypeLiteral */) {
86130                 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);
86131             }
86132         }
86133         function checkGrammarBreakOrContinueStatement(node) {
86134             var current = node;
86135             while (current) {
86136                 if (ts.isFunctionLikeOrClassStaticBlockDeclaration(current)) {
86137                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
86138                 }
86139                 switch (current.kind) {
86140                     case 249 /* LabeledStatement */:
86141                         if (node.label && current.label.escapedText === node.label.escapedText) {
86142                             // found matching label - verify that label usage is correct
86143                             // continue can only target labels that are on iteration statements
86144                             var isMisplacedContinueLabel = node.kind === 244 /* ContinueStatement */
86145                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
86146                             if (isMisplacedContinueLabel) {
86147                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
86148                             }
86149                             return false;
86150                         }
86151                         break;
86152                     case 248 /* SwitchStatement */:
86153                         if (node.kind === 245 /* BreakStatement */ && !node.label) {
86154                             // unlabeled break within switch statement - ok
86155                             return false;
86156                         }
86157                         break;
86158                     default:
86159                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
86160                             // unlabeled break or continue within iteration statement - ok
86161                             return false;
86162                         }
86163                         break;
86164                 }
86165                 current = current.parent;
86166             }
86167             if (node.label) {
86168                 var message = node.kind === 245 /* BreakStatement */
86169                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
86170                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
86171                 return grammarErrorOnNode(node, message);
86172             }
86173             else {
86174                 var message = node.kind === 245 /* BreakStatement */
86175                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
86176                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
86177                 return grammarErrorOnNode(node, message);
86178             }
86179         }
86180         function checkGrammarBindingElement(node) {
86181             if (node.dotDotDotToken) {
86182                 var elements = node.parent.elements;
86183                 if (node !== ts.last(elements)) {
86184                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
86185                 }
86186                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
86187                 if (node.propertyName) {
86188                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
86189                 }
86190             }
86191             if (node.dotDotDotToken && node.initializer) {
86192                 // Error on equals token which immediately precedes the initializer
86193                 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
86194             }
86195         }
86196         function isStringOrNumberLiteralExpression(expr) {
86197             return ts.isStringOrNumericLiteralLike(expr) ||
86198                 expr.kind === 218 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
86199                     expr.operand.kind === 8 /* NumericLiteral */;
86200         }
86201         function isBigIntLiteralExpression(expr) {
86202             return expr.kind === 9 /* BigIntLiteral */ ||
86203                 expr.kind === 218 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
86204                     expr.operand.kind === 9 /* BigIntLiteral */;
86205         }
86206         function isSimpleLiteralEnumReference(expr) {
86207             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
86208                 ts.isEntityNameExpression(expr.expression)) {
86209                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
86210             }
86211         }
86212         function checkAmbientInitializer(node) {
86213             var initializer = node.initializer;
86214             if (initializer) {
86215                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
86216                     isSimpleLiteralEnumReference(initializer) ||
86217                     initializer.kind === 110 /* TrueKeyword */ || initializer.kind === 95 /* FalseKeyword */ ||
86218                     isBigIntLiteralExpression(initializer));
86219                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
86220                 if (isConstOrReadonly && !node.type) {
86221                     if (isInvalidInitializer) {
86222                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
86223                     }
86224                 }
86225                 else {
86226                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
86227                 }
86228                 if (!isConstOrReadonly || isInvalidInitializer) {
86229                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
86230                 }
86231             }
86232         }
86233         function checkGrammarVariableDeclaration(node) {
86234             if (node.parent.parent.kind !== 242 /* ForInStatement */ && node.parent.parent.kind !== 243 /* ForOfStatement */) {
86235                 if (node.flags & 8388608 /* Ambient */) {
86236                     checkAmbientInitializer(node);
86237                 }
86238                 else if (!node.initializer) {
86239                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
86240                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
86241                     }
86242                     if (ts.isVarConst(node)) {
86243                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
86244                     }
86245                 }
86246             }
86247             if (node.exclamationToken && (node.parent.parent.kind !== 236 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
86248                 var message = node.initializer
86249                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
86250                     : !node.type
86251                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
86252                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
86253                 return grammarErrorOnNode(node.exclamationToken, message);
86254             }
86255             if ((moduleKind < ts.ModuleKind.ES2015 || ts.getSourceFileOfNode(node).impliedNodeFormat === ts.ModuleKind.CommonJS) && moduleKind !== ts.ModuleKind.System &&
86256                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
86257                 checkESModuleMarker(node.name);
86258             }
86259             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
86260             // 1. LexicalDeclaration : LetOrConst BindingList ;
86261             // It is a Syntax Error if the BoundNames of BindingList contains "let".
86262             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
86263             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
86264             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
86265             // and its Identifier is eval or arguments
86266             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
86267         }
86268         function checkESModuleMarker(name) {
86269             if (name.kind === 79 /* Identifier */) {
86270                 if (ts.idText(name) === "__esModule") {
86271                     return grammarErrorOnNodeSkippedOn("noEmit", name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
86272                 }
86273             }
86274             else {
86275                 var elements = name.elements;
86276                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
86277                     var element = elements_1[_i];
86278                     if (!ts.isOmittedExpression(element)) {
86279                         return checkESModuleMarker(element.name);
86280                     }
86281                 }
86282             }
86283             return false;
86284         }
86285         function checkGrammarNameInLetOrConstDeclarations(name) {
86286             if (name.kind === 79 /* Identifier */) {
86287                 if (name.originalKeywordKind === 119 /* LetKeyword */) {
86288                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
86289                 }
86290             }
86291             else {
86292                 var elements = name.elements;
86293                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
86294                     var element = elements_2[_i];
86295                     if (!ts.isOmittedExpression(element)) {
86296                         checkGrammarNameInLetOrConstDeclarations(element.name);
86297                     }
86298                 }
86299             }
86300             return false;
86301         }
86302         function checkGrammarVariableDeclarationList(declarationList) {
86303             var declarations = declarationList.declarations;
86304             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
86305                 return true;
86306             }
86307             if (!declarationList.declarations.length) {
86308                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
86309             }
86310             return false;
86311         }
86312         function allowLetAndConstDeclarations(parent) {
86313             switch (parent.kind) {
86314                 case 238 /* IfStatement */:
86315                 case 239 /* DoStatement */:
86316                 case 240 /* WhileStatement */:
86317                 case 247 /* WithStatement */:
86318                 case 241 /* ForStatement */:
86319                 case 242 /* ForInStatement */:
86320                 case 243 /* ForOfStatement */:
86321                     return false;
86322                 case 249 /* LabeledStatement */:
86323                     return allowLetAndConstDeclarations(parent.parent);
86324             }
86325             return true;
86326         }
86327         function checkGrammarForDisallowedLetOrConstStatement(node) {
86328             if (!allowLetAndConstDeclarations(node.parent)) {
86329                 if (ts.isLet(node.declarationList)) {
86330                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
86331                 }
86332                 else if (ts.isVarConst(node.declarationList)) {
86333                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
86334                 }
86335             }
86336         }
86337         function checkGrammarMetaProperty(node) {
86338             var escapedText = node.name.escapedText;
86339             switch (node.keywordToken) {
86340                 case 103 /* NewKeyword */:
86341                     if (escapedText !== "target") {
86342                         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");
86343                     }
86344                     break;
86345                 case 100 /* ImportKeyword */:
86346                     if (escapedText !== "meta") {
86347                         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");
86348                     }
86349                     break;
86350             }
86351         }
86352         function hasParseDiagnostics(sourceFile) {
86353             return sourceFile.parseDiagnostics.length > 0;
86354         }
86355         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
86356             var sourceFile = ts.getSourceFileOfNode(node);
86357             if (!hasParseDiagnostics(sourceFile)) {
86358                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
86359                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
86360                 return true;
86361             }
86362             return false;
86363         }
86364         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
86365             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
86366             if (!hasParseDiagnostics(sourceFile)) {
86367                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
86368                 return true;
86369             }
86370             return false;
86371         }
86372         function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) {
86373             var sourceFile = ts.getSourceFileOfNode(node);
86374             if (!hasParseDiagnostics(sourceFile)) {
86375                 errorSkippedOn(key, node, message, arg0, arg1, arg2);
86376                 return true;
86377             }
86378             return false;
86379         }
86380         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
86381             var sourceFile = ts.getSourceFileOfNode(node);
86382             if (!hasParseDiagnostics(sourceFile)) {
86383                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
86384                 return true;
86385             }
86386             return false;
86387         }
86388         function checkGrammarConstructorTypeParameters(node) {
86389             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
86390             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
86391             if (range) {
86392                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
86393                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
86394             }
86395         }
86396         function checkGrammarConstructorTypeAnnotation(node) {
86397             var type = ts.getEffectiveReturnTypeNode(node);
86398             if (type) {
86399                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
86400             }
86401         }
86402         function checkGrammarProperty(node) {
86403             if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) {
86404                 return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
86405             }
86406             if (ts.isClassLike(node.parent)) {
86407                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
86408                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
86409                 }
86410                 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) {
86411                     return true;
86412                 }
86413                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
86414                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
86415                 }
86416             }
86417             else if (node.parent.kind === 257 /* InterfaceDeclaration */) {
86418                 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)) {
86419                     return true;
86420                 }
86421                 if (node.initializer) {
86422                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
86423                 }
86424             }
86425             else if (ts.isTypeLiteralNode(node.parent)) {
86426                 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)) {
86427                     return true;
86428                 }
86429                 if (node.initializer) {
86430                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
86431                 }
86432             }
86433             if (node.flags & 8388608 /* Ambient */) {
86434                 checkAmbientInitializer(node);
86435             }
86436             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
86437                 node.flags & 8388608 /* Ambient */ || ts.isStatic(node) || ts.hasAbstractModifier(node))) {
86438                 var message = node.initializer
86439                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
86440                     : !node.type
86441                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
86442                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
86443                 return grammarErrorOnNode(node.exclamationToken, message);
86444             }
86445         }
86446         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
86447             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
86448             // interfaces and imports categories:
86449             //
86450             //  DeclarationElement:
86451             //     ExportAssignment
86452             //     export_opt   InterfaceDeclaration
86453             //     export_opt   TypeAliasDeclaration
86454             //     export_opt   ImportDeclaration
86455             //     export_opt   ExternalImportDeclaration
86456             //     export_opt   AmbientDeclaration
86457             //
86458             // TODO: The spec needs to be amended to reflect this grammar.
86459             if (node.kind === 257 /* InterfaceDeclaration */ ||
86460                 node.kind === 258 /* TypeAliasDeclaration */ ||
86461                 node.kind === 265 /* ImportDeclaration */ ||
86462                 node.kind === 264 /* ImportEqualsDeclaration */ ||
86463                 node.kind === 271 /* ExportDeclaration */ ||
86464                 node.kind === 270 /* ExportAssignment */ ||
86465                 node.kind === 263 /* NamespaceExportDeclaration */ ||
86466                 ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
86467                 return false;
86468             }
86469             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
86470         }
86471         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
86472             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
86473                 var decl = _a[_i];
86474                 if (ts.isDeclaration(decl) || decl.kind === 236 /* VariableStatement */) {
86475                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
86476                         return true;
86477                     }
86478                 }
86479             }
86480             return false;
86481         }
86482         function checkGrammarSourceFile(node) {
86483             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
86484         }
86485         function checkGrammarStatementInAmbientContext(node) {
86486             if (node.flags & 8388608 /* Ambient */) {
86487                 // Find containing block which is either Block, ModuleBlock, SourceFile
86488                 var links = getNodeLinks(node);
86489                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
86490                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
86491                 }
86492                 // We are either parented by another statement, or some sort of block.
86493                 // If we're in a block, we only want to really report an error once
86494                 // to prevent noisiness.  So use a bit on the block to indicate if
86495                 // this has already been reported, and don't report if it has.
86496                 //
86497                 if (node.parent.kind === 234 /* Block */ || node.parent.kind === 261 /* ModuleBlock */ || node.parent.kind === 303 /* SourceFile */) {
86498                     var links_2 = getNodeLinks(node.parent);
86499                     // Check if the containing block ever report this error
86500                     if (!links_2.hasReportedStatementInAmbientContext) {
86501                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
86502                     }
86503                 }
86504                 else {
86505                     // We must be parented by a statement.  If so, there's no need
86506                     // to report the error as our parent will have already done it.
86507                     // Debug.assert(isStatement(node.parent));
86508                 }
86509             }
86510             return false;
86511         }
86512         function checkGrammarNumericLiteral(node) {
86513             // Grammar checking
86514             if (node.numericLiteralFlags & 32 /* Octal */) {
86515                 var diagnosticMessage = void 0;
86516                 if (languageVersion >= 1 /* ES5 */) {
86517                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
86518                 }
86519                 else if (ts.isChildOfNodeWithKind(node, 195 /* LiteralType */)) {
86520                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
86521                 }
86522                 else if (ts.isChildOfNodeWithKind(node, 297 /* EnumMember */)) {
86523                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
86524                 }
86525                 if (diagnosticMessage) {
86526                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
86527                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
86528                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
86529                 }
86530             }
86531             // Realism (size) checking
86532             checkNumericLiteralValueSize(node);
86533             return false;
86534         }
86535         function checkNumericLiteralValueSize(node) {
86536             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
86537             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
86538             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
86539             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
86540                 return;
86541             }
86542             // We can't rely on the runtime to accurately store and compare extremely large numeric values
86543             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
86544             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
86545             // it's likely addition operations on it will fail too
86546             var apparentValue = +ts.getTextOfNode(node);
86547             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
86548                 return;
86549             }
86550             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));
86551         }
86552         function checkGrammarBigIntLiteral(node) {
86553             var literalType = ts.isLiteralTypeNode(node.parent) ||
86554                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
86555             if (!literalType) {
86556                 if (languageVersion < 7 /* ES2020 */) {
86557                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
86558                         return true;
86559                     }
86560                 }
86561             }
86562             return false;
86563         }
86564         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
86565             var sourceFile = ts.getSourceFileOfNode(node);
86566             if (!hasParseDiagnostics(sourceFile)) {
86567                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
86568                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
86569                 return true;
86570             }
86571             return false;
86572         }
86573         function getAmbientModules() {
86574             if (!ambientModulesCache) {
86575                 ambientModulesCache = [];
86576                 globals.forEach(function (global, sym) {
86577                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
86578                     if (ambientModuleSymbolRegex.test(sym)) {
86579                         ambientModulesCache.push(global);
86580                     }
86581                 });
86582             }
86583             return ambientModulesCache;
86584         }
86585         function checkGrammarImportClause(node) {
86586             var _a;
86587             if (node.isTypeOnly && node.name && node.namedBindings) {
86588                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
86589             }
86590             if (node.isTypeOnly && ((_a = node.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 268 /* NamedImports */) {
86591                 return checkGrammarNamedImportsOrExports(node.namedBindings);
86592             }
86593             return false;
86594         }
86595         function checkGrammarNamedImportsOrExports(namedBindings) {
86596             return !!ts.forEach(namedBindings.elements, function (specifier) {
86597                 if (specifier.isTypeOnly) {
86598                     return grammarErrorOnFirstToken(specifier, specifier.kind === 269 /* ImportSpecifier */
86599                         ? ts.Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement
86600                         : ts.Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement);
86601                 }
86602             });
86603         }
86604         function checkGrammarImportCallExpression(node) {
86605             if (moduleKind === ts.ModuleKind.ES2015) {
86606                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node12_or_nodenext);
86607             }
86608             if (node.typeArguments) {
86609                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
86610             }
86611             var nodeArguments = node.arguments;
86612             if (moduleKind !== ts.ModuleKind.ESNext) {
86613                 // We are allowed trailing comma after proposal-import-assertions.
86614                 checkGrammarForDisallowedTrailingComma(nodeArguments);
86615                 if (nodeArguments.length > 1) {
86616                     var assertionArgument = nodeArguments[1];
86617                     return grammarErrorOnNode(assertionArgument, ts.Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext);
86618                 }
86619             }
86620             if (nodeArguments.length === 0 || nodeArguments.length > 2) {
86621                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments);
86622             }
86623             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
86624             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
86625             var spreadElement = ts.find(nodeArguments, ts.isSpreadElement);
86626             if (spreadElement) {
86627                 return grammarErrorOnNode(spreadElement, ts.Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element);
86628             }
86629             return false;
86630         }
86631         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
86632             var sourceObjectFlags = ts.getObjectFlags(source);
86633             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
86634                 return ts.find(unionTarget.types, function (target) {
86635                     if (target.flags & 524288 /* Object */) {
86636                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
86637                         if (overlapObjFlags & 4 /* Reference */) {
86638                             return source.target === target.target;
86639                         }
86640                         if (overlapObjFlags & 16 /* Anonymous */) {
86641                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
86642                         }
86643                     }
86644                     return false;
86645                 });
86646             }
86647         }
86648         function findBestTypeForObjectLiteral(source, unionTarget) {
86649             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) {
86650                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
86651             }
86652         }
86653         function findBestTypeForInvokable(source, unionTarget) {
86654             var signatureKind = 0 /* Call */;
86655             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
86656                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
86657             if (hasSignatures) {
86658                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
86659             }
86660         }
86661         function findMostOverlappyType(source, unionTarget) {
86662             var bestMatch;
86663             var matchingCount = 0;
86664             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
86665                 var target = _a[_i];
86666                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
86667                 if (overlap.flags & 4194304 /* Index */) {
86668                     // perfect overlap of keys
86669                     bestMatch = target;
86670                     matchingCount = Infinity;
86671                 }
86672                 else if (overlap.flags & 1048576 /* Union */) {
86673                     // We only want to account for literal types otherwise.
86674                     // If we have a union of index types, it seems likely that we
86675                     // needed to elaborate between two generic mapped types anyway.
86676                     var len = ts.length(ts.filter(overlap.types, isUnitType));
86677                     if (len >= matchingCount) {
86678                         bestMatch = target;
86679                         matchingCount = len;
86680                     }
86681                 }
86682                 else if (isUnitType(overlap) && 1 >= matchingCount) {
86683                     bestMatch = target;
86684                     matchingCount = 1;
86685                 }
86686             }
86687             return bestMatch;
86688         }
86689         function filterPrimitivesIfContainsNonPrimitive(type) {
86690             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
86691                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
86692                 if (!(result.flags & 131072 /* Never */)) {
86693                     return result;
86694                 }
86695             }
86696             return type;
86697         }
86698         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
86699         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
86700             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
86701                 var match = getMatchingUnionConstituentForType(target, source);
86702                 if (match) {
86703                     return match;
86704                 }
86705                 var sourceProperties = getPropertiesOfType(source);
86706                 if (sourceProperties) {
86707                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
86708                     if (sourcePropertiesFiltered) {
86709                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
86710                     }
86711                 }
86712             }
86713             return undefined;
86714         }
86715     }
86716     ts.createTypeChecker = createTypeChecker;
86717     function isNotAccessor(declaration) {
86718         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
86719         return !ts.isAccessor(declaration);
86720     }
86721     function isNotOverload(declaration) {
86722         return (declaration.kind !== 255 /* FunctionDeclaration */ && declaration.kind !== 168 /* MethodDeclaration */) ||
86723             !!declaration.body;
86724     }
86725     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
86726     function isDeclarationNameOrImportPropertyName(name) {
86727         switch (name.parent.kind) {
86728             case 269 /* ImportSpecifier */:
86729             case 274 /* ExportSpecifier */:
86730                 return ts.isIdentifier(name);
86731             default:
86732                 return ts.isDeclarationName(name);
86733         }
86734     }
86735     var JsxNames;
86736     (function (JsxNames) {
86737         JsxNames.JSX = "JSX";
86738         JsxNames.IntrinsicElements = "IntrinsicElements";
86739         JsxNames.ElementClass = "ElementClass";
86740         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
86741         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
86742         JsxNames.Element = "Element";
86743         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
86744         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
86745         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
86746     })(JsxNames || (JsxNames = {}));
86747     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
86748         switch (typeKind) {
86749             case 0 /* Yield */: return "yieldType";
86750             case 1 /* Return */: return "returnType";
86751             case 2 /* Next */: return "nextType";
86752         }
86753     }
86754     function signatureHasRestParameter(s) {
86755         return !!(s.flags & 1 /* HasRestParameter */);
86756     }
86757     ts.signatureHasRestParameter = signatureHasRestParameter;
86758     function signatureHasLiteralTypes(s) {
86759         return !!(s.flags & 2 /* HasLiteralTypes */);
86760     }
86761     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
86762 })(ts || (ts = {}));
86763 var ts;
86764 (function (ts) {
86765     function visitNode(node, visitor, test, lift) {
86766         if (node === undefined || visitor === undefined) {
86767             return node;
86768         }
86769         var visited = visitor(node);
86770         if (visited === node) {
86771             return node;
86772         }
86773         var visitedNode;
86774         if (visited === undefined) {
86775             return undefined;
86776         }
86777         else if (ts.isArray(visited)) {
86778             visitedNode = (lift || extractSingleNode)(visited);
86779         }
86780         else {
86781             visitedNode = visited;
86782         }
86783         ts.Debug.assertNode(visitedNode, test);
86784         return visitedNode;
86785     }
86786     ts.visitNode = visitNode;
86787     /**
86788      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
86789      *
86790      * @param nodes The NodeArray to visit.
86791      * @param visitor The callback used to visit a Node.
86792      * @param test A node test to execute for each node.
86793      * @param start An optional value indicating the starting offset at which to start visiting.
86794      * @param count An optional value indicating the maximum number of nodes to visit.
86795      */
86796     function visitNodes(nodes, visitor, test, start, count) {
86797         if (nodes === undefined || visitor === undefined) {
86798             return nodes;
86799         }
86800         var updated;
86801         // Ensure start and count have valid values
86802         var length = nodes.length;
86803         if (start === undefined || start < 0) {
86804             start = 0;
86805         }
86806         if (count === undefined || count > length - start) {
86807             count = length - start;
86808         }
86809         var hasTrailingComma;
86810         var pos = -1;
86811         var end = -1;
86812         if (start > 0 || count < length) {
86813             // If we are not visiting all of the original nodes, we must always create a new array.
86814             // Since this is a fragment of a node array, we do not copy over the previous location
86815             // and will only copy over `hasTrailingComma` if we are including the last element.
86816             updated = [];
86817             hasTrailingComma = nodes.hasTrailingComma && start + count === length;
86818         }
86819         // Visit each original node.
86820         for (var i = 0; i < count; i++) {
86821             var node = nodes[i + start];
86822             var visited = node !== undefined ? visitor(node) : undefined;
86823             if (updated !== undefined || visited === undefined || visited !== node) {
86824                 if (updated === undefined) {
86825                     // Ensure we have a copy of `nodes`, up to the current index.
86826                     updated = nodes.slice(0, i);
86827                     hasTrailingComma = nodes.hasTrailingComma;
86828                     pos = nodes.pos;
86829                     end = nodes.end;
86830                 }
86831                 if (visited) {
86832                     if (ts.isArray(visited)) {
86833                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
86834                             var visitedNode = visited_1[_i];
86835                             void ts.Debug.assertNode(visitedNode, test);
86836                             updated.push(visitedNode);
86837                         }
86838                     }
86839                     else {
86840                         void ts.Debug.assertNode(visited, test);
86841                         updated.push(visited);
86842                     }
86843                 }
86844             }
86845         }
86846         if (updated) {
86847             // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory.
86848             var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma);
86849             ts.setTextRangePosEnd(updatedArray, pos, end);
86850             return updatedArray;
86851         }
86852         return nodes;
86853     }
86854     ts.visitNodes = visitNodes;
86855     /**
86856      * Starts a new lexical environment and visits a statement list, ending the lexical environment
86857      * and merging hoisted declarations upon completion.
86858      */
86859     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) {
86860         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
86861         context.startLexicalEnvironment();
86862         statements = nodesVisitor(statements, visitor, ts.isStatement, start);
86863         if (ensureUseStrict)
86864             statements = context.factory.ensureUseStrict(statements);
86865         return ts.factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
86866     }
86867     ts.visitLexicalEnvironment = visitLexicalEnvironment;
86868     function visitParameterList(nodes, visitor, context, nodesVisitor) {
86869         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
86870         var updated;
86871         context.startLexicalEnvironment();
86872         if (nodes) {
86873             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
86874             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
86875             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
86876             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
86877             // that we might transform that introduces a temporary variable would fail as the temporary variable
86878             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
86879             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
86880             // when the emit target is greater than ES2015.
86881             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
86882                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
86883                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
86884             }
86885             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
86886         }
86887         context.suspendLexicalEnvironment();
86888         return updated;
86889     }
86890     ts.visitParameterList = visitParameterList;
86891     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
86892         var result;
86893         for (var i = 0; i < parameters.length; i++) {
86894             var parameter = parameters[i];
86895             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
86896             if (result || updated !== parameter) {
86897                 if (!result)
86898                     result = parameters.slice(0, i);
86899                 result[i] = updated;
86900             }
86901         }
86902         if (result) {
86903             return ts.setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
86904         }
86905         return parameters;
86906     }
86907     function addDefaultValueAssignmentIfNeeded(parameter, context) {
86908         // A rest parameter cannot have a binding pattern or an initializer,
86909         // so let's just ignore it.
86910         return parameter.dotDotDotToken ? parameter :
86911             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
86912                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
86913                     parameter;
86914     }
86915     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
86916         var factory = context.factory;
86917         context.addInitializationStatement(factory.createVariableStatement(
86918         /*modifiers*/ undefined, factory.createVariableDeclarationList([
86919             factory.createVariableDeclaration(parameter.name, 
86920             /*exclamationToken*/ undefined, parameter.type, parameter.initializer ?
86921                 factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()), 
86922                 /*questionToken*/ undefined, parameter.initializer, 
86923                 /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) :
86924                 factory.getGeneratedNameForNode(parameter)),
86925         ])));
86926         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
86927         /*initializer*/ undefined);
86928     }
86929     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
86930         var factory = context.factory;
86931         context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
86932             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 */))
86933         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
86934         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
86935         /*initializer*/ undefined);
86936     }
86937     function visitFunctionBody(node, visitor, context, nodeVisitor) {
86938         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
86939         context.resumeLexicalEnvironment();
86940         var updated = nodeVisitor(node, visitor, ts.isConciseBody);
86941         var declarations = context.endLexicalEnvironment();
86942         if (ts.some(declarations)) {
86943             if (!updated) {
86944                 return context.factory.createBlock(declarations);
86945             }
86946             var block = context.factory.converters.convertToFunctionBlock(updated);
86947             var statements = ts.factory.mergeLexicalEnvironment(block.statements, declarations);
86948             return context.factory.updateBlock(block, statements);
86949         }
86950         return updated;
86951     }
86952     ts.visitFunctionBody = visitFunctionBody;
86953     /**
86954      * Visits an iteration body, adding any block-scoped variables required by the transformation.
86955      */
86956     function visitIterationBody(body, visitor, context) {
86957         context.startBlockScope();
86958         var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock);
86959         var declarations = context.endBlockScope();
86960         if (ts.some(declarations)) {
86961             if (ts.isBlock(updated)) {
86962                 declarations.push.apply(declarations, updated.statements);
86963                 return context.factory.updateBlock(updated, declarations);
86964             }
86965             declarations.push(updated);
86966             return context.factory.createBlock(declarations);
86967         }
86968         return updated;
86969     }
86970     ts.visitIterationBody = visitIterationBody;
86971     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) {
86972         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
86973         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
86974         if (node === undefined) {
86975             return undefined;
86976         }
86977         var kind = node.kind;
86978         // No need to visit nodes with no children.
86979         if ((kind > 0 /* FirstToken */ && kind <= 159 /* LastToken */) || kind === 191 /* ThisType */) {
86980             return node;
86981         }
86982         var factory = context.factory;
86983         switch (kind) {
86984             // Names
86985             case 79 /* Identifier */:
86986                 ts.Debug.type(node);
86987                 return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration));
86988             case 160 /* QualifiedName */:
86989                 ts.Debug.type(node);
86990                 return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier));
86991             case 161 /* ComputedPropertyName */:
86992                 ts.Debug.type(node);
86993                 return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression));
86994             // Signature elements
86995             case 162 /* TypeParameter */:
86996                 ts.Debug.type(node);
86997                 return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode));
86998             case 163 /* Parameter */:
86999                 ts.Debug.type(node);
87000                 return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
87001             case 164 /* Decorator */:
87002                 ts.Debug.type(node);
87003                 return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87004             // Type elements
87005             case 165 /* PropertySignature */:
87006                 ts.Debug.type(node);
87007                 return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
87008             case 166 /* PropertyDeclaration */:
87009                 ts.Debug.type(node);
87010                 return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), 
87011                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
87012                 nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
87013             case 167 /* MethodSignature */:
87014                 ts.Debug.type(node);
87015                 return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
87016             case 168 /* MethodDeclaration */:
87017                 ts.Debug.type(node);
87018                 return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
87019             case 170 /* Constructor */:
87020                 ts.Debug.type(node);
87021                 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));
87022             case 171 /* GetAccessor */:
87023                 ts.Debug.type(node);
87024                 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));
87025             case 172 /* SetAccessor */:
87026                 ts.Debug.type(node);
87027                 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));
87028             case 169 /* ClassStaticBlockDeclaration */:
87029                 ts.Debug.type(node);
87030                 context.startLexicalEnvironment();
87031                 context.suspendLexicalEnvironment();
87032                 return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor));
87033             case 173 /* CallSignature */:
87034                 ts.Debug.type(node);
87035                 return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
87036             case 174 /* ConstructSignature */:
87037                 ts.Debug.type(node);
87038                 return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
87039             case 175 /* IndexSignature */:
87040                 ts.Debug.type(node);
87041                 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));
87042             // Types
87043             case 176 /* TypePredicate */:
87044                 ts.Debug.type(node);
87045                 return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode));
87046             case 177 /* TypeReference */:
87047                 ts.Debug.type(node);
87048                 return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
87049             case 178 /* FunctionType */:
87050                 ts.Debug.type(node);
87051                 return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
87052             case 179 /* ConstructorType */:
87053                 ts.Debug.type(node);
87054                 return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
87055             case 180 /* TypeQuery */:
87056                 ts.Debug.type(node);
87057                 return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
87058             case 181 /* TypeLiteral */:
87059                 ts.Debug.type(node);
87060                 return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
87061             case 182 /* ArrayType */:
87062                 ts.Debug.type(node);
87063                 return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode));
87064             case 183 /* TupleType */:
87065                 ts.Debug.type(node);
87066                 return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode));
87067             case 184 /* OptionalType */:
87068                 ts.Debug.type(node);
87069                 return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
87070             case 185 /* RestType */:
87071                 ts.Debug.type(node);
87072                 return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
87073             case 186 /* UnionType */:
87074                 ts.Debug.type(node);
87075                 return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
87076             case 187 /* IntersectionType */:
87077                 ts.Debug.type(node);
87078                 return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
87079             case 188 /* ConditionalType */:
87080                 ts.Debug.type(node);
87081                 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));
87082             case 189 /* InferType */:
87083                 ts.Debug.type(node);
87084                 return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
87085             case 199 /* ImportType */:
87086                 ts.Debug.type(node);
87087                 return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
87088             case 196 /* NamedTupleMember */:
87089                 ts.Debug.type(node);
87090                 return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode));
87091             case 190 /* ParenthesizedType */:
87092                 ts.Debug.type(node);
87093                 return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
87094             case 192 /* TypeOperator */:
87095                 ts.Debug.type(node);
87096                 return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
87097             case 193 /* IndexedAccessType */:
87098                 ts.Debug.type(node);
87099                 return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode));
87100             case 194 /* MappedType */:
87101                 ts.Debug.type(node);
87102                 return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement));
87103             case 195 /* LiteralType */:
87104                 ts.Debug.type(node);
87105                 return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression));
87106             case 197 /* TemplateLiteralType */:
87107                 ts.Debug.type(node);
87108                 return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan));
87109             case 198 /* TemplateLiteralTypeSpan */:
87110                 ts.Debug.type(node);
87111                 return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
87112             // Binding patterns
87113             case 200 /* ObjectBindingPattern */:
87114                 ts.Debug.type(node);
87115                 return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
87116             case 201 /* ArrayBindingPattern */:
87117                 ts.Debug.type(node);
87118                 return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
87119             case 202 /* BindingElement */:
87120                 ts.Debug.type(node);
87121                 return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression));
87122             // Expression
87123             case 203 /* ArrayLiteralExpression */:
87124                 ts.Debug.type(node);
87125                 return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
87126             case 204 /* ObjectLiteralExpression */:
87127                 ts.Debug.type(node);
87128                 return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
87129             case 205 /* PropertyAccessExpression */:
87130                 if (node.flags & 32 /* OptionalChain */) {
87131                     ts.Debug.type(node);
87132                     return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName));
87133                 }
87134                 ts.Debug.type(node);
87135                 return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName));
87136             case 206 /* ElementAccessExpression */:
87137                 if (node.flags & 32 /* OptionalChain */) {
87138                     ts.Debug.type(node);
87139                     return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
87140                 }
87141                 ts.Debug.type(node);
87142                 return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
87143             case 207 /* CallExpression */:
87144                 if (node.flags & 32 /* OptionalChain */) {
87145                     ts.Debug.type(node);
87146                     return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
87147                 }
87148                 ts.Debug.type(node);
87149                 return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
87150             case 208 /* NewExpression */:
87151                 ts.Debug.type(node);
87152                 return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
87153             case 209 /* TaggedTemplateExpression */:
87154                 ts.Debug.type(node);
87155                 return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral));
87156             case 210 /* TypeAssertionExpression */:
87157                 ts.Debug.type(node);
87158                 return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression));
87159             case 211 /* ParenthesizedExpression */:
87160                 ts.Debug.type(node);
87161                 return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87162             case 212 /* FunctionExpression */:
87163                 ts.Debug.type(node);
87164                 return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), 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));
87165             case 213 /* ArrowFunction */:
87166                 ts.Debug.type(node);
87167                 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.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor));
87168             case 214 /* DeleteExpression */:
87169                 ts.Debug.type(node);
87170                 return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87171             case 215 /* TypeOfExpression */:
87172                 ts.Debug.type(node);
87173                 return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87174             case 216 /* VoidExpression */:
87175                 ts.Debug.type(node);
87176                 return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87177             case 217 /* AwaitExpression */:
87178                 ts.Debug.type(node);
87179                 return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87180             case 218 /* PrefixUnaryExpression */:
87181                 ts.Debug.type(node);
87182                 return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
87183             case 219 /* PostfixUnaryExpression */:
87184                 ts.Debug.type(node);
87185                 return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
87186             case 220 /* BinaryExpression */:
87187                 ts.Debug.type(node);
87188                 return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression));
87189             case 221 /* ConditionalExpression */:
87190                 ts.Debug.type(node);
87191                 return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression));
87192             case 222 /* TemplateExpression */:
87193                 ts.Debug.type(node);
87194                 return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
87195             case 223 /* YieldExpression */:
87196                 ts.Debug.type(node);
87197                 return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression));
87198             case 224 /* SpreadElement */:
87199                 ts.Debug.type(node);
87200                 return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87201             case 225 /* ClassExpression */:
87202                 ts.Debug.type(node);
87203                 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));
87204             case 227 /* ExpressionWithTypeArguments */:
87205                 ts.Debug.type(node);
87206                 return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
87207             case 228 /* AsExpression */:
87208                 ts.Debug.type(node);
87209                 return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode));
87210             case 229 /* NonNullExpression */:
87211                 if (node.flags & 32 /* OptionalChain */) {
87212                     ts.Debug.type(node);
87213                     return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87214                 }
87215                 ts.Debug.type(node);
87216                 return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87217             case 230 /* MetaProperty */:
87218                 ts.Debug.type(node);
87219                 return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
87220             // Misc
87221             case 232 /* TemplateSpan */:
87222                 ts.Debug.type(node);
87223                 return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
87224             // Element
87225             case 234 /* Block */:
87226                 ts.Debug.type(node);
87227                 return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
87228             case 236 /* VariableStatement */:
87229                 ts.Debug.type(node);
87230                 return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList));
87231             case 237 /* ExpressionStatement */:
87232                 ts.Debug.type(node);
87233                 return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87234             case 238 /* IfStatement */:
87235                 ts.Debug.type(node);
87236                 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));
87237             case 239 /* DoStatement */:
87238                 ts.Debug.type(node);
87239                 return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression));
87240             case 240 /* WhileStatement */:
87241                 ts.Debug.type(node);
87242                 return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context));
87243             case 241 /* ForStatement */:
87244                 ts.Debug.type(node);
87245                 return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context));
87246             case 242 /* ForInStatement */:
87247                 ts.Debug.type(node);
87248                 return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context));
87249             case 243 /* ForOfStatement */:
87250                 ts.Debug.type(node);
87251                 return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context));
87252             case 244 /* ContinueStatement */:
87253                 ts.Debug.type(node);
87254                 return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
87255             case 245 /* BreakStatement */:
87256                 ts.Debug.type(node);
87257                 return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
87258             case 246 /* ReturnStatement */:
87259                 ts.Debug.type(node);
87260                 return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87261             case 247 /* WithStatement */:
87262                 ts.Debug.type(node);
87263                 return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
87264             case 248 /* SwitchStatement */:
87265                 ts.Debug.type(node);
87266                 return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock));
87267             case 249 /* LabeledStatement */:
87268                 ts.Debug.type(node);
87269                 return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
87270             case 250 /* ThrowStatement */:
87271                 ts.Debug.type(node);
87272                 return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87273             case 251 /* TryStatement */:
87274                 ts.Debug.type(node);
87275                 return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock));
87276             case 253 /* VariableDeclaration */:
87277                 ts.Debug.type(node);
87278                 return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
87279             case 254 /* VariableDeclarationList */:
87280                 ts.Debug.type(node);
87281                 return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
87282             case 255 /* FunctionDeclaration */:
87283                 ts.Debug.type(node);
87284                 return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), 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));
87285             case 256 /* ClassDeclaration */:
87286                 ts.Debug.type(node);
87287                 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));
87288             case 257 /* InterfaceDeclaration */:
87289                 ts.Debug.type(node);
87290                 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));
87291             case 258 /* TypeAliasDeclaration */:
87292                 ts.Debug.type(node);
87293                 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));
87294             case 259 /* EnumDeclaration */:
87295                 ts.Debug.type(node);
87296                 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));
87297             case 260 /* ModuleDeclaration */:
87298                 ts.Debug.type(node);
87299                 return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody));
87300             case 261 /* ModuleBlock */:
87301                 ts.Debug.type(node);
87302                 return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
87303             case 262 /* CaseBlock */:
87304                 ts.Debug.type(node);
87305                 return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
87306             case 263 /* NamespaceExportDeclaration */:
87307                 ts.Debug.type(node);
87308                 return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
87309             case 264 /* ImportEqualsDeclaration */:
87310                 ts.Debug.type(node);
87311                 return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference));
87312             case 265 /* ImportDeclaration */:
87313                 ts.Debug.type(node);
87314                 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), nodeVisitor(node.assertClause, visitor, ts.isAssertClause));
87315             case 292 /* AssertClause */:
87316                 ts.Debug.type(node);
87317                 return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine);
87318             case 293 /* AssertEntry */:
87319                 ts.Debug.type(node);
87320                 return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isStringLiteral));
87321             case 266 /* ImportClause */:
87322                 ts.Debug.type(node);
87323                 return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings));
87324             case 267 /* NamespaceImport */:
87325                 ts.Debug.type(node);
87326                 return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
87327             case 273 /* NamespaceExport */:
87328                 ts.Debug.type(node);
87329                 return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
87330             case 268 /* NamedImports */:
87331                 ts.Debug.type(node);
87332                 return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
87333             case 269 /* ImportSpecifier */:
87334                 ts.Debug.type(node);
87335                 return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
87336             case 270 /* ExportAssignment */:
87337                 ts.Debug.type(node);
87338                 return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression));
87339             case 271 /* ExportDeclaration */:
87340                 ts.Debug.type(node);
87341                 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), nodeVisitor(node.assertClause, visitor, ts.isAssertClause));
87342             case 272 /* NamedExports */:
87343                 ts.Debug.type(node);
87344                 return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
87345             case 274 /* ExportSpecifier */:
87346                 ts.Debug.type(node);
87347                 return factory.updateExportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
87348             // Module references
87349             case 276 /* ExternalModuleReference */:
87350                 ts.Debug.type(node);
87351                 return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87352             // JSX
87353             case 277 /* JsxElement */:
87354                 ts.Debug.type(node);
87355                 return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement));
87356             case 278 /* JsxSelfClosingElement */:
87357                 ts.Debug.type(node);
87358                 return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
87359             case 279 /* JsxOpeningElement */:
87360                 ts.Debug.type(node);
87361                 return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
87362             case 280 /* JsxClosingElement */:
87363                 ts.Debug.type(node);
87364                 return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression));
87365             case 281 /* JsxFragment */:
87366                 ts.Debug.type(node);
87367                 return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment));
87368             case 284 /* JsxAttribute */:
87369                 ts.Debug.type(node);
87370                 return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
87371             case 285 /* JsxAttributes */:
87372                 ts.Debug.type(node);
87373                 return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
87374             case 286 /* JsxSpreadAttribute */:
87375                 ts.Debug.type(node);
87376                 return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87377             case 287 /* JsxExpression */:
87378                 ts.Debug.type(node);
87379                 return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87380             // Clauses
87381             case 288 /* CaseClause */:
87382                 ts.Debug.type(node);
87383                 return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
87384             case 289 /* DefaultClause */:
87385                 ts.Debug.type(node);
87386                 return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
87387             case 290 /* HeritageClause */:
87388                 ts.Debug.type(node);
87389                 return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
87390             case 291 /* CatchClause */:
87391                 ts.Debug.type(node);
87392                 return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock));
87393             // Property assignments
87394             case 294 /* PropertyAssignment */:
87395                 ts.Debug.type(node);
87396                 return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
87397             case 295 /* ShorthandPropertyAssignment */:
87398                 ts.Debug.type(node);
87399                 return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression));
87400             case 296 /* SpreadAssignment */:
87401                 ts.Debug.type(node);
87402                 return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87403             // Enum
87404             case 297 /* EnumMember */:
87405                 ts.Debug.type(node);
87406                 return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
87407             // Top-level nodes
87408             case 303 /* SourceFile */:
87409                 ts.Debug.type(node);
87410                 return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context));
87411             // Transformation nodes
87412             case 348 /* PartiallyEmittedExpression */:
87413                 ts.Debug.type(node);
87414                 return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
87415             case 349 /* CommaListExpression */:
87416                 ts.Debug.type(node);
87417                 return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
87418             default:
87419                 // No need to visit nodes with no children.
87420                 return node;
87421         }
87422     }
87423     ts.visitEachChild = visitEachChild;
87424     /**
87425      * Extracts the single node from a NodeArray.
87426      *
87427      * @param nodes The NodeArray.
87428      */
87429     function extractSingleNode(nodes) {
87430         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
87431         return ts.singleOrUndefined(nodes);
87432     }
87433 })(ts || (ts = {}));
87434 /* @internal */
87435 var ts;
87436 (function (ts) {
87437     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
87438         var _a = generatorOptions.extendedDiagnostics
87439             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
87440             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
87441         // Current source map file and its index in the sources list
87442         var rawSources = [];
87443         var sources = [];
87444         var sourceToSourceIndexMap = new ts.Map();
87445         var sourcesContent;
87446         var names = [];
87447         var nameToNameIndexMap;
87448         var mappingCharCodes = [];
87449         var mappings = "";
87450         // Last recorded and encoded mappings
87451         var lastGeneratedLine = 0;
87452         var lastGeneratedCharacter = 0;
87453         var lastSourceIndex = 0;
87454         var lastSourceLine = 0;
87455         var lastSourceCharacter = 0;
87456         var lastNameIndex = 0;
87457         var hasLast = false;
87458         var pendingGeneratedLine = 0;
87459         var pendingGeneratedCharacter = 0;
87460         var pendingSourceIndex = 0;
87461         var pendingSourceLine = 0;
87462         var pendingSourceCharacter = 0;
87463         var pendingNameIndex = 0;
87464         var hasPending = false;
87465         var hasPendingSource = false;
87466         var hasPendingName = false;
87467         return {
87468             getSources: function () { return rawSources; },
87469             addSource: addSource,
87470             setSourceContent: setSourceContent,
87471             addName: addName,
87472             addMapping: addMapping,
87473             appendSourceMap: appendSourceMap,
87474             toJSON: toJSON,
87475             toString: function () { return JSON.stringify(toJSON()); }
87476         };
87477         function addSource(fileName) {
87478             enter();
87479             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
87480             /*isAbsolutePathAnUrl*/ true);
87481             var sourceIndex = sourceToSourceIndexMap.get(source);
87482             if (sourceIndex === undefined) {
87483                 sourceIndex = sources.length;
87484                 sources.push(source);
87485                 rawSources.push(fileName);
87486                 sourceToSourceIndexMap.set(source, sourceIndex);
87487             }
87488             exit();
87489             return sourceIndex;
87490         }
87491         /* eslint-disable boolean-trivia, no-null/no-null */
87492         function setSourceContent(sourceIndex, content) {
87493             enter();
87494             if (content !== null) {
87495                 if (!sourcesContent)
87496                     sourcesContent = [];
87497                 while (sourcesContent.length < sourceIndex) {
87498                     sourcesContent.push(null);
87499                 }
87500                 sourcesContent[sourceIndex] = content;
87501             }
87502             exit();
87503         }
87504         /* eslint-enable boolean-trivia, no-null/no-null */
87505         function addName(name) {
87506             enter();
87507             if (!nameToNameIndexMap)
87508                 nameToNameIndexMap = new ts.Map();
87509             var nameIndex = nameToNameIndexMap.get(name);
87510             if (nameIndex === undefined) {
87511                 nameIndex = names.length;
87512                 names.push(name);
87513                 nameToNameIndexMap.set(name, nameIndex);
87514             }
87515             exit();
87516             return nameIndex;
87517         }
87518         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
87519             return !hasPending
87520                 || pendingGeneratedLine !== generatedLine
87521                 || pendingGeneratedCharacter !== generatedCharacter;
87522         }
87523         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
87524             return sourceIndex !== undefined
87525                 && sourceLine !== undefined
87526                 && sourceCharacter !== undefined
87527                 && pendingSourceIndex === sourceIndex
87528                 && (pendingSourceLine > sourceLine
87529                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
87530         }
87531         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
87532             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
87533             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
87534             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
87535             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
87536             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
87537             enter();
87538             // If this location wasn't recorded or the location in source is going backwards, record the mapping
87539             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
87540                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
87541                 commitPendingMapping();
87542                 pendingGeneratedLine = generatedLine;
87543                 pendingGeneratedCharacter = generatedCharacter;
87544                 hasPendingSource = false;
87545                 hasPendingName = false;
87546                 hasPending = true;
87547             }
87548             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
87549                 pendingSourceIndex = sourceIndex;
87550                 pendingSourceLine = sourceLine;
87551                 pendingSourceCharacter = sourceCharacter;
87552                 hasPendingSource = true;
87553                 if (nameIndex !== undefined) {
87554                     pendingNameIndex = nameIndex;
87555                     hasPendingName = true;
87556                 }
87557             }
87558             exit();
87559         }
87560         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
87561             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
87562             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
87563             enter();
87564             // First, decode the old component sourcemap
87565             var sourceIndexToNewSourceIndexMap = [];
87566             var nameIndexToNewNameIndexMap;
87567             var mappingIterator = decodeMappings(map.mappings);
87568             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
87569                 var raw = iterResult.value;
87570                 if (end && (raw.generatedLine > end.line ||
87571                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
87572                     break;
87573                 }
87574                 if (start && (raw.generatedLine < start.line ||
87575                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
87576                     continue;
87577                 }
87578                 // Then reencode all the updated mappings into the overall map
87579                 var newSourceIndex = void 0;
87580                 var newSourceLine = void 0;
87581                 var newSourceCharacter = void 0;
87582                 var newNameIndex = void 0;
87583                 if (raw.sourceIndex !== undefined) {
87584                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
87585                     if (newSourceIndex === undefined) {
87586                         // Apply offsets to each position and fixup source entries
87587                         var rawPath = map.sources[raw.sourceIndex];
87588                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
87589                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
87590                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
87591                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
87592                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
87593                         }
87594                     }
87595                     newSourceLine = raw.sourceLine;
87596                     newSourceCharacter = raw.sourceCharacter;
87597                     if (map.names && raw.nameIndex !== undefined) {
87598                         if (!nameIndexToNewNameIndexMap)
87599                             nameIndexToNewNameIndexMap = [];
87600                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
87601                         if (newNameIndex === undefined) {
87602                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
87603                         }
87604                     }
87605                 }
87606                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
87607                 var newGeneratedLine = rawGeneratedLine + generatedLine;
87608                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
87609                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
87610                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
87611             }
87612             exit();
87613         }
87614         function shouldCommitMapping() {
87615             return !hasLast
87616                 || lastGeneratedLine !== pendingGeneratedLine
87617                 || lastGeneratedCharacter !== pendingGeneratedCharacter
87618                 || lastSourceIndex !== pendingSourceIndex
87619                 || lastSourceLine !== pendingSourceLine
87620                 || lastSourceCharacter !== pendingSourceCharacter
87621                 || lastNameIndex !== pendingNameIndex;
87622         }
87623         function appendMappingCharCode(charCode) {
87624             mappingCharCodes.push(charCode);
87625             // String.fromCharCode accepts its arguments on the stack, so we have to chunk the input,
87626             // otherwise we can get stack overflows for large source maps
87627             if (mappingCharCodes.length >= 1024) {
87628                 flushMappingBuffer();
87629             }
87630         }
87631         function commitPendingMapping() {
87632             if (!hasPending || !shouldCommitMapping()) {
87633                 return;
87634             }
87635             enter();
87636             // Line/Comma delimiters
87637             if (lastGeneratedLine < pendingGeneratedLine) {
87638                 // Emit line delimiters
87639                 do {
87640                     appendMappingCharCode(59 /* semicolon */);
87641                     lastGeneratedLine++;
87642                 } while (lastGeneratedLine < pendingGeneratedLine);
87643                 // Only need to set this once
87644                 lastGeneratedCharacter = 0;
87645             }
87646             else {
87647                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
87648                 // Emit comma to separate the entry
87649                 if (hasLast) {
87650                     appendMappingCharCode(44 /* comma */);
87651                 }
87652             }
87653             // 1. Relative generated character
87654             appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter);
87655             lastGeneratedCharacter = pendingGeneratedCharacter;
87656             if (hasPendingSource) {
87657                 // 2. Relative sourceIndex
87658                 appendBase64VLQ(pendingSourceIndex - lastSourceIndex);
87659                 lastSourceIndex = pendingSourceIndex;
87660                 // 3. Relative source line
87661                 appendBase64VLQ(pendingSourceLine - lastSourceLine);
87662                 lastSourceLine = pendingSourceLine;
87663                 // 4. Relative source character
87664                 appendBase64VLQ(pendingSourceCharacter - lastSourceCharacter);
87665                 lastSourceCharacter = pendingSourceCharacter;
87666                 if (hasPendingName) {
87667                     // 5. Relative nameIndex
87668                     appendBase64VLQ(pendingNameIndex - lastNameIndex);
87669                     lastNameIndex = pendingNameIndex;
87670                 }
87671             }
87672             hasLast = true;
87673             exit();
87674         }
87675         function flushMappingBuffer() {
87676             if (mappingCharCodes.length > 0) {
87677                 mappings += String.fromCharCode.apply(undefined, mappingCharCodes);
87678                 mappingCharCodes.length = 0;
87679             }
87680         }
87681         function toJSON() {
87682             commitPendingMapping();
87683             flushMappingBuffer();
87684             return {
87685                 version: 3,
87686                 file: file,
87687                 sourceRoot: sourceRoot,
87688                 sources: sources,
87689                 names: names,
87690                 mappings: mappings,
87691                 sourcesContent: sourcesContent,
87692             };
87693         }
87694         function appendBase64VLQ(inValue) {
87695             // Add a new least significant bit that has the sign of the value.
87696             // if negative number the least significant bit that gets added to the number has value 1
87697             // else least significant bit value that gets added is 0
87698             // eg. -1 changes to binary : 01 [1] => 3
87699             //     +1 changes to binary : 01 [0] => 2
87700             if (inValue < 0) {
87701                 inValue = ((-inValue) << 1) + 1;
87702             }
87703             else {
87704                 inValue = inValue << 1;
87705             }
87706             // Encode 5 bits at a time starting from least significant bits
87707             do {
87708                 var currentDigit = inValue & 31; // 11111
87709                 inValue = inValue >> 5;
87710                 if (inValue > 0) {
87711                     // There are still more digits to decode, set the msb (6th bit)
87712                     currentDigit = currentDigit | 32;
87713                 }
87714                 appendMappingCharCode(base64FormatEncode(currentDigit));
87715             } while (inValue > 0);
87716         }
87717     }
87718     ts.createSourceMapGenerator = createSourceMapGenerator;
87719     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
87720     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/;
87721     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
87722     function getLineInfo(text, lineStarts) {
87723         return {
87724             getLineCount: function () { return lineStarts.length; },
87725             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
87726         };
87727     }
87728     ts.getLineInfo = getLineInfo;
87729     /**
87730      * Tries to find the sourceMappingURL comment at the end of a file.
87731      */
87732     function tryGetSourceMappingURL(lineInfo) {
87733         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
87734             var line = lineInfo.getLineText(index);
87735             var comment = sourceMapCommentRegExp.exec(line);
87736             if (comment) {
87737                 return ts.trimStringEnd(comment[1]);
87738             }
87739             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
87740             else if (!line.match(whitespaceOrMapCommentRegExp)) {
87741                 break;
87742             }
87743         }
87744     }
87745     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
87746     /* eslint-disable no-null/no-null */
87747     function isStringOrNull(x) {
87748         return typeof x === "string" || x === null;
87749     }
87750     function isRawSourceMap(x) {
87751         return x !== null
87752             && typeof x === "object"
87753             && x.version === 3
87754             && typeof x.file === "string"
87755             && typeof x.mappings === "string"
87756             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
87757             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
87758             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
87759             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
87760     }
87761     ts.isRawSourceMap = isRawSourceMap;
87762     /* eslint-enable no-null/no-null */
87763     function tryParseRawSourceMap(text) {
87764         try {
87765             var parsed = JSON.parse(text);
87766             if (isRawSourceMap(parsed)) {
87767                 return parsed;
87768             }
87769         }
87770         catch (_a) {
87771             // empty
87772         }
87773         return undefined;
87774     }
87775     ts.tryParseRawSourceMap = tryParseRawSourceMap;
87776     function decodeMappings(mappings) {
87777         var done = false;
87778         var pos = 0;
87779         var generatedLine = 0;
87780         var generatedCharacter = 0;
87781         var sourceIndex = 0;
87782         var sourceLine = 0;
87783         var sourceCharacter = 0;
87784         var nameIndex = 0;
87785         var error;
87786         return {
87787             get pos() { return pos; },
87788             get error() { return error; },
87789             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
87790             next: function () {
87791                 while (!done && pos < mappings.length) {
87792                     var ch = mappings.charCodeAt(pos);
87793                     if (ch === 59 /* semicolon */) {
87794                         // new line
87795                         generatedLine++;
87796                         generatedCharacter = 0;
87797                         pos++;
87798                         continue;
87799                     }
87800                     if (ch === 44 /* comma */) {
87801                         // Next entry is on same line - no action needed
87802                         pos++;
87803                         continue;
87804                     }
87805                     var hasSource = false;
87806                     var hasName = false;
87807                     generatedCharacter += base64VLQFormatDecode();
87808                     if (hasReportedError())
87809                         return stopIterating();
87810                     if (generatedCharacter < 0)
87811                         return setErrorAndStopIterating("Invalid generatedCharacter found");
87812                     if (!isSourceMappingSegmentEnd()) {
87813                         hasSource = true;
87814                         sourceIndex += base64VLQFormatDecode();
87815                         if (hasReportedError())
87816                             return stopIterating();
87817                         if (sourceIndex < 0)
87818                             return setErrorAndStopIterating("Invalid sourceIndex found");
87819                         if (isSourceMappingSegmentEnd())
87820                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
87821                         sourceLine += base64VLQFormatDecode();
87822                         if (hasReportedError())
87823                             return stopIterating();
87824                         if (sourceLine < 0)
87825                             return setErrorAndStopIterating("Invalid sourceLine found");
87826                         if (isSourceMappingSegmentEnd())
87827                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
87828                         sourceCharacter += base64VLQFormatDecode();
87829                         if (hasReportedError())
87830                             return stopIterating();
87831                         if (sourceCharacter < 0)
87832                             return setErrorAndStopIterating("Invalid sourceCharacter found");
87833                         if (!isSourceMappingSegmentEnd()) {
87834                             hasName = true;
87835                             nameIndex += base64VLQFormatDecode();
87836                             if (hasReportedError())
87837                                 return stopIterating();
87838                             if (nameIndex < 0)
87839                                 return setErrorAndStopIterating("Invalid nameIndex found");
87840                             if (!isSourceMappingSegmentEnd())
87841                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
87842                         }
87843                     }
87844                     return { value: captureMapping(hasSource, hasName), done: done };
87845                 }
87846                 return stopIterating();
87847             }
87848         };
87849         function captureMapping(hasSource, hasName) {
87850             return {
87851                 generatedLine: generatedLine,
87852                 generatedCharacter: generatedCharacter,
87853                 sourceIndex: hasSource ? sourceIndex : undefined,
87854                 sourceLine: hasSource ? sourceLine : undefined,
87855                 sourceCharacter: hasSource ? sourceCharacter : undefined,
87856                 nameIndex: hasName ? nameIndex : undefined
87857             };
87858         }
87859         function stopIterating() {
87860             done = true;
87861             return { value: undefined, done: true };
87862         }
87863         function setError(message) {
87864             if (error === undefined) {
87865                 error = message;
87866             }
87867         }
87868         function setErrorAndStopIterating(message) {
87869             setError(message);
87870             return stopIterating();
87871         }
87872         function hasReportedError() {
87873             return error !== undefined;
87874         }
87875         function isSourceMappingSegmentEnd() {
87876             return (pos === mappings.length ||
87877                 mappings.charCodeAt(pos) === 44 /* comma */ ||
87878                 mappings.charCodeAt(pos) === 59 /* semicolon */);
87879         }
87880         function base64VLQFormatDecode() {
87881             var moreDigits = true;
87882             var shiftCount = 0;
87883             var value = 0;
87884             for (; moreDigits; pos++) {
87885                 if (pos >= mappings.length)
87886                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
87887                 // 6 digit number
87888                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
87889                 if (currentByte === -1)
87890                     return setError("Invalid character in VLQ"), -1;
87891                 // If msb is set, we still have more bits to continue
87892                 moreDigits = (currentByte & 32) !== 0;
87893                 // least significant 5 bits are the next msbs in the final value.
87894                 value = value | ((currentByte & 31) << shiftCount);
87895                 shiftCount += 5;
87896             }
87897             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
87898             if ((value & 1) === 0) {
87899                 // + number
87900                 value = value >> 1;
87901             }
87902             else {
87903                 // - number
87904                 value = value >> 1;
87905                 value = -value;
87906             }
87907             return value;
87908         }
87909     }
87910     ts.decodeMappings = decodeMappings;
87911     function sameMapping(left, right) {
87912         return left === right
87913             || left.generatedLine === right.generatedLine
87914                 && left.generatedCharacter === right.generatedCharacter
87915                 && left.sourceIndex === right.sourceIndex
87916                 && left.sourceLine === right.sourceLine
87917                 && left.sourceCharacter === right.sourceCharacter
87918                 && left.nameIndex === right.nameIndex;
87919     }
87920     ts.sameMapping = sameMapping;
87921     function isSourceMapping(mapping) {
87922         return mapping.sourceIndex !== undefined
87923             && mapping.sourceLine !== undefined
87924             && mapping.sourceCharacter !== undefined;
87925     }
87926     ts.isSourceMapping = isSourceMapping;
87927     function base64FormatEncode(value) {
87928         return value >= 0 && value < 26 ? 65 /* A */ + value :
87929             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
87930                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
87931                     value === 62 ? 43 /* plus */ :
87932                         value === 63 ? 47 /* slash */ :
87933                             ts.Debug.fail("".concat(value, ": not a base64 value"));
87934     }
87935     function base64FormatDecode(ch) {
87936         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
87937             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
87938                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
87939                     ch === 43 /* plus */ ? 62 :
87940                         ch === 47 /* slash */ ? 63 :
87941                             -1;
87942     }
87943     function isSourceMappedPosition(value) {
87944         return value.sourceIndex !== undefined
87945             && value.sourcePosition !== undefined;
87946     }
87947     function sameMappedPosition(left, right) {
87948         return left.generatedPosition === right.generatedPosition
87949             && left.sourceIndex === right.sourceIndex
87950             && left.sourcePosition === right.sourcePosition;
87951     }
87952     function compareSourcePositions(left, right) {
87953         // Compares sourcePosition without comparing sourceIndex
87954         // since the mappings are grouped by sourceIndex
87955         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
87956         return ts.compareValues(left.sourcePosition, right.sourcePosition);
87957     }
87958     function compareGeneratedPositions(left, right) {
87959         return ts.compareValues(left.generatedPosition, right.generatedPosition);
87960     }
87961     function getSourcePositionOfMapping(value) {
87962         return value.sourcePosition;
87963     }
87964     function getGeneratedPositionOfMapping(value) {
87965         return value.generatedPosition;
87966     }
87967     function createDocumentPositionMapper(host, map, mapPath) {
87968         var mapDirectory = ts.getDirectoryPath(mapPath);
87969         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
87970         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
87971         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
87972         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
87973         var sourceToSourceIndexMap = new ts.Map(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
87974         var decodedMappings;
87975         var generatedMappings;
87976         var sourceMappings;
87977         return {
87978             getSourcePosition: getSourcePosition,
87979             getGeneratedPosition: getGeneratedPosition
87980         };
87981         function processMapping(mapping) {
87982             var generatedPosition = generatedFile !== undefined
87983                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
87984                 : -1;
87985             var source;
87986             var sourcePosition;
87987             if (isSourceMapping(mapping)) {
87988                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
87989                 source = map.sources[mapping.sourceIndex];
87990                 sourcePosition = sourceFile !== undefined
87991                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
87992                     : -1;
87993             }
87994             return {
87995                 generatedPosition: generatedPosition,
87996                 source: source,
87997                 sourceIndex: mapping.sourceIndex,
87998                 sourcePosition: sourcePosition,
87999                 nameIndex: mapping.nameIndex
88000             };
88001         }
88002         function getDecodedMappings() {
88003             if (decodedMappings === undefined) {
88004                 var decoder = decodeMappings(map.mappings);
88005                 var mappings = ts.arrayFrom(decoder, processMapping);
88006                 if (decoder.error !== undefined) {
88007                     if (host.log) {
88008                         host.log("Encountered error while decoding sourcemap: ".concat(decoder.error));
88009                     }
88010                     decodedMappings = ts.emptyArray;
88011                 }
88012                 else {
88013                     decodedMappings = mappings;
88014                 }
88015             }
88016             return decodedMappings;
88017         }
88018         function getSourceMappings(sourceIndex) {
88019             if (sourceMappings === undefined) {
88020                 var lists = [];
88021                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
88022                     var mapping = _a[_i];
88023                     if (!isSourceMappedPosition(mapping))
88024                         continue;
88025                     var list = lists[mapping.sourceIndex];
88026                     if (!list)
88027                         lists[mapping.sourceIndex] = list = [];
88028                     list.push(mapping);
88029                 }
88030                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
88031             }
88032             return sourceMappings[sourceIndex];
88033         }
88034         function getGeneratedMappings() {
88035             if (generatedMappings === undefined) {
88036                 var list = [];
88037                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
88038                     var mapping = _a[_i];
88039                     list.push(mapping);
88040                 }
88041                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
88042             }
88043             return generatedMappings;
88044         }
88045         function getGeneratedPosition(loc) {
88046             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
88047             if (sourceIndex === undefined)
88048                 return loc;
88049             var sourceMappings = getSourceMappings(sourceIndex);
88050             if (!ts.some(sourceMappings))
88051                 return loc;
88052             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
88053             if (targetIndex < 0) {
88054                 // if no exact match, closest is 2's complement of result
88055                 targetIndex = ~targetIndex;
88056             }
88057             var mapping = sourceMappings[targetIndex];
88058             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
88059                 return loc;
88060             }
88061             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
88062         }
88063         function getSourcePosition(loc) {
88064             var generatedMappings = getGeneratedMappings();
88065             if (!ts.some(generatedMappings))
88066                 return loc;
88067             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
88068             if (targetIndex < 0) {
88069                 // if no exact match, closest is 2's complement of result
88070                 targetIndex = ~targetIndex;
88071             }
88072             var mapping = generatedMappings[targetIndex];
88073             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
88074                 return loc;
88075             }
88076             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
88077         }
88078     }
88079     ts.createDocumentPositionMapper = createDocumentPositionMapper;
88080     ts.identitySourceMapConsumer = {
88081         getSourcePosition: ts.identity,
88082         getGeneratedPosition: ts.identity
88083     };
88084 })(ts || (ts = {}));
88085 /* @internal */
88086 var ts;
88087 (function (ts) {
88088     function getOriginalNodeId(node) {
88089         node = ts.getOriginalNode(node);
88090         return node ? ts.getNodeId(node) : 0;
88091     }
88092     ts.getOriginalNodeId = getOriginalNodeId;
88093     function containsDefaultReference(node) {
88094         if (!node)
88095             return false;
88096         if (!ts.isNamedImports(node))
88097             return false;
88098         return ts.some(node.elements, isNamedDefaultReference);
88099     }
88100     function isNamedDefaultReference(e) {
88101         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
88102     }
88103     function chainBundle(context, transformSourceFile) {
88104         return transformSourceFileOrBundle;
88105         function transformSourceFileOrBundle(node) {
88106             return node.kind === 303 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
88107         }
88108         function transformBundle(node) {
88109             return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
88110         }
88111     }
88112     ts.chainBundle = chainBundle;
88113     function getExportNeedsImportStarHelper(node) {
88114         return !!ts.getNamespaceDeclarationNode(node);
88115     }
88116     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
88117     function getImportNeedsImportStarHelper(node) {
88118         if (!!ts.getNamespaceDeclarationNode(node)) {
88119             return true;
88120         }
88121         var bindings = node.importClause && node.importClause.namedBindings;
88122         if (!bindings) {
88123             return false;
88124         }
88125         if (!ts.isNamedImports(bindings))
88126             return false;
88127         var defaultRefCount = 0;
88128         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
88129             var binding = _a[_i];
88130             if (isNamedDefaultReference(binding)) {
88131                 defaultRefCount++;
88132             }
88133         }
88134         // 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
88135         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
88136     }
88137     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
88138     function getImportNeedsImportDefaultHelper(node) {
88139         // 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)
88140         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
88141     }
88142     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
88143     function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
88144         var externalImports = [];
88145         var exportSpecifiers = ts.createMultiMap();
88146         var exportedBindings = [];
88147         var uniqueExports = new ts.Map();
88148         var exportedNames;
88149         var hasExportDefault = false;
88150         var exportEquals;
88151         var hasExportStarsToExportValues = false;
88152         var hasImportStar = false;
88153         var hasImportDefault = false;
88154         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
88155             var node = _a[_i];
88156             switch (node.kind) {
88157                 case 265 /* ImportDeclaration */:
88158                     // import "mod"
88159                     // import x from "mod"
88160                     // import * as x from "mod"
88161                     // import { x, y } from "mod"
88162                     externalImports.push(node);
88163                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
88164                         hasImportStar = true;
88165                     }
88166                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
88167                         hasImportDefault = true;
88168                     }
88169                     break;
88170                 case 264 /* ImportEqualsDeclaration */:
88171                     if (node.moduleReference.kind === 276 /* ExternalModuleReference */) {
88172                         // import x = require("mod")
88173                         externalImports.push(node);
88174                     }
88175                     break;
88176                 case 271 /* ExportDeclaration */:
88177                     if (node.moduleSpecifier) {
88178                         if (!node.exportClause) {
88179                             // export * from "mod"
88180                             externalImports.push(node);
88181                             hasExportStarsToExportValues = true;
88182                         }
88183                         else {
88184                             // export * as ns from "mod"
88185                             // export { x, y } from "mod"
88186                             externalImports.push(node);
88187                             if (ts.isNamedExports(node.exportClause)) {
88188                                 addExportedNamesForExportDeclaration(node);
88189                             }
88190                             else {
88191                                 var name = node.exportClause.name;
88192                                 if (!uniqueExports.get(ts.idText(name))) {
88193                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
88194                                     uniqueExports.set(ts.idText(name), true);
88195                                     exportedNames = ts.append(exportedNames, name);
88196                                 }
88197                                 // we use the same helpers for `export * as ns` as we do for `import * as ns`
88198                                 hasImportStar = true;
88199                             }
88200                         }
88201                     }
88202                     else {
88203                         // export { x, y }
88204                         addExportedNamesForExportDeclaration(node);
88205                     }
88206                     break;
88207                 case 270 /* ExportAssignment */:
88208                     if (node.isExportEquals && !exportEquals) {
88209                         // export = x
88210                         exportEquals = node;
88211                     }
88212                     break;
88213                 case 236 /* VariableStatement */:
88214                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
88215                         for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) {
88216                             var decl = _c[_b];
88217                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
88218                         }
88219                     }
88220                     break;
88221                 case 255 /* FunctionDeclaration */:
88222                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
88223                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
88224                             // export default function() { }
88225                             if (!hasExportDefault) {
88226                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
88227                                 hasExportDefault = true;
88228                             }
88229                         }
88230                         else {
88231                             // export function x() { }
88232                             var name = node.name;
88233                             if (!uniqueExports.get(ts.idText(name))) {
88234                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
88235                                 uniqueExports.set(ts.idText(name), true);
88236                                 exportedNames = ts.append(exportedNames, name);
88237                             }
88238                         }
88239                     }
88240                     break;
88241                 case 256 /* ClassDeclaration */:
88242                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
88243                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
88244                             // export default class { }
88245                             if (!hasExportDefault) {
88246                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
88247                                 hasExportDefault = true;
88248                             }
88249                         }
88250                         else {
88251                             // export class x { }
88252                             var name = node.name;
88253                             if (name && !uniqueExports.get(ts.idText(name))) {
88254                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
88255                                 uniqueExports.set(ts.idText(name), true);
88256                                 exportedNames = ts.append(exportedNames, name);
88257                             }
88258                         }
88259                     }
88260                     break;
88261             }
88262         }
88263         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
88264         if (externalHelpersImportDeclaration) {
88265             externalImports.unshift(externalHelpersImportDeclaration);
88266         }
88267         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
88268         function addExportedNamesForExportDeclaration(node) {
88269             for (var _i = 0, _a = ts.cast(node.exportClause, ts.isNamedExports).elements; _i < _a.length; _i++) {
88270                 var specifier = _a[_i];
88271                 if (!uniqueExports.get(ts.idText(specifier.name))) {
88272                     var name = specifier.propertyName || specifier.name;
88273                     if (!node.moduleSpecifier) {
88274                         exportSpecifiers.add(ts.idText(name), specifier);
88275                     }
88276                     var decl = resolver.getReferencedImportDeclaration(name)
88277                         || resolver.getReferencedValueDeclaration(name);
88278                     if (decl) {
88279                         multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
88280                     }
88281                     uniqueExports.set(ts.idText(specifier.name), true);
88282                     exportedNames = ts.append(exportedNames, specifier.name);
88283                 }
88284             }
88285         }
88286     }
88287     ts.collectExternalModuleInfo = collectExternalModuleInfo;
88288     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
88289         if (ts.isBindingPattern(decl.name)) {
88290             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
88291                 var element = _a[_i];
88292                 if (!ts.isOmittedExpression(element)) {
88293                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
88294                 }
88295             }
88296         }
88297         else if (!ts.isGeneratedIdentifier(decl.name)) {
88298             var text = ts.idText(decl.name);
88299             if (!uniqueExports.get(text)) {
88300                 uniqueExports.set(text, true);
88301                 exportedNames = ts.append(exportedNames, decl.name);
88302             }
88303         }
88304         return exportedNames;
88305     }
88306     /** Use a sparse array as a multi-map. */
88307     function multiMapSparseArrayAdd(map, key, value) {
88308         var values = map[key];
88309         if (values) {
88310             values.push(value);
88311         }
88312         else {
88313             map[key] = values = [value];
88314         }
88315         return values;
88316     }
88317     /**
88318      * Used in the module transformer to check if an expression is reasonably without sideeffect,
88319      *  and thus better to copy into multiple places rather than to cache in a temporary variable
88320      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
88321      */
88322     function isSimpleCopiableExpression(expression) {
88323         return ts.isStringLiteralLike(expression) ||
88324             expression.kind === 8 /* NumericLiteral */ ||
88325             ts.isKeyword(expression.kind) ||
88326             ts.isIdentifier(expression);
88327     }
88328     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
88329     /**
88330      * A simple inlinable expression is an expression which can be copied into multiple locations
88331      * without risk of repeating any sideeffects and whose value could not possibly change between
88332      * any such locations
88333      */
88334     function isSimpleInlineableExpression(expression) {
88335         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression);
88336     }
88337     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
88338     function isCompoundAssignment(kind) {
88339         return kind >= 64 /* FirstCompoundAssignment */
88340             && kind <= 78 /* LastCompoundAssignment */;
88341     }
88342     ts.isCompoundAssignment = isCompoundAssignment;
88343     function getNonAssignmentOperatorForCompoundAssignment(kind) {
88344         switch (kind) {
88345             case 64 /* PlusEqualsToken */: return 39 /* PlusToken */;
88346             case 65 /* MinusEqualsToken */: return 40 /* MinusToken */;
88347             case 66 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
88348             case 67 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
88349             case 68 /* SlashEqualsToken */: return 43 /* SlashToken */;
88350             case 69 /* PercentEqualsToken */: return 44 /* PercentToken */;
88351             case 70 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
88352             case 71 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
88353             case 72 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
88354             case 73 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
88355             case 74 /* BarEqualsToken */: return 51 /* BarToken */;
88356             case 78 /* CaretEqualsToken */: return 52 /* CaretToken */;
88357             case 75 /* BarBarEqualsToken */: return 56 /* BarBarToken */;
88358             case 76 /* AmpersandAmpersandEqualsToken */: return 55 /* AmpersandAmpersandToken */;
88359             case 77 /* QuestionQuestionEqualsToken */: return 60 /* QuestionQuestionToken */;
88360         }
88361     }
88362     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
88363     /**
88364      * Adds super call and preceding prologue directives into the list of statements.
88365      *
88366      * @param ctor The constructor node.
88367      * @param result The list of statements.
88368      * @param visitor The visitor to apply to each node added to the result array.
88369      * @returns index of the statement that follows super call
88370      */
88371     function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) {
88372         if (ctor.body) {
88373             var statements = ctor.body.statements;
88374             // add prologue directives to the list (if any)
88375             var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
88376             if (index === statements.length) {
88377                 // list contains nothing but prologue directives (or empty) - exit
88378                 return index;
88379             }
88380             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
88381             if (superIndex > -1) {
88382                 for (var i = index; i <= superIndex; i++) {
88383                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
88384                 }
88385                 return superIndex + 1;
88386             }
88387             return index;
88388         }
88389         return 0;
88390     }
88391     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
88392     function getProperties(node, requireInitializer, isStatic) {
88393         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
88394     }
88395     ts.getProperties = getProperties;
88396     function isStaticPropertyDeclarationOrClassStaticBlockDeclaration(element) {
88397         return isStaticPropertyDeclaration(element) || ts.isClassStaticBlockDeclaration(element);
88398     }
88399     function getStaticPropertiesAndClassStaticBlock(node) {
88400         return ts.filter(node.members, isStaticPropertyDeclarationOrClassStaticBlockDeclaration);
88401     }
88402     ts.getStaticPropertiesAndClassStaticBlock = getStaticPropertiesAndClassStaticBlock;
88403     /**
88404      * Is a class element either a static or an instance property declaration with an initializer?
88405      *
88406      * @param member The class element node.
88407      * @param isStatic A value indicating whether the member should be a static or instance member.
88408      */
88409     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
88410         return ts.isPropertyDeclaration(member)
88411             && (!!member.initializer || !requireInitializer)
88412             && ts.hasStaticModifier(member) === isStatic;
88413     }
88414     function isStaticPropertyDeclaration(member) {
88415         return ts.isPropertyDeclaration(member) && ts.hasStaticModifier(member);
88416     }
88417     /**
88418      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
88419      *
88420      * @param member The class element node.
88421      * @param isStatic A value indicating whether the member should be a static or instance member.
88422      */
88423     function isInitializedProperty(member) {
88424         return member.kind === 166 /* PropertyDeclaration */
88425             && member.initializer !== undefined;
88426     }
88427     ts.isInitializedProperty = isInitializedProperty;
88428     /**
88429      * Gets a value indicating whether a class element is a private instance method or accessor.
88430      *
88431      * @param member The class element node.
88432      */
88433     function isNonStaticMethodOrAccessorWithPrivateName(member) {
88434         return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name);
88435     }
88436     ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName;
88437 })(ts || (ts = {}));
88438 /*@internal*/
88439 var ts;
88440 (function (ts) {
88441     var FlattenLevel;
88442     (function (FlattenLevel) {
88443         FlattenLevel[FlattenLevel["All"] = 0] = "All";
88444         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
88445     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
88446     /**
88447      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
88448      *
88449      * @param node The node to flatten.
88450      * @param visitor An optional visitor used to visit initializers.
88451      * @param context The transformation context.
88452      * @param level Indicates the extent to which flattening should occur.
88453      * @param needsValue An optional value indicating whether the value from the right-hand-side of
88454      * the destructuring assignment is needed as part of a larger expression.
88455      * @param createAssignmentCallback An optional callback used to create the assignment expression.
88456      */
88457     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
88458         var location = node;
88459         var value;
88460         if (ts.isDestructuringAssignment(node)) {
88461             value = node.right;
88462             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
88463                 if (ts.isDestructuringAssignment(value)) {
88464                     location = node = value;
88465                     value = node.right;
88466                 }
88467                 else {
88468                     return ts.visitNode(value, visitor, ts.isExpression);
88469                 }
88470             }
88471         }
88472         var expressions;
88473         var flattenContext = {
88474             context: context,
88475             level: level,
88476             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
88477             hoistTempVariables: true,
88478             emitExpression: emitExpression,
88479             emitBindingOrAssignment: emitBindingOrAssignment,
88480             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayAssignmentPattern(context.factory, elements); },
88481             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectAssignmentPattern(context.factory, elements); },
88482             createArrayBindingOrAssignmentElement: makeAssignmentElement,
88483             visitor: visitor
88484         };
88485         if (value) {
88486             value = ts.visitNode(value, visitor, ts.isExpression);
88487             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
88488                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
88489                 // If the right-hand value of the assignment is also an assignment target then
88490                 // we need to cache the right-hand value.
88491                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
88492             }
88493             else if (needsValue) {
88494                 // If the right-hand value of the destructuring assignment needs to be preserved (as
88495                 // is the case when the destructuring assignment is part of a larger expression),
88496                 // then we need to cache the right-hand value.
88497                 //
88498                 // The source map location for the assignment should point to the entire binary
88499                 // expression.
88500                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
88501             }
88502             else if (ts.nodeIsSynthesized(node)) {
88503                 // Generally, the source map location for a destructuring assignment is the root
88504                 // expression.
88505                 //
88506                 // However, if the root expression is synthesized (as in the case
88507                 // of the initializer when transforming a ForOfStatement), then the source map
88508                 // location should point to the right-hand value of the expression.
88509                 location = value;
88510             }
88511         }
88512         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
88513         if (value && needsValue) {
88514             if (!ts.some(expressions)) {
88515                 return value;
88516             }
88517             expressions.push(value);
88518         }
88519         return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
88520         function emitExpression(expression) {
88521             expressions = ts.append(expressions, expression);
88522         }
88523         function emitBindingOrAssignment(target, value, location, original) {
88524             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
88525             var expression = createAssignmentCallback
88526                 ? createAssignmentCallback(target, value, location)
88527                 : ts.setTextRange(context.factory.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
88528             expression.original = original;
88529             emitExpression(expression);
88530         }
88531     }
88532     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
88533     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
88534         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
88535         if (ts.isBindingOrAssignmentPattern(target)) {
88536             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
88537         }
88538         else if (ts.isIdentifier(target)) {
88539             return target.escapedText === escapedName;
88540         }
88541         return false;
88542     }
88543     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
88544         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
88545         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
88546             var element = elements_3[_i];
88547             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
88548                 return true;
88549             }
88550         }
88551         return false;
88552     }
88553     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
88554         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
88555         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
88556             return true;
88557         }
88558         var target = ts.getTargetOfBindingOrAssignmentElement(element);
88559         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
88560     }
88561     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
88562         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
88563     }
88564     /**
88565      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
88566      *
88567      * @param node The node to flatten.
88568      * @param visitor An optional visitor used to visit initializers.
88569      * @param context The transformation context.
88570      * @param boundValue The value bound to the declaration.
88571      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
88572      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
88573      * @param level Indicates the extent to which flattening should occur.
88574      */
88575     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
88576         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
88577         var pendingExpressions;
88578         var pendingDeclarations = [];
88579         var declarations = [];
88580         var flattenContext = {
88581             context: context,
88582             level: level,
88583             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
88584             hoistTempVariables: hoistTempVariables,
88585             emitExpression: emitExpression,
88586             emitBindingOrAssignment: emitBindingOrAssignment,
88587             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayBindingPattern(context.factory, elements); },
88588             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectBindingPattern(context.factory, elements); },
88589             createArrayBindingOrAssignmentElement: function (name) { return makeBindingElement(context.factory, name); },
88590             visitor: visitor
88591         };
88592         if (ts.isVariableDeclaration(node)) {
88593             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
88594             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
88595                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
88596                 // If the right-hand value of the assignment is also an assignment target then
88597                 // we need to cache the right-hand value.
88598                 initializer = ensureIdentifier(flattenContext, ts.visitNode(initializer, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, initializer);
88599                 node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
88600             }
88601         }
88602         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
88603         if (pendingExpressions) {
88604             var temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined);
88605             if (hoistTempVariables) {
88606                 var value = context.factory.inlineExpressions(pendingExpressions);
88607                 pendingExpressions = undefined;
88608                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
88609             }
88610             else {
88611                 context.hoistVariableDeclaration(temp);
88612                 var pendingDeclaration = ts.last(pendingDeclarations);
88613                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value));
88614                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
88615                 pendingDeclaration.value = temp;
88616             }
88617         }
88618         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
88619             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
88620             var variable = context.factory.createVariableDeclaration(name, 
88621             /*exclamationToken*/ undefined, 
88622             /*type*/ undefined, pendingExpressions_1 ? context.factory.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
88623             variable.original = original;
88624             ts.setTextRange(variable, location);
88625             declarations.push(variable);
88626         }
88627         return declarations;
88628         function emitExpression(value) {
88629             pendingExpressions = ts.append(pendingExpressions, value);
88630         }
88631         function emitBindingOrAssignment(target, value, location, original) {
88632             ts.Debug.assertNode(target, ts.isBindingName);
88633             if (pendingExpressions) {
88634                 value = context.factory.inlineExpressions(ts.append(pendingExpressions, value));
88635                 pendingExpressions = undefined;
88636             }
88637             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
88638         }
88639     }
88640     ts.flattenDestructuringBinding = flattenDestructuringBinding;
88641     /**
88642      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
88643      *
88644      * @param flattenContext Options used to control flattening.
88645      * @param element The element to flatten.
88646      * @param value The current RHS value to assign to the element.
88647      * @param location The location to use for source maps and comments.
88648      * @param skipInitializer An optional value indicating whether to include the initializer
88649      * for the element.
88650      */
88651     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
88652         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
88653         if (!skipInitializer) {
88654             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
88655             if (initializer) {
88656                 // Combine value and initializer
88657                 if (value) {
88658                     value = createDefaultValueCheck(flattenContext, value, initializer, location);
88659                     // If 'value' is not a simple expression, it could contain side-effecting code that should evaluate before an object or array binding pattern.
88660                     if (!ts.isSimpleInlineableExpression(initializer) && ts.isBindingOrAssignmentPattern(bindingTarget)) {
88661                         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
88662                     }
88663                 }
88664                 else {
88665                     value = initializer;
88666                 }
88667             }
88668             else if (!value) {
88669                 // Use 'void 0' in absence of value and initializer
88670                 value = flattenContext.context.factory.createVoidZero();
88671             }
88672         }
88673         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
88674             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
88675         }
88676         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
88677             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
88678         }
88679         else {
88680             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
88681         }
88682     }
88683     /**
88684      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
88685      *
88686      * @param flattenContext Options used to control flattening.
88687      * @param parent The parent element of the pattern.
88688      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
88689      * @param value The current RHS value to assign to the element.
88690      * @param location The location to use for source maps and comments.
88691      */
88692     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
88693         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
88694         var numElements = elements.length;
88695         if (numElements !== 1) {
88696             // For anything other than a single-element destructuring we need to generate a temporary
88697             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
88698             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
88699             // so in that case, we'll intentionally create that temporary.
88700             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
88701             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
88702         }
88703         var bindingElements;
88704         var computedTempVariables;
88705         for (var i = 0; i < numElements; i++) {
88706             var element = elements[i];
88707             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
88708                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
88709                 if (flattenContext.level >= 1 /* ObjectRest */
88710                     && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */))
88711                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */))
88712                     && !ts.isComputedPropertyName(propertyName)) {
88713                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
88714                 }
88715                 else {
88716                     if (bindingElements) {
88717                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
88718                         bindingElements = undefined;
88719                     }
88720                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
88721                     if (ts.isComputedPropertyName(propertyName)) {
88722                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
88723                     }
88724                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
88725                 }
88726             }
88727             else if (i === numElements - 1) {
88728                 if (bindingElements) {
88729                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
88730                     bindingElements = undefined;
88731                 }
88732                 var rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
88733                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
88734             }
88735         }
88736         if (bindingElements) {
88737             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
88738         }
88739     }
88740     /**
88741      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
88742      *
88743      * @param flattenContext Options used to control flattening.
88744      * @param parent The parent element of the pattern.
88745      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
88746      * @param value The current RHS value to assign to the element.
88747      * @param location The location to use for source maps and comments.
88748      */
88749     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
88750         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
88751         var numElements = elements.length;
88752         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
88753             // Read the elements of the iterable into an array
88754             value = ensureIdentifier(flattenContext, ts.setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
88755                 ? undefined
88756                 : numElements), location), 
88757             /*reuseIdentifierExpressions*/ false, location);
88758         }
88759         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
88760             || ts.every(elements, ts.isOmittedExpression)) {
88761             // For anything other than a single-element destructuring we need to generate a temporary
88762             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
88763             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
88764             // so in that case, we'll intentionally create that temporary.
88765             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
88766             // then we will create temporary variable.
88767             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
88768             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
88769         }
88770         var bindingElements;
88771         var restContainingElements;
88772         for (var i = 0; i < numElements; i++) {
88773             var element = elements[i];
88774             if (flattenContext.level >= 1 /* ObjectRest */) {
88775                 // If an array pattern contains an ObjectRest, we must cache the result so that we
88776                 // can perform the ObjectRest destructuring in a different declaration
88777                 if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) {
88778                     flattenContext.hasTransformedPriorElement = true;
88779                     var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
88780                     if (flattenContext.hoistTempVariables) {
88781                         flattenContext.context.hoistVariableDeclaration(temp);
88782                     }
88783                     restContainingElements = ts.append(restContainingElements, [temp, element]);
88784                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
88785                 }
88786                 else {
88787                     bindingElements = ts.append(bindingElements, element);
88788                 }
88789             }
88790             else if (ts.isOmittedExpression(element)) {
88791                 continue;
88792             }
88793             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
88794                 var rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
88795                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
88796             }
88797             else if (i === numElements - 1) {
88798                 var rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
88799                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
88800             }
88801         }
88802         if (bindingElements) {
88803             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
88804         }
88805         if (restContainingElements) {
88806             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
88807                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
88808                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
88809             }
88810         }
88811     }
88812     function isSimpleBindingOrAssignmentElement(element) {
88813         var target = ts.getTargetOfBindingOrAssignmentElement(element);
88814         if (!target || ts.isOmittedExpression(target))
88815             return true;
88816         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
88817         if (propertyName && !ts.isPropertyNameLiteral(propertyName))
88818             return false;
88819         var initializer = ts.getInitializerOfBindingOrAssignmentElement(element);
88820         if (initializer && !ts.isSimpleInlineableExpression(initializer))
88821             return false;
88822         if (ts.isBindingOrAssignmentPattern(target))
88823             return ts.every(ts.getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement);
88824         return ts.isIdentifier(target);
88825     }
88826     /**
88827      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
88828      *
88829      * @param flattenContext Options used to control flattening.
88830      * @param value The RHS value to test.
88831      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
88832      * @param location The location to use for source maps and comments.
88833      */
88834     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
88835         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
88836         return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value);
88837     }
88838     /**
88839      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
88840      * right-hand side of a transformed destructuring assignment.
88841      *
88842      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
88843      *
88844      * @param flattenContext Options used to control flattening.
88845      * @param value The RHS value that is the source of the property.
88846      * @param propertyName The destructuring property name.
88847      */
88848     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
88849         if (ts.isComputedPropertyName(propertyName)) {
88850             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
88851             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
88852         }
88853         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
88854             var argumentExpression = ts.factory.cloneNode(propertyName);
88855             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
88856         }
88857         else {
88858             var name = flattenContext.context.factory.createIdentifier(ts.idText(propertyName));
88859             return flattenContext.context.factory.createPropertyAccessExpression(value, name);
88860         }
88861     }
88862     /**
88863      * Ensures that there exists a declared identifier whose value holds the given expression.
88864      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
88865      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
88866      *
88867      * @param flattenContext Options used to control flattening.
88868      * @param value the expression whose value needs to be bound.
88869      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
88870      * false if it is necessary to always emit an identifier.
88871      * @param location The location to use for source maps and comments.
88872      */
88873     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
88874         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
88875             return value;
88876         }
88877         else {
88878             var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
88879             if (flattenContext.hoistTempVariables) {
88880                 flattenContext.context.hoistVariableDeclaration(temp);
88881                 flattenContext.emitExpression(ts.setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
88882             }
88883             else {
88884                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
88885             }
88886             return temp;
88887         }
88888     }
88889     function makeArrayBindingPattern(factory, elements) {
88890         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
88891         return factory.createArrayBindingPattern(elements);
88892     }
88893     function makeArrayAssignmentPattern(factory, elements) {
88894         return factory.createArrayLiteralExpression(ts.map(elements, factory.converters.convertToArrayAssignmentElement));
88895     }
88896     function makeObjectBindingPattern(factory, elements) {
88897         ts.Debug.assertEachNode(elements, ts.isBindingElement);
88898         return factory.createObjectBindingPattern(elements);
88899     }
88900     function makeObjectAssignmentPattern(factory, elements) {
88901         return factory.createObjectLiteralExpression(ts.map(elements, factory.converters.convertToObjectAssignmentElement));
88902     }
88903     function makeBindingElement(factory, name) {
88904         return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
88905     }
88906     function makeAssignmentElement(name) {
88907         return name;
88908     }
88909 })(ts || (ts = {}));
88910 /*@internal*/
88911 var ts;
88912 (function (ts) {
88913     var ProcessLevel;
88914     (function (ProcessLevel) {
88915         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
88916         ProcessLevel[ProcessLevel["All"] = 1] = "All";
88917     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
88918     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
88919         // Visit the tag expression
88920         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
88921         // Build up the template arguments and the raw and cooked strings for the template.
88922         // We start out with 'undefined' for the first argument and revisit later
88923         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
88924         var templateArguments = [undefined];
88925         var cookedStrings = [];
88926         var rawStrings = [];
88927         var template = node.template;
88928         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) {
88929             return ts.visitEachChild(node, visitor, context);
88930         }
88931         if (ts.isNoSubstitutionTemplateLiteral(template)) {
88932             cookedStrings.push(createTemplateCooked(template));
88933             rawStrings.push(getRawLiteral(template, currentSourceFile));
88934         }
88935         else {
88936             cookedStrings.push(createTemplateCooked(template.head));
88937             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
88938             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
88939                 var templateSpan = _a[_i];
88940                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
88941                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
88942                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
88943             }
88944         }
88945         var helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(ts.factory.createArrayLiteralExpression(cookedStrings), ts.factory.createArrayLiteralExpression(rawStrings));
88946         // Create a variable to cache the template object if we're in a module.
88947         // Do not do this in the global scope, as any variable we currently generate could conflict with
88948         // variables from outside of the current compilation. In the future, we can revisit this behavior.
88949         if (ts.isExternalModule(currentSourceFile)) {
88950             var tempVar = ts.factory.createUniqueName("templateObject");
88951             recordTaggedTemplateString(tempVar);
88952             templateArguments[0] = ts.factory.createLogicalOr(tempVar, ts.factory.createAssignment(tempVar, helperCall));
88953         }
88954         else {
88955             templateArguments[0] = helperCall;
88956         }
88957         return ts.factory.createCallExpression(tag, /*typeArguments*/ undefined, templateArguments);
88958     }
88959     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
88960     function createTemplateCooked(template) {
88961         return template.templateFlags ? ts.factory.createVoidZero() : ts.factory.createStringLiteral(template.text);
88962     }
88963     /**
88964      * Creates an ES5 compatible literal from an ES6 template literal.
88965      *
88966      * @param node The ES6 template literal.
88967      */
88968     function getRawLiteral(node, currentSourceFile) {
88969         // Find original source text, since we need to emit the raw strings of the tagged template.
88970         // The raw strings contain the (escaped) strings of what the user wrote.
88971         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
88972         var text = node.rawText;
88973         if (text === undefined) {
88974             ts.Debug.assertIsDefined(currentSourceFile, "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform.");
88975             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
88976             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
88977             // thus we need to remove those characters.
88978             // First template piece starts with "`", others with "}"
88979             // Last template piece ends with "`", others with "${"
88980             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
88981             text = text.substring(1, text.length - (isLast ? 1 : 2));
88982         }
88983         // Newline normalization:
88984         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
88985         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
88986         text = text.replace(/\r\n?/g, "\n");
88987         return ts.setTextRange(ts.factory.createStringLiteral(text), node);
88988     }
88989 })(ts || (ts = {}));
88990 /*@internal*/
88991 var ts;
88992 (function (ts) {
88993     /**
88994      * Indicates whether to emit type metadata in the new format.
88995      */
88996     var USE_NEW_TYPE_METADATA_FORMAT = false;
88997     var TypeScriptSubstitutionFlags;
88998     (function (TypeScriptSubstitutionFlags) {
88999         /** Enables substitutions for decorated classes. */
89000         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
89001         /** Enables substitutions for namespace exports. */
89002         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
89003         /* Enables substitutions for unqualified enum members */
89004         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
89005     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
89006     var ClassFacts;
89007     (function (ClassFacts) {
89008         ClassFacts[ClassFacts["None"] = 0] = "None";
89009         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
89010         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
89011         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
89012         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
89013         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
89014         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
89015         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
89016         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
89017         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
89018         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
89019         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
89020         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
89021     })(ClassFacts || (ClassFacts = {}));
89022     function transformTypeScript(context) {
89023         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
89024         var resolver = context.getEmitResolver();
89025         var compilerOptions = context.getCompilerOptions();
89026         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
89027         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
89028         var moduleKind = ts.getEmitModuleKind(compilerOptions);
89029         // Save the previous transformation hooks.
89030         var previousOnEmitNode = context.onEmitNode;
89031         var previousOnSubstituteNode = context.onSubstituteNode;
89032         // Set new transformation hooks.
89033         context.onEmitNode = onEmitNode;
89034         context.onSubstituteNode = onSubstituteNode;
89035         // Enable substitution for property/element access to emit const enum values.
89036         context.enableSubstitution(205 /* PropertyAccessExpression */);
89037         context.enableSubstitution(206 /* ElementAccessExpression */);
89038         // These variables contain state that changes as we descend into the tree.
89039         var currentSourceFile;
89040         var currentNamespace;
89041         var currentNamespaceContainerName;
89042         var currentLexicalScope;
89043         var currentNameScope;
89044         var currentScopeFirstDeclarationsOfName;
89045         var currentClassHasParameterProperties;
89046         /**
89047          * Keeps track of whether expression substitution has been enabled for specific edge cases.
89048          * They are persisted between each SourceFile transformation and should not be reset.
89049          */
89050         var enabledSubstitutions;
89051         /**
89052          * A map that keeps track of aliases created for classes with decorators to avoid issues
89053          * with the double-binding behavior of classes.
89054          */
89055         var classAliases;
89056         /**
89057          * Keeps track of whether we are within any containing namespaces when performing
89058          * just-in-time substitution while printing an expression identifier.
89059          */
89060         var applicableSubstitutions;
89061         return transformSourceFileOrBundle;
89062         function transformSourceFileOrBundle(node) {
89063             if (node.kind === 304 /* Bundle */) {
89064                 return transformBundle(node);
89065             }
89066             return transformSourceFile(node);
89067         }
89068         function transformBundle(node) {
89069             return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
89070                 if (prepend.kind === 306 /* InputFiles */) {
89071                     return ts.createUnparsedSourceFile(prepend, "js");
89072                 }
89073                 return prepend;
89074             }));
89075         }
89076         /**
89077          * Transform TypeScript-specific syntax in a SourceFile.
89078          *
89079          * @param node A SourceFile node.
89080          */
89081         function transformSourceFile(node) {
89082             if (node.isDeclarationFile) {
89083                 return node;
89084             }
89085             currentSourceFile = node;
89086             var visited = saveStateAndInvoke(node, visitSourceFile);
89087             ts.addEmitHelpers(visited, context.readEmitHelpers());
89088             currentSourceFile = undefined;
89089             return visited;
89090         }
89091         /**
89092          * Visits a node, saving and restoring state variables on the stack.
89093          *
89094          * @param node The node to visit.
89095          */
89096         function saveStateAndInvoke(node, f) {
89097             // Save state
89098             var savedCurrentScope = currentLexicalScope;
89099             var savedCurrentNameScope = currentNameScope;
89100             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
89101             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
89102             // Handle state changes before visiting a node.
89103             onBeforeVisitNode(node);
89104             var visited = f(node);
89105             // Restore state
89106             if (currentLexicalScope !== savedCurrentScope) {
89107                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
89108             }
89109             currentLexicalScope = savedCurrentScope;
89110             currentNameScope = savedCurrentNameScope;
89111             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
89112             return visited;
89113         }
89114         /**
89115          * Performs actions that should always occur immediately before visiting a node.
89116          *
89117          * @param node The node to visit.
89118          */
89119         function onBeforeVisitNode(node) {
89120             switch (node.kind) {
89121                 case 303 /* SourceFile */:
89122                 case 262 /* CaseBlock */:
89123                 case 261 /* ModuleBlock */:
89124                 case 234 /* Block */:
89125                     currentLexicalScope = node;
89126                     currentNameScope = undefined;
89127                     currentScopeFirstDeclarationsOfName = undefined;
89128                     break;
89129                 case 256 /* ClassDeclaration */:
89130                 case 255 /* FunctionDeclaration */:
89131                     if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
89132                         break;
89133                     }
89134                     // Record these declarations provided that they have a name.
89135                     if (node.name) {
89136                         recordEmittedDeclarationInScope(node);
89137                     }
89138                     else {
89139                         // These nodes should always have names unless they are default-exports;
89140                         // however, class declaration parsing allows for undefined names, so syntactically invalid
89141                         // programs may also have an undefined name.
89142                         ts.Debug.assert(node.kind === 256 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */));
89143                     }
89144                     if (ts.isClassDeclaration(node)) {
89145                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
89146                         currentNameScope = node;
89147                     }
89148                     break;
89149             }
89150         }
89151         /**
89152          * General-purpose node visitor.
89153          *
89154          * @param node The node to visit.
89155          */
89156         function visitor(node) {
89157             return saveStateAndInvoke(node, visitorWorker);
89158         }
89159         /**
89160          * Visits and possibly transforms any node.
89161          *
89162          * @param node The node to visit.
89163          */
89164         function visitorWorker(node) {
89165             if (node.transformFlags & 1 /* ContainsTypeScript */) {
89166                 return visitTypeScript(node);
89167             }
89168             return node;
89169         }
89170         /**
89171          * Specialized visitor that visits the immediate children of a SourceFile.
89172          *
89173          * @param node The node to visit.
89174          */
89175         function sourceElementVisitor(node) {
89176             return saveStateAndInvoke(node, sourceElementVisitorWorker);
89177         }
89178         /**
89179          * Specialized visitor that visits the immediate children of a SourceFile.
89180          *
89181          * @param node The node to visit.
89182          */
89183         function sourceElementVisitorWorker(node) {
89184             switch (node.kind) {
89185                 case 265 /* ImportDeclaration */:
89186                 case 264 /* ImportEqualsDeclaration */:
89187                 case 270 /* ExportAssignment */:
89188                 case 271 /* ExportDeclaration */:
89189                     return visitElidableStatement(node);
89190                 default:
89191                     return visitorWorker(node);
89192             }
89193         }
89194         function visitElidableStatement(node) {
89195             var parsed = ts.getParseTreeNode(node);
89196             if (parsed !== node) {
89197                 // If the node has been transformed by a `before` transformer, perform no ellision on it
89198                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
89199                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
89200                 // and will trigger debug failures when debug verbosity is turned up
89201                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
89202                     // This node contains TypeScript, so we should visit its children.
89203                     return ts.visitEachChild(node, visitor, context);
89204                 }
89205                 // Otherwise, we can just return the node
89206                 return node;
89207             }
89208             switch (node.kind) {
89209                 case 265 /* ImportDeclaration */:
89210                     return visitImportDeclaration(node);
89211                 case 264 /* ImportEqualsDeclaration */:
89212                     return visitImportEqualsDeclaration(node);
89213                 case 270 /* ExportAssignment */:
89214                     return visitExportAssignment(node);
89215                 case 271 /* ExportDeclaration */:
89216                     return visitExportDeclaration(node);
89217                 default:
89218                     ts.Debug.fail("Unhandled ellided statement");
89219             }
89220         }
89221         /**
89222          * Specialized visitor that visits the immediate children of a namespace.
89223          *
89224          * @param node The node to visit.
89225          */
89226         function namespaceElementVisitor(node) {
89227             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
89228         }
89229         /**
89230          * Specialized visitor that visits the immediate children of a namespace.
89231          *
89232          * @param node The node to visit.
89233          */
89234         function namespaceElementVisitorWorker(node) {
89235             if (node.kind === 271 /* ExportDeclaration */ ||
89236                 node.kind === 265 /* ImportDeclaration */ ||
89237                 node.kind === 266 /* ImportClause */ ||
89238                 (node.kind === 264 /* ImportEqualsDeclaration */ &&
89239                     node.moduleReference.kind === 276 /* ExternalModuleReference */)) {
89240                 // do not emit ES6 imports and exports since they are illegal inside a namespace
89241                 return undefined;
89242             }
89243             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasSyntacticModifier(node, 1 /* Export */)) {
89244                 return visitTypeScript(node);
89245             }
89246             return node;
89247         }
89248         /**
89249          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
89250          *
89251          * @param node The node to visit.
89252          */
89253         function classElementVisitor(node) {
89254             return saveStateAndInvoke(node, classElementVisitorWorker);
89255         }
89256         /**
89257          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
89258          *
89259          * @param node The node to visit.
89260          */
89261         function classElementVisitorWorker(node) {
89262             switch (node.kind) {
89263                 case 170 /* Constructor */:
89264                     return visitConstructor(node);
89265                 case 166 /* PropertyDeclaration */:
89266                     // Property declarations are not TypeScript syntax, but they must be visited
89267                     // for the decorator transformation.
89268                     return visitPropertyDeclaration(node);
89269                 case 175 /* IndexSignature */:
89270                 case 171 /* GetAccessor */:
89271                 case 172 /* SetAccessor */:
89272                 case 168 /* MethodDeclaration */:
89273                 case 169 /* ClassStaticBlockDeclaration */:
89274                     // Fallback to the default visit behavior.
89275                     return visitorWorker(node);
89276                 case 233 /* SemicolonClassElement */:
89277                     return node;
89278                 default:
89279                     return ts.Debug.failBadSyntaxKind(node);
89280             }
89281         }
89282         function modifierVisitor(node) {
89283             if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) {
89284                 return undefined;
89285             }
89286             else if (currentNamespace && node.kind === 93 /* ExportKeyword */) {
89287                 return undefined;
89288             }
89289             return node;
89290         }
89291         /**
89292          * Branching visitor, visits a TypeScript syntax node.
89293          *
89294          * @param node The node to visit.
89295          */
89296         function visitTypeScript(node) {
89297             if (ts.isStatement(node) && ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
89298                 // TypeScript ambient declarations are elided, but some comments may be preserved.
89299                 // See the implementation of `getLeadingComments` in comments.ts for more details.
89300                 return factory.createNotEmittedStatement(node);
89301             }
89302             switch (node.kind) {
89303                 case 93 /* ExportKeyword */:
89304                 case 88 /* DefaultKeyword */:
89305                     // ES6 export and default modifiers are elided when inside a namespace.
89306                     return currentNamespace ? undefined : node;
89307                 case 123 /* PublicKeyword */:
89308                 case 121 /* PrivateKeyword */:
89309                 case 122 /* ProtectedKeyword */:
89310                 case 126 /* AbstractKeyword */:
89311                 case 158 /* OverrideKeyword */:
89312                 case 85 /* ConstKeyword */:
89313                 case 135 /* DeclareKeyword */:
89314                 case 144 /* ReadonlyKeyword */:
89315                 // TypeScript accessibility and readonly modifiers are elided
89316                 // falls through
89317                 case 182 /* ArrayType */:
89318                 case 183 /* TupleType */:
89319                 case 184 /* OptionalType */:
89320                 case 185 /* RestType */:
89321                 case 181 /* TypeLiteral */:
89322                 case 176 /* TypePredicate */:
89323                 case 162 /* TypeParameter */:
89324                 case 130 /* AnyKeyword */:
89325                 case 154 /* UnknownKeyword */:
89326                 case 133 /* BooleanKeyword */:
89327                 case 149 /* StringKeyword */:
89328                 case 146 /* NumberKeyword */:
89329                 case 143 /* NeverKeyword */:
89330                 case 114 /* VoidKeyword */:
89331                 case 150 /* SymbolKeyword */:
89332                 case 179 /* ConstructorType */:
89333                 case 178 /* FunctionType */:
89334                 case 180 /* TypeQuery */:
89335                 case 177 /* TypeReference */:
89336                 case 186 /* UnionType */:
89337                 case 187 /* IntersectionType */:
89338                 case 188 /* ConditionalType */:
89339                 case 190 /* ParenthesizedType */:
89340                 case 191 /* ThisType */:
89341                 case 192 /* TypeOperator */:
89342                 case 193 /* IndexedAccessType */:
89343                 case 194 /* MappedType */:
89344                 case 195 /* LiteralType */:
89345                 // TypeScript type nodes are elided.
89346                 // falls through
89347                 case 175 /* IndexSignature */:
89348                 // TypeScript index signatures are elided.
89349                 // falls through
89350                 case 164 /* Decorator */:
89351                     // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
89352                     return undefined;
89353                 case 258 /* TypeAliasDeclaration */:
89354                     // TypeScript type-only declarations are elided.
89355                     return factory.createNotEmittedStatement(node);
89356                 case 166 /* PropertyDeclaration */:
89357                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
89358                     return visitPropertyDeclaration(node);
89359                 case 263 /* NamespaceExportDeclaration */:
89360                     // TypeScript namespace export declarations are elided.
89361                     return undefined;
89362                 case 170 /* Constructor */:
89363                     return visitConstructor(node);
89364                 case 257 /* InterfaceDeclaration */:
89365                     // TypeScript interfaces are elided, but some comments may be preserved.
89366                     // See the implementation of `getLeadingComments` in comments.ts for more details.
89367                     return factory.createNotEmittedStatement(node);
89368                 case 256 /* ClassDeclaration */:
89369                     // This may be a class declaration with TypeScript syntax extensions.
89370                     //
89371                     // TypeScript class syntax extensions include:
89372                     // - decorators
89373                     // - optional `implements` heritage clause
89374                     // - parameter property assignments in the constructor
89375                     // - index signatures
89376                     // - method overload signatures
89377                     return visitClassDeclaration(node);
89378                 case 225 /* ClassExpression */:
89379                     // This may be a class expression with TypeScript syntax extensions.
89380                     //
89381                     // TypeScript class syntax extensions include:
89382                     // - decorators
89383                     // - optional `implements` heritage clause
89384                     // - parameter property assignments in the constructor
89385                     // - index signatures
89386                     // - method overload signatures
89387                     return visitClassExpression(node);
89388                 case 290 /* HeritageClause */:
89389                     // This may be a heritage clause with TypeScript syntax extensions.
89390                     //
89391                     // TypeScript heritage clause extensions include:
89392                     // - `implements` clause
89393                     return visitHeritageClause(node);
89394                 case 227 /* ExpressionWithTypeArguments */:
89395                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
89396                     return visitExpressionWithTypeArguments(node);
89397                 case 168 /* MethodDeclaration */:
89398                     // TypeScript method declarations may have decorators, modifiers
89399                     // or type annotations.
89400                     return visitMethodDeclaration(node);
89401                 case 171 /* GetAccessor */:
89402                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
89403                     return visitGetAccessor(node);
89404                 case 172 /* SetAccessor */:
89405                     // Set Accessors can have TypeScript modifiers and type annotations.
89406                     return visitSetAccessor(node);
89407                 case 255 /* FunctionDeclaration */:
89408                     // Typescript function declarations can have modifiers, decorators, and type annotations.
89409                     return visitFunctionDeclaration(node);
89410                 case 212 /* FunctionExpression */:
89411                     // TypeScript function expressions can have modifiers and type annotations.
89412                     return visitFunctionExpression(node);
89413                 case 213 /* ArrowFunction */:
89414                     // TypeScript arrow functions can have modifiers and type annotations.
89415                     return visitArrowFunction(node);
89416                 case 163 /* Parameter */:
89417                     // This may be a parameter declaration with TypeScript syntax extensions.
89418                     //
89419                     // TypeScript parameter declaration syntax extensions include:
89420                     // - decorators
89421                     // - accessibility modifiers
89422                     // - the question mark (?) token for optional parameters
89423                     // - type annotations
89424                     // - this parameters
89425                     return visitParameter(node);
89426                 case 211 /* ParenthesizedExpression */:
89427                     // ParenthesizedExpressions are TypeScript if their expression is a
89428                     // TypeAssertion or AsExpression
89429                     return visitParenthesizedExpression(node);
89430                 case 210 /* TypeAssertionExpression */:
89431                 case 228 /* AsExpression */:
89432                     // TypeScript type assertions are removed, but their subtrees are preserved.
89433                     return visitAssertionExpression(node);
89434                 case 207 /* CallExpression */:
89435                     return visitCallExpression(node);
89436                 case 208 /* NewExpression */:
89437                     return visitNewExpression(node);
89438                 case 209 /* TaggedTemplateExpression */:
89439                     return visitTaggedTemplateExpression(node);
89440                 case 229 /* NonNullExpression */:
89441                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
89442                     return visitNonNullExpression(node);
89443                 case 259 /* EnumDeclaration */:
89444                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
89445                     return visitEnumDeclaration(node);
89446                 case 236 /* VariableStatement */:
89447                     // TypeScript namespace exports for variable statements must be transformed.
89448                     return visitVariableStatement(node);
89449                 case 253 /* VariableDeclaration */:
89450                     return visitVariableDeclaration(node);
89451                 case 260 /* ModuleDeclaration */:
89452                     // TypeScript namespace declarations must be transformed.
89453                     return visitModuleDeclaration(node);
89454                 case 264 /* ImportEqualsDeclaration */:
89455                     // TypeScript namespace or external module import.
89456                     return visitImportEqualsDeclaration(node);
89457                 case 278 /* JsxSelfClosingElement */:
89458                     return visitJsxSelfClosingElement(node);
89459                 case 279 /* JsxOpeningElement */:
89460                     return visitJsxJsxOpeningElement(node);
89461                 default:
89462                     // node contains some other TypeScript syntax
89463                     return ts.visitEachChild(node, visitor, context);
89464             }
89465         }
89466         function visitSourceFile(node) {
89467             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
89468                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
89469                 !ts.isJsonSourceFile(node);
89470             return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
89471         }
89472         function getClassFacts(node, staticProperties) {
89473             var facts = 0 /* None */;
89474             if (ts.some(staticProperties))
89475                 facts |= 1 /* HasStaticInitializedProperties */;
89476             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
89477             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */)
89478                 facts |= 64 /* IsDerivedClass */;
89479             if (ts.classOrConstructorParameterIsDecorated(node))
89480                 facts |= 2 /* HasConstructorDecorators */;
89481             if (ts.childIsDecorated(node))
89482                 facts |= 4 /* HasMemberDecorators */;
89483             if (isExportOfNamespace(node))
89484                 facts |= 8 /* IsExportOfNamespace */;
89485             else if (isDefaultExternalModuleExport(node))
89486                 facts |= 32 /* IsDefaultExternalExport */;
89487             else if (isNamedExternalModuleExport(node))
89488                 facts |= 16 /* IsNamedExternalExport */;
89489             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
89490                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
89491             return facts;
89492         }
89493         function hasTypeScriptClassSyntax(node) {
89494             return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */);
89495         }
89496         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
89497             return ts.some(node.decorators)
89498                 || ts.some(node.typeParameters)
89499                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
89500                 || ts.some(node.members, hasTypeScriptClassSyntax);
89501         }
89502         function visitClassDeclaration(node) {
89503             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* Export */))) {
89504                 return ts.visitEachChild(node, visitor, context);
89505             }
89506             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
89507             var facts = getClassFacts(node, staticProperties);
89508             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
89509                 context.startLexicalEnvironment();
89510             }
89511             var name = node.name || (facts & 5 /* NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined);
89512             var classStatement = facts & 2 /* HasConstructorDecorators */
89513                 ? createClassDeclarationHeadWithDecorators(node, name)
89514                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
89515             var statements = [classStatement];
89516             // Write any decorators of the node.
89517             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
89518             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
89519             addConstructorDecorationStatement(statements, node);
89520             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
89521                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
89522                 // 'es2015' transformer can properly nest static initializers and decorators. The result
89523                 // looks something like:
89524                 //
89525                 //  var C = function () {
89526                 //      class C {
89527                 //      }
89528                 //      C.static_prop = 1;
89529                 //      return C;
89530                 //  }();
89531                 //
89532                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
89533                 var localName = factory.getInternalName(node);
89534                 // The following partially-emitted expression exists purely to align our sourcemap
89535                 // emit with the original emitter.
89536                 var outer = factory.createPartiallyEmittedExpression(localName);
89537                 ts.setTextRangeEnd(outer, closingBraceLocation.end);
89538                 ts.setEmitFlags(outer, 1536 /* NoComments */);
89539                 var statement = factory.createReturnStatement(outer);
89540                 ts.setTextRangePos(statement, closingBraceLocation.pos);
89541                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
89542                 statements.push(statement);
89543                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
89544                 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
89545                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
89546                 var varStatement = factory.createVariableStatement(
89547                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
89548                     factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
89549                     /*exclamationToken*/ undefined, 
89550                     /*type*/ undefined, iife)
89551                 ]));
89552                 ts.setOriginalNode(varStatement, node);
89553                 ts.setCommentRange(varStatement, node);
89554                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
89555                 ts.startOnNewLine(varStatement);
89556                 statements = [varStatement];
89557             }
89558             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
89559             // Otherwise, if the class was exported at the top level and was decorated, emit an export
89560             // declaration or export default for the class.
89561             if (facts & 8 /* IsExportOfNamespace */) {
89562                 addExportMemberAssignment(statements, node);
89563             }
89564             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
89565                 if (facts & 32 /* IsDefaultExternalExport */) {
89566                     statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
89567                 }
89568                 else if (facts & 16 /* IsNamedExternalExport */) {
89569                     statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
89570                 }
89571             }
89572             if (statements.length > 1) {
89573                 // Add a DeclarationMarker as a marker for the end of the declaration
89574                 statements.push(factory.createEndOfDeclarationMarker(node));
89575                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
89576             }
89577             return ts.singleOrMany(statements);
89578         }
89579         /**
89580          * Transforms a non-decorated class declaration and appends the resulting statements.
89581          *
89582          * @param node A ClassDeclaration node.
89583          * @param name The name of the class.
89584          * @param facts Precomputed facts about the class.
89585          */
89586         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
89587             //  ${modifiers} class ${name} ${heritageClauses} {
89588             //      ${members}
89589             //  }
89590             // we do not emit modifiers on the declaration if we are emitting an IIFE
89591             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
89592                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
89593                 : undefined;
89594             var classDeclaration = factory.createClassDeclaration(
89595             /*decorators*/ undefined, modifiers, name, 
89596             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
89597             // To better align with the old emitter, we should not emit a trailing source map
89598             // entry if the class has static properties.
89599             var emitFlags = ts.getEmitFlags(node);
89600             if (facts & 1 /* HasStaticInitializedProperties */) {
89601                 emitFlags |= 32 /* NoTrailingSourceMap */;
89602             }
89603             ts.setTextRange(classDeclaration, node);
89604             ts.setOriginalNode(classDeclaration, node);
89605             ts.setEmitFlags(classDeclaration, emitFlags);
89606             return classDeclaration;
89607         }
89608         /**
89609          * Transforms a decorated class declaration and appends the resulting statements. If
89610          * the class requires an alias to avoid issues with double-binding, the alias is returned.
89611          */
89612         function createClassDeclarationHeadWithDecorators(node, name) {
89613             // When we emit an ES6 class that has a class decorator, we must tailor the
89614             // emit to certain specific cases.
89615             //
89616             // In the simplest case, we emit the class declaration as a let declaration, and
89617             // evaluate decorators after the close of the class body:
89618             //
89619             //  [Example 1]
89620             //  ---------------------------------------------------------------------
89621             //  TypeScript                      | Javascript
89622             //  ---------------------------------------------------------------------
89623             //  @dec                            | let C = class C {
89624             //  class C {                       | }
89625             //  }                               | C = __decorate([dec], C);
89626             //  ---------------------------------------------------------------------
89627             //  @dec                            | let C = class C {
89628             //  export class C {                | }
89629             //  }                               | C = __decorate([dec], C);
89630             //                                  | export { C };
89631             //  ---------------------------------------------------------------------
89632             //
89633             // If a class declaration contains a reference to itself *inside* of the class body,
89634             // this introduces two bindings to the class: One outside of the class body, and one
89635             // inside of the class body. If we apply decorators as in [Example 1] above, there
89636             // is the possibility that the decorator `dec` will return a new value for the
89637             // constructor, which would result in the binding inside of the class no longer
89638             // pointing to the same reference as the binding outside of the class.
89639             //
89640             // As a result, we must instead rewrite all references to the class *inside* of the
89641             // class body to instead point to a local temporary alias for the class:
89642             //
89643             //  [Example 2]
89644             //  ---------------------------------------------------------------------
89645             //  TypeScript                      | Javascript
89646             //  ---------------------------------------------------------------------
89647             //  @dec                            | let C = C_1 = class C {
89648             //  class C {                       |   static x() { return C_1.y; }
89649             //    static x() { return C.y; }    | }
89650             //    static y = 1;                 | C.y = 1;
89651             //  }                               | C = C_1 = __decorate([dec], C);
89652             //                                  | var C_1;
89653             //  ---------------------------------------------------------------------
89654             //  @dec                            | let C = class C {
89655             //  export class C {                |   static x() { return C_1.y; }
89656             //    static x() { return C.y; }    | }
89657             //    static y = 1;                 | C.y = 1;
89658             //  }                               | C = C_1 = __decorate([dec], C);
89659             //                                  | export { C };
89660             //                                  | var C_1;
89661             //  ---------------------------------------------------------------------
89662             //
89663             // If a class declaration is the default export of a module, we instead emit
89664             // the export after the decorated declaration:
89665             //
89666             //  [Example 3]
89667             //  ---------------------------------------------------------------------
89668             //  TypeScript                      | Javascript
89669             //  ---------------------------------------------------------------------
89670             //  @dec                            | let default_1 = class {
89671             //  export default class {          | }
89672             //  }                               | default_1 = __decorate([dec], default_1);
89673             //                                  | export default default_1;
89674             //  ---------------------------------------------------------------------
89675             //  @dec                            | let C = class C {
89676             //  export default class C {        | }
89677             //  }                               | C = __decorate([dec], C);
89678             //                                  | export default C;
89679             //  ---------------------------------------------------------------------
89680             //
89681             // If the class declaration is the default export and a reference to itself
89682             // inside of the class body, we must emit both an alias for the class *and*
89683             // move the export after the declaration:
89684             //
89685             //  [Example 4]
89686             //  ---------------------------------------------------------------------
89687             //  TypeScript                      | Javascript
89688             //  ---------------------------------------------------------------------
89689             //  @dec                            | let C = class C {
89690             //  export default class C {        |   static x() { return C_1.y; }
89691             //    static x() { return C.y; }    | }
89692             //    static y = 1;                 | C.y = 1;
89693             //  }                               | C = C_1 = __decorate([dec], C);
89694             //                                  | export default C;
89695             //                                  | var C_1;
89696             //  ---------------------------------------------------------------------
89697             //
89698             var location = ts.moveRangePastDecorators(node);
89699             var classAlias = getClassAliasIfNeeded(node);
89700             // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name
89701             // without any block-scoped variable collision handling
89702             var declName = languageVersion <= 2 /* ES2015 */ ?
89703                 factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) :
89704                 factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
89705             //  ... = class ${name} ${heritageClauses} {
89706             //      ${members}
89707             //  }
89708             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
89709             var members = transformClassMembers(node);
89710             var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
89711             ts.setOriginalNode(classExpression, node);
89712             ts.setTextRange(classExpression, location);
89713             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
89714             //                                         or decoratedClassAlias if the class contain self-reference.
89715             var statement = factory.createVariableStatement(
89716             /*modifiers*/ undefined, factory.createVariableDeclarationList([
89717                 factory.createVariableDeclaration(declName, 
89718                 /*exclamationToken*/ undefined, 
89719                 /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression)
89720             ], 1 /* Let */));
89721             ts.setOriginalNode(statement, node);
89722             ts.setTextRange(statement, location);
89723             ts.setCommentRange(statement, node);
89724             return statement;
89725         }
89726         function visitClassExpression(node) {
89727             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
89728                 return ts.visitEachChild(node, visitor, context);
89729             }
89730             var classExpression = factory.createClassExpression(
89731             /*decorators*/ undefined, 
89732             /*modifiers*/ undefined, node.name, 
89733             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
89734             ts.setOriginalNode(classExpression, node);
89735             ts.setTextRange(classExpression, node);
89736             return classExpression;
89737         }
89738         /**
89739          * Transforms the members of a class.
89740          *
89741          * @param node The current class.
89742          */
89743         function transformClassMembers(node) {
89744             var members = [];
89745             var constructor = ts.getFirstConstructorWithBody(node);
89746             var parametersWithPropertyAssignments = constructor &&
89747                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
89748             if (parametersWithPropertyAssignments) {
89749                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
89750                     var parameter = parametersWithPropertyAssignments_1[_i];
89751                     if (ts.isIdentifier(parameter.name)) {
89752                         members.push(ts.setOriginalNode(factory.createPropertyDeclaration(
89753                         /*decorators*/ undefined, 
89754                         /*modifiers*/ undefined, parameter.name, 
89755                         /*questionOrExclamationToken*/ undefined, 
89756                         /*type*/ undefined, 
89757                         /*initializer*/ undefined), parameter));
89758                     }
89759                 }
89760             }
89761             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
89762             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
89763         }
89764         /**
89765          * Gets either the static or instance members of a class that are decorated, or have
89766          * parameters that are decorated.
89767          *
89768          * @param node The class containing the member.
89769          * @param isStatic A value indicating whether to retrieve static or instance members of
89770          *                 the class.
89771          */
89772         function getDecoratedClassElements(node, isStatic) {
89773             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
89774         }
89775         /**
89776          * Determines whether a class member is a static member of a class that is decorated, or
89777          * has parameters that are decorated.
89778          *
89779          * @param member The class member.
89780          */
89781         function isStaticDecoratedClassElement(member, parent) {
89782             return isDecoratedClassElement(member, /*isStaticElement*/ true, parent);
89783         }
89784         /**
89785          * Determines whether a class member is an instance member of a class that is decorated,
89786          * or has parameters that are decorated.
89787          *
89788          * @param member The class member.
89789          */
89790         function isInstanceDecoratedClassElement(member, parent) {
89791             return isDecoratedClassElement(member, /*isStaticElement*/ false, parent);
89792         }
89793         /**
89794          * Determines whether a class member is either a static or an instance member of a class
89795          * that is decorated, or has parameters that are decorated.
89796          *
89797          * @param member The class member.
89798          */
89799         function isDecoratedClassElement(member, isStaticElement, parent) {
89800             return ts.nodeOrChildIsDecorated(member, parent)
89801                 && isStaticElement === ts.isStatic(member);
89802         }
89803         /**
89804          * Gets an array of arrays of decorators for the parameters of a function-like node.
89805          * The offset into the result array should correspond to the offset of the parameter.
89806          *
89807          * @param node The function-like node.
89808          */
89809         function getDecoratorsOfParameters(node) {
89810             var decorators;
89811             if (node) {
89812                 var parameters = node.parameters;
89813                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
89814                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
89815                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
89816                 for (var i = 0; i < numParameters; i++) {
89817                     var parameter = parameters[i + firstParameterOffset];
89818                     if (decorators || parameter.decorators) {
89819                         if (!decorators) {
89820                             decorators = new Array(numParameters);
89821                         }
89822                         decorators[i] = parameter.decorators;
89823                     }
89824                 }
89825             }
89826             return decorators;
89827         }
89828         /**
89829          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
89830          * parameters of the constructor of the class.
89831          *
89832          * @param node The class node.
89833          */
89834         function getAllDecoratorsOfConstructor(node) {
89835             var decorators = node.decorators;
89836             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
89837             if (!decorators && !parameters) {
89838                 return undefined;
89839             }
89840             return {
89841                 decorators: decorators,
89842                 parameters: parameters
89843             };
89844         }
89845         /**
89846          * Gets an AllDecorators object containing the decorators for the member and its parameters.
89847          *
89848          * @param node The class node that contains the member.
89849          * @param member The class member.
89850          */
89851         function getAllDecoratorsOfClassElement(node, member) {
89852             switch (member.kind) {
89853                 case 171 /* GetAccessor */:
89854                 case 172 /* SetAccessor */:
89855                     return getAllDecoratorsOfAccessors(node, member);
89856                 case 168 /* MethodDeclaration */:
89857                     return getAllDecoratorsOfMethod(member);
89858                 case 166 /* PropertyDeclaration */:
89859                     return getAllDecoratorsOfProperty(member);
89860                 default:
89861                     return undefined;
89862             }
89863         }
89864         /**
89865          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
89866          *
89867          * @param node The class node that contains the accessor.
89868          * @param accessor The class accessor member.
89869          */
89870         function getAllDecoratorsOfAccessors(node, accessor) {
89871             if (!accessor.body) {
89872                 return undefined;
89873             }
89874             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
89875             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
89876             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
89877                 return undefined;
89878             }
89879             var decorators = firstAccessorWithDecorators.decorators;
89880             var parameters = getDecoratorsOfParameters(setAccessor);
89881             if (!decorators && !parameters) {
89882                 return undefined;
89883             }
89884             return { decorators: decorators, parameters: parameters };
89885         }
89886         /**
89887          * Gets an AllDecorators object containing the decorators for the method and its parameters.
89888          *
89889          * @param method The class method member.
89890          */
89891         function getAllDecoratorsOfMethod(method) {
89892             if (!method.body) {
89893                 return undefined;
89894             }
89895             var decorators = method.decorators;
89896             var parameters = getDecoratorsOfParameters(method);
89897             if (!decorators && !parameters) {
89898                 return undefined;
89899             }
89900             return { decorators: decorators, parameters: parameters };
89901         }
89902         /**
89903          * Gets an AllDecorators object containing the decorators for the property.
89904          *
89905          * @param property The class property member.
89906          */
89907         function getAllDecoratorsOfProperty(property) {
89908             var decorators = property.decorators;
89909             if (!decorators) {
89910                 return undefined;
89911             }
89912             return { decorators: decorators };
89913         }
89914         /**
89915          * Transforms all of the decorators for a declaration into an array of expressions.
89916          *
89917          * @param node The declaration node.
89918          * @param allDecorators An object containing all of the decorators for the declaration.
89919          */
89920         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
89921             if (!allDecorators) {
89922                 return undefined;
89923             }
89924             var decoratorExpressions = [];
89925             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
89926             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
89927             addTypeMetadata(node, container, decoratorExpressions);
89928             return decoratorExpressions;
89929         }
89930         /**
89931          * Generates statements used to apply decorators to either the static or instance members
89932          * of a class.
89933          *
89934          * @param node The class node.
89935          * @param isStatic A value indicating whether to generate statements for static or
89936          *                 instance members.
89937          */
89938         function addClassElementDecorationStatements(statements, node, isStatic) {
89939             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
89940         }
89941         /**
89942          * Generates expressions used to apply decorators to either the static or instance members
89943          * of a class.
89944          *
89945          * @param node The class node.
89946          * @param isStatic A value indicating whether to generate expressions for static or
89947          *                 instance members.
89948          */
89949         function generateClassElementDecorationExpressions(node, isStatic) {
89950             var members = getDecoratedClassElements(node, isStatic);
89951             var expressions;
89952             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
89953                 var member = members_6[_i];
89954                 var expression = generateClassElementDecorationExpression(node, member);
89955                 if (expression) {
89956                     if (!expressions) {
89957                         expressions = [expression];
89958                     }
89959                     else {
89960                         expressions.push(expression);
89961                     }
89962                 }
89963             }
89964             return expressions;
89965         }
89966         /**
89967          * Generates an expression used to evaluate class element decorators at runtime.
89968          *
89969          * @param node The class node that contains the member.
89970          * @param member The class member.
89971          */
89972         function generateClassElementDecorationExpression(node, member) {
89973             var allDecorators = getAllDecoratorsOfClassElement(node, member);
89974             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
89975             if (!decoratorExpressions) {
89976                 return undefined;
89977             }
89978             // Emit the call to __decorate. Given the following:
89979             //
89980             //   class C {
89981             //     @dec method(@dec2 x) {}
89982             //     @dec get accessor() {}
89983             //     @dec prop;
89984             //   }
89985             //
89986             // The emit for a method is:
89987             //
89988             //   __decorate([
89989             //       dec,
89990             //       __param(0, dec2),
89991             //       __metadata("design:type", Function),
89992             //       __metadata("design:paramtypes", [Object]),
89993             //       __metadata("design:returntype", void 0)
89994             //   ], C.prototype, "method", null);
89995             //
89996             // The emit for an accessor is:
89997             //
89998             //   __decorate([
89999             //       dec
90000             //   ], C.prototype, "accessor", null);
90001             //
90002             // The emit for a property is:
90003             //
90004             //   __decorate([
90005             //       dec
90006             //   ], C.prototype, "prop");
90007             //
90008             var prefix = getClassMemberPrefix(node, member);
90009             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
90010             var descriptor = languageVersion > 0 /* ES3 */
90011                 ? member.kind === 166 /* PropertyDeclaration */
90012                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
90013                     // should not invoke `Object.getOwnPropertyDescriptor`.
90014                     ? factory.createVoidZero()
90015                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
90016                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
90017                     : factory.createNull()
90018                 : undefined;
90019             var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor);
90020             ts.setTextRange(helper, ts.moveRangePastDecorators(member));
90021             ts.setEmitFlags(helper, 1536 /* NoComments */);
90022             return helper;
90023         }
90024         /**
90025          * Generates a __decorate helper call for a class constructor.
90026          *
90027          * @param node The class node.
90028          */
90029         function addConstructorDecorationStatement(statements, node) {
90030             var expression = generateConstructorDecorationExpression(node);
90031             if (expression) {
90032                 statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node));
90033             }
90034         }
90035         /**
90036          * Generates a __decorate helper call for a class constructor.
90037          *
90038          * @param node The class node.
90039          */
90040         function generateConstructorDecorationExpression(node) {
90041             var allDecorators = getAllDecoratorsOfConstructor(node);
90042             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
90043             if (!decoratorExpressions) {
90044                 return undefined;
90045             }
90046             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
90047             // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name
90048             // without any block-scoped variable collision handling
90049             var localName = languageVersion <= 2 /* ES2015 */ ?
90050                 factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) :
90051                 factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
90052             var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
90053             var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate);
90054             ts.setEmitFlags(expression, 1536 /* NoComments */);
90055             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
90056             return expression;
90057         }
90058         /**
90059          * Transforms a decorator into an expression.
90060          *
90061          * @param decorator The decorator node.
90062          */
90063         function transformDecorator(decorator) {
90064             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
90065         }
90066         /**
90067          * Transforms the decorators of a parameter.
90068          *
90069          * @param decorators The decorators for the parameter at the provided offset.
90070          * @param parameterOffset The offset of the parameter.
90071          */
90072         function transformDecoratorsOfParameter(decorators, parameterOffset) {
90073             var expressions;
90074             if (decorators) {
90075                 expressions = [];
90076                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
90077                     var decorator = decorators_1[_i];
90078                     var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset);
90079                     ts.setTextRange(helper, decorator.expression);
90080                     ts.setEmitFlags(helper, 1536 /* NoComments */);
90081                     expressions.push(helper);
90082                 }
90083             }
90084             return expressions;
90085         }
90086         /**
90087          * Adds optional type metadata for a declaration.
90088          *
90089          * @param node The declaration node.
90090          * @param decoratorExpressions The destination array to which to add new decorator expressions.
90091          */
90092         function addTypeMetadata(node, container, decoratorExpressions) {
90093             if (USE_NEW_TYPE_METADATA_FORMAT) {
90094                 addNewTypeMetadata(node, container, decoratorExpressions);
90095             }
90096             else {
90097                 addOldTypeMetadata(node, container, decoratorExpressions);
90098             }
90099         }
90100         function addOldTypeMetadata(node, container, decoratorExpressions) {
90101             if (compilerOptions.emitDecoratorMetadata) {
90102                 if (shouldAddTypeMetadata(node)) {
90103                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node)));
90104                 }
90105                 if (shouldAddParamTypesMetadata(node)) {
90106                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container)));
90107                 }
90108                 if (shouldAddReturnTypeMetadata(node)) {
90109                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node)));
90110                 }
90111             }
90112         }
90113         function addNewTypeMetadata(node, container, decoratorExpressions) {
90114             if (compilerOptions.emitDecoratorMetadata) {
90115                 var properties = void 0;
90116                 if (shouldAddTypeMetadata(node)) {
90117                     (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
90118                 }
90119                 if (shouldAddParamTypesMetadata(node)) {
90120                     (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
90121                 }
90122                 if (shouldAddReturnTypeMetadata(node)) {
90123                     (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
90124                 }
90125                 if (properties) {
90126                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)));
90127                 }
90128             }
90129         }
90130         /**
90131          * Determines whether to emit the "design:type" metadata based on the node's kind.
90132          * The caller should have already tested whether the node has decorators and whether the
90133          * emitDecoratorMetadata compiler option is set.
90134          *
90135          * @param node The node to test.
90136          */
90137         function shouldAddTypeMetadata(node) {
90138             var kind = node.kind;
90139             return kind === 168 /* MethodDeclaration */
90140                 || kind === 171 /* GetAccessor */
90141                 || kind === 172 /* SetAccessor */
90142                 || kind === 166 /* PropertyDeclaration */;
90143         }
90144         /**
90145          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
90146          * The caller should have already tested whether the node has decorators and whether the
90147          * emitDecoratorMetadata compiler option is set.
90148          *
90149          * @param node The node to test.
90150          */
90151         function shouldAddReturnTypeMetadata(node) {
90152             return node.kind === 168 /* MethodDeclaration */;
90153         }
90154         /**
90155          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
90156          * The caller should have already tested whether the node has decorators and whether the
90157          * emitDecoratorMetadata compiler option is set.
90158          *
90159          * @param node The node to test.
90160          */
90161         function shouldAddParamTypesMetadata(node) {
90162             switch (node.kind) {
90163                 case 256 /* ClassDeclaration */:
90164                 case 225 /* ClassExpression */:
90165                     return ts.getFirstConstructorWithBody(node) !== undefined;
90166                 case 168 /* MethodDeclaration */:
90167                 case 171 /* GetAccessor */:
90168                 case 172 /* SetAccessor */:
90169                     return true;
90170             }
90171             return false;
90172         }
90173         function getAccessorTypeNode(node) {
90174             var accessors = resolver.getAllAccessorDeclarations(node);
90175             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
90176                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
90177         }
90178         /**
90179          * Serializes the type of a node for use with decorator type metadata.
90180          *
90181          * @param node The node that should have its type serialized.
90182          */
90183         function serializeTypeOfNode(node) {
90184             switch (node.kind) {
90185                 case 166 /* PropertyDeclaration */:
90186                 case 163 /* Parameter */:
90187                     return serializeTypeNode(node.type);
90188                 case 172 /* SetAccessor */:
90189                 case 171 /* GetAccessor */:
90190                     return serializeTypeNode(getAccessorTypeNode(node));
90191                 case 256 /* ClassDeclaration */:
90192                 case 225 /* ClassExpression */:
90193                 case 168 /* MethodDeclaration */:
90194                     return factory.createIdentifier("Function");
90195                 default:
90196                     return factory.createVoidZero();
90197             }
90198         }
90199         /**
90200          * Serializes the types of the parameters of a node for use with decorator type metadata.
90201          *
90202          * @param node The node that should have its parameter types serialized.
90203          */
90204         function serializeParameterTypesOfNode(node, container) {
90205             var valueDeclaration = ts.isClassLike(node)
90206                 ? ts.getFirstConstructorWithBody(node)
90207                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
90208                     ? node
90209                     : undefined;
90210             var expressions = [];
90211             if (valueDeclaration) {
90212                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
90213                 var numParameters = parameters.length;
90214                 for (var i = 0; i < numParameters; i++) {
90215                     var parameter = parameters[i];
90216                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
90217                         continue;
90218                     }
90219                     if (parameter.dotDotDotToken) {
90220                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
90221                     }
90222                     else {
90223                         expressions.push(serializeTypeOfNode(parameter));
90224                     }
90225                 }
90226             }
90227             return factory.createArrayLiteralExpression(expressions);
90228         }
90229         function getParametersOfDecoratedDeclaration(node, container) {
90230             if (container && node.kind === 171 /* GetAccessor */) {
90231                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
90232                 if (setAccessor) {
90233                     return setAccessor.parameters;
90234                 }
90235             }
90236             return node.parameters;
90237         }
90238         /**
90239          * Serializes the return type of a node for use with decorator type metadata.
90240          *
90241          * @param node The node that should have its return type serialized.
90242          */
90243         function serializeReturnTypeOfNode(node) {
90244             if (ts.isFunctionLike(node) && node.type) {
90245                 return serializeTypeNode(node.type);
90246             }
90247             else if (ts.isAsyncFunction(node)) {
90248                 return factory.createIdentifier("Promise");
90249             }
90250             return factory.createVoidZero();
90251         }
90252         /**
90253          * Serializes a type node for use with decorator type metadata.
90254          *
90255          * Types are serialized in the following fashion:
90256          * - Void types point to "undefined" (e.g. "void 0")
90257          * - Function and Constructor types point to the global "Function" constructor.
90258          * - Interface types with a call or construct signature types point to the global
90259          *   "Function" constructor.
90260          * - Array and Tuple types point to the global "Array" constructor.
90261          * - Type predicates and booleans point to the global "Boolean" constructor.
90262          * - String literal types and strings point to the global "String" constructor.
90263          * - Enum and number types point to the global "Number" constructor.
90264          * - Symbol types point to the global "Symbol" constructor.
90265          * - Type references to classes (or class-like variables) point to the constructor for the class.
90266          * - Anything else points to the global "Object" constructor.
90267          *
90268          * @param node The type node to serialize.
90269          */
90270         function serializeTypeNode(node) {
90271             if (node === undefined) {
90272                 return factory.createIdentifier("Object");
90273             }
90274             switch (node.kind) {
90275                 case 114 /* VoidKeyword */:
90276                 case 152 /* UndefinedKeyword */:
90277                 case 143 /* NeverKeyword */:
90278                     return factory.createVoidZero();
90279                 case 190 /* ParenthesizedType */:
90280                     return serializeTypeNode(node.type);
90281                 case 178 /* FunctionType */:
90282                 case 179 /* ConstructorType */:
90283                     return factory.createIdentifier("Function");
90284                 case 182 /* ArrayType */:
90285                 case 183 /* TupleType */:
90286                     return factory.createIdentifier("Array");
90287                 case 176 /* TypePredicate */:
90288                 case 133 /* BooleanKeyword */:
90289                     return factory.createIdentifier("Boolean");
90290                 case 149 /* StringKeyword */:
90291                     return factory.createIdentifier("String");
90292                 case 147 /* ObjectKeyword */:
90293                     return factory.createIdentifier("Object");
90294                 case 195 /* LiteralType */:
90295                     switch (node.literal.kind) {
90296                         case 10 /* StringLiteral */:
90297                         case 14 /* NoSubstitutionTemplateLiteral */:
90298                             return factory.createIdentifier("String");
90299                         case 218 /* PrefixUnaryExpression */:
90300                         case 8 /* NumericLiteral */:
90301                             return factory.createIdentifier("Number");
90302                         case 9 /* BigIntLiteral */:
90303                             return getGlobalBigIntNameWithFallback();
90304                         case 110 /* TrueKeyword */:
90305                         case 95 /* FalseKeyword */:
90306                             return factory.createIdentifier("Boolean");
90307                         case 104 /* NullKeyword */:
90308                             return factory.createVoidZero();
90309                         default:
90310                             return ts.Debug.failBadSyntaxKind(node.literal);
90311                     }
90312                 case 146 /* NumberKeyword */:
90313                     return factory.createIdentifier("Number");
90314                 case 157 /* BigIntKeyword */:
90315                     return getGlobalBigIntNameWithFallback();
90316                 case 150 /* SymbolKeyword */:
90317                     return languageVersion < 2 /* ES2015 */
90318                         ? getGlobalSymbolNameWithFallback()
90319                         : factory.createIdentifier("Symbol");
90320                 case 177 /* TypeReference */:
90321                     return serializeTypeReferenceNode(node);
90322                 case 187 /* IntersectionType */:
90323                 case 186 /* UnionType */:
90324                     return serializeTypeList(node.types);
90325                 case 188 /* ConditionalType */:
90326                     return serializeTypeList([node.trueType, node.falseType]);
90327                 case 192 /* TypeOperator */:
90328                     if (node.operator === 144 /* ReadonlyKeyword */) {
90329                         return serializeTypeNode(node.type);
90330                     }
90331                     break;
90332                 case 180 /* TypeQuery */:
90333                 case 193 /* IndexedAccessType */:
90334                 case 194 /* MappedType */:
90335                 case 181 /* TypeLiteral */:
90336                 case 130 /* AnyKeyword */:
90337                 case 154 /* UnknownKeyword */:
90338                 case 191 /* ThisType */:
90339                 case 199 /* ImportType */:
90340                     break;
90341                 // handle JSDoc types from an invalid parse
90342                 case 310 /* JSDocAllType */:
90343                 case 311 /* JSDocUnknownType */:
90344                 case 315 /* JSDocFunctionType */:
90345                 case 316 /* JSDocVariadicType */:
90346                 case 317 /* JSDocNamepathType */:
90347                     break;
90348                 case 312 /* JSDocNullableType */:
90349                 case 313 /* JSDocNonNullableType */:
90350                 case 314 /* JSDocOptionalType */:
90351                     return serializeTypeNode(node.type);
90352                 default:
90353                     return ts.Debug.failBadSyntaxKind(node);
90354             }
90355             return factory.createIdentifier("Object");
90356         }
90357         function serializeTypeList(types) {
90358             // Note when updating logic here also update getEntityNameForDecoratorMetadata
90359             // so that aliases can be marked as referenced
90360             var serializedUnion;
90361             for (var _i = 0, types_23 = types; _i < types_23.length; _i++) {
90362                 var typeNode = types_23[_i];
90363                 while (typeNode.kind === 190 /* ParenthesizedType */) {
90364                     typeNode = typeNode.type; // Skip parens if need be
90365                 }
90366                 if (typeNode.kind === 143 /* NeverKeyword */) {
90367                     continue; // Always elide `never` from the union/intersection if possible
90368                 }
90369                 if (!strictNullChecks && (typeNode.kind === 195 /* LiteralType */ && typeNode.literal.kind === 104 /* NullKeyword */ || typeNode.kind === 152 /* UndefinedKeyword */)) {
90370                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
90371                 }
90372                 var serializedIndividual = serializeTypeNode(typeNode);
90373                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
90374                     // One of the individual is global object, return immediately
90375                     return serializedIndividual;
90376                 }
90377                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
90378                 // anything more complex and we will just default to Object
90379                 else if (serializedUnion) {
90380                     // Different types
90381                     if (!ts.isIdentifier(serializedUnion) ||
90382                         !ts.isIdentifier(serializedIndividual) ||
90383                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
90384                         return factory.createIdentifier("Object");
90385                     }
90386                 }
90387                 else {
90388                     // Initialize the union type
90389                     serializedUnion = serializedIndividual;
90390                 }
90391             }
90392             // If we were able to find common type, use it
90393             return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
90394         }
90395         /**
90396          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
90397          * decorator type metadata.
90398          *
90399          * @param node The type reference node.
90400          */
90401         function serializeTypeReferenceNode(node) {
90402             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
90403             switch (kind) {
90404                 case ts.TypeReferenceSerializationKind.Unknown:
90405                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
90406                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
90407                         return factory.createIdentifier("Object");
90408                     }
90409                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
90410                     var temp = factory.createTempVariable(hoistVariableDeclaration);
90411                     return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), 
90412                     /*questionToken*/ undefined, temp, 
90413                     /*colonToken*/ undefined, factory.createIdentifier("Object"));
90414                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
90415                     return serializeEntityNameAsExpression(node.typeName);
90416                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
90417                     return factory.createVoidZero();
90418                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
90419                     return getGlobalBigIntNameWithFallback();
90420                 case ts.TypeReferenceSerializationKind.BooleanType:
90421                     return factory.createIdentifier("Boolean");
90422                 case ts.TypeReferenceSerializationKind.NumberLikeType:
90423                     return factory.createIdentifier("Number");
90424                 case ts.TypeReferenceSerializationKind.StringLikeType:
90425                     return factory.createIdentifier("String");
90426                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
90427                     return factory.createIdentifier("Array");
90428                 case ts.TypeReferenceSerializationKind.ESSymbolType:
90429                     return languageVersion < 2 /* ES2015 */
90430                         ? getGlobalSymbolNameWithFallback()
90431                         : factory.createIdentifier("Symbol");
90432                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
90433                     return factory.createIdentifier("Function");
90434                 case ts.TypeReferenceSerializationKind.Promise:
90435                     return factory.createIdentifier("Promise");
90436                 case ts.TypeReferenceSerializationKind.ObjectType:
90437                     return factory.createIdentifier("Object");
90438                 default:
90439                     return ts.Debug.assertNever(kind);
90440             }
90441         }
90442         function createCheckedValue(left, right) {
90443             return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right);
90444         }
90445         /**
90446          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
90447          *
90448          * @param node The entity name to serialize.
90449          */
90450         function serializeEntityNameAsExpressionFallback(node) {
90451             if (node.kind === 79 /* Identifier */) {
90452                 // A -> typeof A !== undefined && A
90453                 var copied = serializeEntityNameAsExpression(node);
90454                 return createCheckedValue(copied, copied);
90455             }
90456             if (node.left.kind === 79 /* Identifier */) {
90457                 // A.B -> typeof A !== undefined && A.B
90458                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
90459             }
90460             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
90461             var left = serializeEntityNameAsExpressionFallback(node.left);
90462             var temp = factory.createTempVariable(hoistVariableDeclaration);
90463             return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right));
90464         }
90465         /**
90466          * Serializes an entity name as an expression for decorator type metadata.
90467          *
90468          * @param node The entity name to serialize.
90469          */
90470         function serializeEntityNameAsExpression(node) {
90471             switch (node.kind) {
90472                 case 79 /* Identifier */:
90473                     // Create a clone of the name with a new parent, and treat it as if it were
90474                     // a source tree node for the purposes of the checker.
90475                     var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent);
90476                     name.original = undefined;
90477                     ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
90478                     return name;
90479                 case 160 /* QualifiedName */:
90480                     return serializeQualifiedNameAsExpression(node);
90481             }
90482         }
90483         /**
90484          * Serializes an qualified name as an expression for decorator type metadata.
90485          *
90486          * @param node The qualified name to serialize.
90487          * @param useFallback A value indicating whether to use logical operators to test for the
90488          *                    qualified name at runtime.
90489          */
90490         function serializeQualifiedNameAsExpression(node) {
90491             return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
90492         }
90493         /**
90494          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
90495          * available.
90496          */
90497         function getGlobalSymbolNameWithFallback() {
90498             return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), 
90499             /*questionToken*/ undefined, factory.createIdentifier("Symbol"), 
90500             /*colonToken*/ undefined, factory.createIdentifier("Object"));
90501         }
90502         /**
90503          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
90504          * available.
90505          */
90506         function getGlobalBigIntNameWithFallback() {
90507             return languageVersion < 99 /* ESNext */
90508                 ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), 
90509                 /*questionToken*/ undefined, factory.createIdentifier("BigInt"), 
90510                 /*colonToken*/ undefined, factory.createIdentifier("Object"))
90511                 : factory.createIdentifier("BigInt");
90512         }
90513         /**
90514          * Gets an expression that represents a property name (for decorated properties or enums).
90515          * For a computed property, a name is generated for the node.
90516          *
90517          * @param member The member whose name should be converted into an expression.
90518          */
90519         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
90520             var name = member.name;
90521             if (ts.isPrivateIdentifier(name)) {
90522                 return factory.createIdentifier("");
90523             }
90524             else if (ts.isComputedPropertyName(name)) {
90525                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
90526                     ? factory.getGeneratedNameForNode(name)
90527                     : name.expression;
90528             }
90529             else if (ts.isIdentifier(name)) {
90530                 return factory.createStringLiteral(ts.idText(name));
90531             }
90532             else {
90533                 return factory.cloneNode(name);
90534             }
90535         }
90536         /**
90537          * Visits the property name of a class element, for use when emitting property
90538          * initializers. For a computed property on a node with decorators, a temporary
90539          * value is stored for later use.
90540          *
90541          * @param member The member whose name should be visited.
90542          */
90543         function visitPropertyNameOfClassElement(member) {
90544             var name = member.name;
90545             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
90546             // The names are used more than once when:
90547             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
90548             //   - the property has a decorator.
90549             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
90550                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
90551                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
90552                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
90553                     var generatedName = factory.getGeneratedNameForNode(name);
90554                     hoistVariableDeclaration(generatedName);
90555                     return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
90556                 }
90557             }
90558             return ts.visitNode(name, visitor, ts.isPropertyName);
90559         }
90560         /**
90561          * Transforms a HeritageClause with TypeScript syntax.
90562          *
90563          * This function will only be called when one of the following conditions are met:
90564          * - The node is a non-`extends` heritage clause that should be elided.
90565          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
90566          *
90567          * @param node The HeritageClause to transform.
90568          */
90569         function visitHeritageClause(node) {
90570             if (node.token === 117 /* ImplementsKeyword */) {
90571                 // implements clauses are elided
90572                 return undefined;
90573             }
90574             return ts.visitEachChild(node, visitor, context);
90575         }
90576         /**
90577          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
90578          *
90579          * This function will only be called when one of the following conditions are met:
90580          * - The node contains type arguments that should be elided.
90581          *
90582          * @param node The ExpressionWithTypeArguments to transform.
90583          */
90584         function visitExpressionWithTypeArguments(node) {
90585             return factory.updateExpressionWithTypeArguments(node, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression), 
90586             /*typeArguments*/ undefined);
90587         }
90588         /**
90589          * Determines whether to emit a function-like declaration. We should not emit the
90590          * declaration if it does not have a body.
90591          *
90592          * @param node The declaration node.
90593          */
90594         function shouldEmitFunctionLikeDeclaration(node) {
90595             return !ts.nodeIsMissing(node.body);
90596         }
90597         function visitPropertyDeclaration(node) {
90598             if (node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
90599                 return undefined;
90600             }
90601             var updated = factory.updatePropertyDeclaration(node, 
90602             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
90603             /*questionOrExclamationToken*/ undefined, 
90604             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
90605             if (updated !== node) {
90606                 // While we emit the source map for the node after skipping decorators and modifiers,
90607                 // we need to emit the comments for the original range.
90608                 ts.setCommentRange(updated, node);
90609                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
90610             }
90611             return updated;
90612         }
90613         function visitConstructor(node) {
90614             if (!shouldEmitFunctionLikeDeclaration(node)) {
90615                 return undefined;
90616             }
90617             return factory.updateConstructorDeclaration(node, 
90618             /*decorators*/ undefined, 
90619             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
90620         }
90621         function transformConstructorBody(body, constructor) {
90622             var parametersWithPropertyAssignments = constructor &&
90623                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
90624             if (!ts.some(parametersWithPropertyAssignments)) {
90625                 return ts.visitFunctionBody(body, visitor, context);
90626             }
90627             var statements = [];
90628             var indexOfFirstStatement = 0;
90629             resumeLexicalEnvironment();
90630             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
90631             // Add parameters with property assignments. Transforms this:
90632             //
90633             //  constructor (public x, public y) {
90634             //  }
90635             //
90636             // Into this:
90637             //
90638             //  constructor (x, y) {
90639             //      this.x = x;
90640             //      this.y = y;
90641             //  }
90642             //
90643             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
90644             // Add the existing statements, skipping the initial super call.
90645             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
90646             // End the lexical environment.
90647             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
90648             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true);
90649             ts.setTextRange(block, /*location*/ body);
90650             ts.setOriginalNode(block, body);
90651             return block;
90652         }
90653         /**
90654          * Transforms a parameter into a property assignment statement.
90655          *
90656          * @param node The parameter declaration.
90657          */
90658         function transformParameterWithPropertyAssignment(node) {
90659             var name = node.name;
90660             if (!ts.isIdentifier(name)) {
90661                 return undefined;
90662             }
90663             // TODO(rbuckton): Does this need to be parented?
90664             var propertyName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
90665             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
90666             // TODO(rbuckton): Does this need to be parented?
90667             var localName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
90668             ts.setEmitFlags(localName, 1536 /* NoComments */);
90669             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))));
90670         }
90671         function visitMethodDeclaration(node) {
90672             if (!shouldEmitFunctionLikeDeclaration(node)) {
90673                 return undefined;
90674             }
90675             var updated = factory.updateMethodDeclaration(node, 
90676             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
90677             /*questionToken*/ undefined, 
90678             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
90679             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
90680             if (updated !== node) {
90681                 // While we emit the source map for the node after skipping decorators and modifiers,
90682                 // we need to emit the comments for the original range.
90683                 ts.setCommentRange(updated, node);
90684                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
90685             }
90686             return updated;
90687         }
90688         /**
90689          * Determines whether to emit an accessor declaration. We should not emit the
90690          * declaration if it does not have a body and is abstract.
90691          *
90692          * @param node The declaration node.
90693          */
90694         function shouldEmitAccessorDeclaration(node) {
90695             return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* Abstract */));
90696         }
90697         function visitGetAccessor(node) {
90698             if (!shouldEmitAccessorDeclaration(node)) {
90699                 return undefined;
90700             }
90701             var updated = factory.updateGetAccessorDeclaration(node, 
90702             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
90703             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
90704             if (updated !== node) {
90705                 // While we emit the source map for the node after skipping decorators and modifiers,
90706                 // we need to emit the comments for the original range.
90707                 ts.setCommentRange(updated, node);
90708                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
90709             }
90710             return updated;
90711         }
90712         function visitSetAccessor(node) {
90713             if (!shouldEmitAccessorDeclaration(node)) {
90714                 return undefined;
90715             }
90716             var updated = factory.updateSetAccessorDeclaration(node, 
90717             /*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([]));
90718             if (updated !== node) {
90719                 // While we emit the source map for the node after skipping decorators and modifiers,
90720                 // we need to emit the comments for the original range.
90721                 ts.setCommentRange(updated, node);
90722                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
90723             }
90724             return updated;
90725         }
90726         function visitFunctionDeclaration(node) {
90727             if (!shouldEmitFunctionLikeDeclaration(node)) {
90728                 return factory.createNotEmittedStatement(node);
90729             }
90730             var updated = factory.updateFunctionDeclaration(node, 
90731             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
90732             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
90733             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
90734             if (isExportOfNamespace(node)) {
90735                 var statements = [updated];
90736                 addExportMemberAssignment(statements, node);
90737                 return statements;
90738             }
90739             return updated;
90740         }
90741         function visitFunctionExpression(node) {
90742             if (!shouldEmitFunctionLikeDeclaration(node)) {
90743                 return factory.createOmittedExpression();
90744             }
90745             var updated = factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
90746             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
90747             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
90748             return updated;
90749         }
90750         function visitArrowFunction(node) {
90751             var updated = factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
90752             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
90753             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
90754             return updated;
90755         }
90756         function visitParameter(node) {
90757             if (ts.parameterIsThisKeyword(node)) {
90758                 return undefined;
90759             }
90760             var updated = factory.updateParameterDeclaration(node, 
90761             /*decorators*/ undefined, 
90762             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
90763             /*questionToken*/ undefined, 
90764             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
90765             if (updated !== node) {
90766                 // While we emit the source map for the node after skipping decorators and modifiers,
90767                 // we need to emit the comments for the original range.
90768                 ts.setCommentRange(updated, node);
90769                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
90770                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
90771                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
90772             }
90773             return updated;
90774         }
90775         function visitVariableStatement(node) {
90776             if (isExportOfNamespace(node)) {
90777                 var variables = ts.getInitializedVariables(node.declarationList);
90778                 if (variables.length === 0) {
90779                     // elide statement if there are no initialized variables.
90780                     return undefined;
90781                 }
90782                 return ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
90783             }
90784             else {
90785                 return ts.visitEachChild(node, visitor, context);
90786             }
90787         }
90788         function transformInitializedVariable(node) {
90789             var name = node.name;
90790             if (ts.isBindingPattern(name)) {
90791                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
90792                 /*needsValue*/ false, createNamespaceExportExpression);
90793             }
90794             else {
90795                 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
90796                 /*location*/ node);
90797             }
90798         }
90799         function visitVariableDeclaration(node) {
90800             return factory.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
90801             /*exclamationToken*/ undefined, 
90802             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
90803         }
90804         function visitParenthesizedExpression(node) {
90805             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
90806             if (ts.isAssertionExpression(innerExpression)) {
90807                 // Make sure we consider all nested cast expressions, e.g.:
90808                 // (<any><number><any>-A).x;
90809                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
90810                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
90811                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
90812                 // the parentheses, however, could cause change in the semantics of the generated
90813                 // code if the casted expression has a lower precedence than the rest of the
90814                 // expression.
90815                 //
90816                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
90817                 // preserve the position information of the original expression.
90818                 //
90819                 // Due to the auto-parenthesization rules used by the visitor and factory functions
90820                 // we can safely elide the parentheses here, as a new synthetic
90821                 // ParenthesizedExpression will be inserted if we remove parentheses too
90822                 // aggressively.
90823                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
90824                 // correctly for return and throw, we must keep the parenthesis
90825                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
90826                     return factory.updateParenthesizedExpression(node, expression);
90827                 }
90828                 return factory.createPartiallyEmittedExpression(expression, node);
90829             }
90830             return ts.visitEachChild(node, visitor, context);
90831         }
90832         function visitAssertionExpression(node) {
90833             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
90834             return factory.createPartiallyEmittedExpression(expression, node);
90835         }
90836         function visitNonNullExpression(node) {
90837             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
90838             return factory.createPartiallyEmittedExpression(expression, node);
90839         }
90840         function visitCallExpression(node) {
90841             return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
90842             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
90843         }
90844         function visitNewExpression(node) {
90845             return factory.updateNewExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
90846             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
90847         }
90848         function visitTaggedTemplateExpression(node) {
90849             return factory.updateTaggedTemplateExpression(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
90850             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
90851         }
90852         function visitJsxSelfClosingElement(node) {
90853             return factory.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
90854             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
90855         }
90856         function visitJsxJsxOpeningElement(node) {
90857             return factory.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
90858             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
90859         }
90860         /**
90861          * Determines whether to emit an enum declaration.
90862          *
90863          * @param node The enum declaration node.
90864          */
90865         function shouldEmitEnumDeclaration(node) {
90866             return !ts.isEnumConst(node)
90867                 || ts.shouldPreserveConstEnums(compilerOptions);
90868         }
90869         /**
90870          * Visits an enum declaration.
90871          *
90872          * This function will be called any time a TypeScript enum is encountered.
90873          *
90874          * @param node The enum declaration node.
90875          */
90876         function visitEnumDeclaration(node) {
90877             if (!shouldEmitEnumDeclaration(node)) {
90878                 return factory.createNotEmittedStatement(node);
90879             }
90880             var statements = [];
90881             // We request to be advised when the printer is about to print this node. This allows
90882             // us to set up the correct state for later substitutions.
90883             var emitFlags = 2 /* AdviseOnEmitNode */;
90884             // If needed, we should emit a variable declaration for the enum. If we emit
90885             // a leading variable declaration, we should not emit leading comments for the
90886             // enum body.
90887             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
90888             if (varAdded) {
90889                 // We should still emit the comments if we are emitting a system module.
90890                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
90891                     emitFlags |= 512 /* NoLeadingComments */;
90892                 }
90893             }
90894             // `parameterName` is the declaration name used inside of the enum.
90895             var parameterName = getNamespaceParameterName(node);
90896             // `containerName` is the expression used inside of the enum for assignments.
90897             var containerName = getNamespaceContainerName(node);
90898             // `exportName` is the expression used within this node's container for any exported references.
90899             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
90900                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
90901                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
90902             //  x || (x = {})
90903             //  exports.x || (exports.x = {})
90904             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
90905             if (hasNamespaceQualifiedExportName(node)) {
90906                 // `localName` is the expression used within this node's containing scope for any local references.
90907                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
90908                 //  x = (exports.x || (exports.x = {}))
90909                 moduleArg = factory.createAssignment(localName, moduleArg);
90910             }
90911             //  (function (x) {
90912             //      x[x["y"] = 0] = "y";
90913             //      ...
90914             //  })(x || (x = {}));
90915             var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
90916             /*modifiers*/ undefined, 
90917             /*asteriskToken*/ undefined, 
90918             /*name*/ undefined, 
90919             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90920             /*type*/ undefined, transformEnumBody(node, containerName)), 
90921             /*typeArguments*/ undefined, [moduleArg]));
90922             ts.setOriginalNode(enumStatement, node);
90923             if (varAdded) {
90924                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
90925                 ts.setSyntheticLeadingComments(enumStatement, undefined);
90926                 ts.setSyntheticTrailingComments(enumStatement, undefined);
90927             }
90928             ts.setTextRange(enumStatement, node);
90929             ts.addEmitFlags(enumStatement, emitFlags);
90930             statements.push(enumStatement);
90931             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
90932             // the end of the declaration.
90933             statements.push(factory.createEndOfDeclarationMarker(node));
90934             return statements;
90935         }
90936         /**
90937          * Transforms the body of an enum declaration.
90938          *
90939          * @param node The enum declaration node.
90940          */
90941         function transformEnumBody(node, localName) {
90942             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
90943             currentNamespaceContainerName = localName;
90944             var statements = [];
90945             startLexicalEnvironment();
90946             var members = ts.map(node.members, transformEnumMember);
90947             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90948             ts.addRange(statements, members);
90949             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
90950             return factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), 
90951             /*multiLine*/ true);
90952         }
90953         /**
90954          * Transforms an enum member into a statement.
90955          *
90956          * @param member The enum member node.
90957          */
90958         function transformEnumMember(member) {
90959             // enums don't support computed properties
90960             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
90961             // old emitter always generate 'expression' part of the name as-is.
90962             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
90963             var valueExpression = transformEnumMemberDeclarationValue(member);
90964             var innerAssignment = factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression);
90965             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
90966                 innerAssignment :
90967                 factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name);
90968             return ts.setTextRange(factory.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
90969         }
90970         /**
90971          * Transforms the value of an enum member.
90972          *
90973          * @param member The enum member node.
90974          */
90975         function transformEnumMemberDeclarationValue(member) {
90976             var value = resolver.getConstantValue(member);
90977             if (value !== undefined) {
90978                 return typeof value === "string" ? factory.createStringLiteral(value) : factory.createNumericLiteral(value);
90979             }
90980             else {
90981                 enableSubstitutionForNonQualifiedEnumMembers();
90982                 if (member.initializer) {
90983                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
90984                 }
90985                 else {
90986                     return factory.createVoidZero();
90987                 }
90988             }
90989         }
90990         /**
90991          * Determines whether to elide a module declaration.
90992          *
90993          * @param node The module declaration node.
90994          */
90995         function shouldEmitModuleDeclaration(nodeIn) {
90996             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
90997             if (!node) {
90998                 // If we can't find a parse tree node, assume the node is instantiated.
90999                 return true;
91000             }
91001             return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions));
91002         }
91003         /**
91004          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
91005          * or `exports.x`).
91006          */
91007         function hasNamespaceQualifiedExportName(node) {
91008             return isExportOfNamespace(node)
91009                 || (isExternalModuleExport(node)
91010                     && moduleKind !== ts.ModuleKind.ES2015
91011                     && moduleKind !== ts.ModuleKind.ES2020
91012                     && moduleKind !== ts.ModuleKind.ES2022
91013                     && moduleKind !== ts.ModuleKind.ESNext
91014                     && moduleKind !== ts.ModuleKind.System);
91015         }
91016         /**
91017          * Records that a declaration was emitted in the current scope, if it was the first
91018          * declaration for the provided symbol.
91019          */
91020         function recordEmittedDeclarationInScope(node) {
91021             if (!currentScopeFirstDeclarationsOfName) {
91022                 currentScopeFirstDeclarationsOfName = new ts.Map();
91023             }
91024             var name = declaredNameInScope(node);
91025             if (!currentScopeFirstDeclarationsOfName.has(name)) {
91026                 currentScopeFirstDeclarationsOfName.set(name, node);
91027             }
91028         }
91029         /**
91030          * Determines whether a declaration is the first declaration with
91031          * the same name emitted in the current scope.
91032          */
91033         function isFirstEmittedDeclarationInScope(node) {
91034             if (currentScopeFirstDeclarationsOfName) {
91035                 var name = declaredNameInScope(node);
91036                 return currentScopeFirstDeclarationsOfName.get(name) === node;
91037             }
91038             return true;
91039         }
91040         function declaredNameInScope(node) {
91041             ts.Debug.assertNode(node.name, ts.isIdentifier);
91042             return node.name.escapedText;
91043         }
91044         /**
91045          * Adds a leading VariableStatement for a enum or module declaration.
91046          */
91047         function addVarForEnumOrModuleDeclaration(statements, node) {
91048             // Emit a variable statement for the module. We emit top-level enums as a `var`
91049             // declaration to avoid static errors in global scripts scripts due to redeclaration.
91050             // enums in any other scope are emitted as a `let` declaration.
91051             var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
91052                 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
91053             ], currentLexicalScope.kind === 303 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
91054             ts.setOriginalNode(statement, node);
91055             recordEmittedDeclarationInScope(node);
91056             if (isFirstEmittedDeclarationInScope(node)) {
91057                 // Adjust the source map emit to match the old emitter.
91058                 if (node.kind === 259 /* EnumDeclaration */) {
91059                     ts.setSourceMapRange(statement.declarationList, node);
91060                 }
91061                 else {
91062                     ts.setSourceMapRange(statement, node);
91063                 }
91064                 // Trailing comments for module declaration should be emitted after the function closure
91065                 // instead of the variable statement:
91066                 //
91067                 //     /** Module comment*/
91068                 //     module m1 {
91069                 //         function foo4Export() {
91070                 //         }
91071                 //     } // trailing comment module
91072                 //
91073                 // Should emit:
91074                 //
91075                 //     /** Module comment*/
91076                 //     var m1;
91077                 //     (function (m1) {
91078                 //         function foo4Export() {
91079                 //         }
91080                 //     })(m1 || (m1 = {})); // trailing comment module
91081                 //
91082                 ts.setCommentRange(statement, node);
91083                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
91084                 statements.push(statement);
91085                 return true;
91086             }
91087             else {
91088                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91089                 // declaration we do not emit a leading variable declaration. To preserve the
91090                 // begin/end semantics of the declararation and to properly handle exports
91091                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
91092                 var mergeMarker = factory.createMergeDeclarationMarker(statement);
91093                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
91094                 statements.push(mergeMarker);
91095                 return false;
91096             }
91097         }
91098         /**
91099          * Visits a module declaration node.
91100          *
91101          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
91102          *
91103          * @param node The module declaration node.
91104          */
91105         function visitModuleDeclaration(node) {
91106             if (!shouldEmitModuleDeclaration(node)) {
91107                 return factory.createNotEmittedStatement(node);
91108             }
91109             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
91110             enableSubstitutionForNamespaceExports();
91111             var statements = [];
91112             // We request to be advised when the printer is about to print this node. This allows
91113             // us to set up the correct state for later substitutions.
91114             var emitFlags = 2 /* AdviseOnEmitNode */;
91115             // If needed, we should emit a variable declaration for the module. If we emit
91116             // a leading variable declaration, we should not emit leading comments for the
91117             // module body.
91118             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
91119             if (varAdded) {
91120                 // We should still emit the comments if we are emitting a system module.
91121                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
91122                     emitFlags |= 512 /* NoLeadingComments */;
91123                 }
91124             }
91125             // `parameterName` is the declaration name used inside of the namespace.
91126             var parameterName = getNamespaceParameterName(node);
91127             // `containerName` is the expression used inside of the namespace for exports.
91128             var containerName = getNamespaceContainerName(node);
91129             // `exportName` is the expression used within this node's container for any exported references.
91130             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
91131                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
91132                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
91133             //  x || (x = {})
91134             //  exports.x || (exports.x = {})
91135             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
91136             if (hasNamespaceQualifiedExportName(node)) {
91137                 // `localName` is the expression used within this node's containing scope for any local references.
91138                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
91139                 //  x = (exports.x || (exports.x = {}))
91140                 moduleArg = factory.createAssignment(localName, moduleArg);
91141             }
91142             //  (function (x_1) {
91143             //      x_1.y = ...;
91144             //  })(x || (x = {}));
91145             var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
91146             /*modifiers*/ undefined, 
91147             /*asteriskToken*/ undefined, 
91148             /*name*/ undefined, 
91149             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
91150             /*type*/ undefined, transformModuleBody(node, containerName)), 
91151             /*typeArguments*/ undefined, [moduleArg]));
91152             ts.setOriginalNode(moduleStatement, node);
91153             if (varAdded) {
91154                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
91155                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
91156                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
91157             }
91158             ts.setTextRange(moduleStatement, node);
91159             ts.addEmitFlags(moduleStatement, emitFlags);
91160             statements.push(moduleStatement);
91161             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
91162             // the end of the declaration.
91163             statements.push(factory.createEndOfDeclarationMarker(node));
91164             return statements;
91165         }
91166         /**
91167          * Transforms the body of a module declaration.
91168          *
91169          * @param node The module declaration node.
91170          */
91171         function transformModuleBody(node, namespaceLocalName) {
91172             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
91173             var savedCurrentNamespace = currentNamespace;
91174             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
91175             currentNamespaceContainerName = namespaceLocalName;
91176             currentNamespace = node;
91177             currentScopeFirstDeclarationsOfName = undefined;
91178             var statements = [];
91179             startLexicalEnvironment();
91180             var statementsLocation;
91181             var blockLocation;
91182             if (node.body) {
91183                 if (node.body.kind === 261 /* ModuleBlock */) {
91184                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
91185                     statementsLocation = node.body.statements;
91186                     blockLocation = node.body;
91187                 }
91188                 else {
91189                     var result = visitModuleDeclaration(node.body);
91190                     if (result) {
91191                         if (ts.isArray(result)) {
91192                             ts.addRange(statements, result);
91193                         }
91194                         else {
91195                             statements.push(result);
91196                         }
91197                     }
91198                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
91199                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
91200                 }
91201             }
91202             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
91203             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
91204             currentNamespace = savedCurrentNamespace;
91205             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
91206             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
91207             /*location*/ statementsLocation), 
91208             /*multiLine*/ true);
91209             ts.setTextRange(block, blockLocation);
91210             // namespace hello.hi.world {
91211             //      function foo() {}
91212             //
91213             //      // TODO, blah
91214             // }
91215             //
91216             // should be emitted as
91217             //
91218             // var hello;
91219             // (function (hello) {
91220             //     var hi;
91221             //     (function (hi) {
91222             //         var world;
91223             //         (function (world) {
91224             //             function foo() { }
91225             //             // TODO, blah
91226             //         })(world = hi.world || (hi.world = {}));
91227             //     })(hi = hello.hi || (hello.hi = {}));
91228             // })(hello || (hello = {}));
91229             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
91230             if (!node.body || node.body.kind !== 261 /* ModuleBlock */) {
91231                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
91232             }
91233             return block;
91234         }
91235         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
91236             if (moduleDeclaration.body.kind === 260 /* ModuleDeclaration */) {
91237                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
91238                 return recursiveInnerModule || moduleDeclaration.body;
91239             }
91240         }
91241         /**
91242          * Visits an import declaration, eliding it if it is type-only or if it has an import clause that may be elided.
91243          *
91244          * @param node The import declaration node.
91245          */
91246         function visitImportDeclaration(node) {
91247             if (!node.importClause) {
91248                 // Do not elide a side-effect only import declaration.
91249                 //  import "foo";
91250                 return node;
91251             }
91252             if (node.importClause.isTypeOnly) {
91253                 // Always elide type-only imports
91254                 return undefined;
91255             }
91256             // Elide the declaration if the import clause was elided.
91257             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
91258             return importClause ||
91259                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
91260                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
91261                 ? factory.updateImportDeclaration(node, 
91262                 /*decorators*/ undefined, 
91263                 /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause)
91264                 : undefined;
91265         }
91266         /**
91267          * Visits an import clause, eliding it if its `name` and `namedBindings` may both be elided.
91268          *
91269          * @param node The import clause node.
91270          */
91271         function visitImportClause(node) {
91272             ts.Debug.assert(!node.isTypeOnly);
91273             // Elide the import clause if we elide both its name and its named bindings.
91274             var name = shouldEmitAliasDeclaration(node) ? node.name : undefined;
91275             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
91276             return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined;
91277         }
91278         /**
91279          * Visits named import bindings, eliding them if their targets, their references, and the compilation settings allow.
91280          *
91281          * @param node The named import bindings node.
91282          */
91283         function visitNamedImportBindings(node) {
91284             if (node.kind === 267 /* NamespaceImport */) {
91285                 // Elide a namespace import if it is not referenced.
91286                 return shouldEmitAliasDeclaration(node) ? node : undefined;
91287             }
91288             else {
91289                 // Elide named imports if all of its import specifiers are elided and settings allow.
91290                 var allowEmpty = compilerOptions.preserveValueImports && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
91291                     compilerOptions.importsNotUsedAsValues === 2 /* Error */);
91292                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
91293                 return allowEmpty || ts.some(elements) ? factory.updateNamedImports(node, elements) : undefined;
91294             }
91295         }
91296         /**
91297          * Visits an import specifier, eliding it if its target, its references, and the compilation settings allow.
91298          *
91299          * @param node The import specifier node.
91300          */
91301         function visitImportSpecifier(node) {
91302             return !node.isTypeOnly && shouldEmitAliasDeclaration(node) ? node : undefined;
91303         }
91304         /**
91305          * Visits an export assignment, eliding it if it does not contain a clause that resolves
91306          * to a value.
91307          *
91308          * @param node The export assignment node.
91309          */
91310         function visitExportAssignment(node) {
91311             // Elide the export assignment if it does not reference a value.
91312             return resolver.isValueAliasDeclaration(node)
91313                 ? ts.visitEachChild(node, visitor, context)
91314                 : undefined;
91315         }
91316         /**
91317          * Visits an export declaration, eliding it if it does not contain a clause that resolves to a value.
91318          *
91319          * @param node The export declaration node.
91320          */
91321         function visitExportDeclaration(node) {
91322             if (node.isTypeOnly) {
91323                 return undefined;
91324             }
91325             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
91326                 // never elide `export <whatever> from <whereever>` declarations -
91327                 // they should be kept for sideffects/untyped exports, even when the
91328                 // type checker doesn't know about any exports
91329                 return node;
91330             }
91331             // Elide the export declaration if all of its named exports are elided.
91332             var allowEmpty = !!node.moduleSpecifier && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
91333                 compilerOptions.importsNotUsedAsValues === 2 /* Error */);
91334             var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings);
91335             return exportClause
91336                 ? factory.updateExportDeclaration(node, 
91337                 /*decorators*/ undefined, 
91338                 /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause)
91339                 : undefined;
91340         }
91341         /**
91342          * Visits named exports, eliding it if it does not contain an export specifier that
91343          * resolves to a value.
91344          *
91345          * @param node The named exports node.
91346          */
91347         function visitNamedExports(node, allowEmpty) {
91348             // Elide the named exports if all of its export specifiers were elided.
91349             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
91350             return allowEmpty || ts.some(elements) ? factory.updateNamedExports(node, elements) : undefined;
91351         }
91352         function visitNamespaceExports(node) {
91353             return factory.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
91354         }
91355         function visitNamedExportBindings(node, allowEmpty) {
91356             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node, allowEmpty);
91357         }
91358         /**
91359          * Visits an export specifier, eliding it if it does not resolve to a value.
91360          *
91361          * @param node The export specifier node.
91362          */
91363         function visitExportSpecifier(node) {
91364             // Elide an export specifier if it does not reference a value.
91365             return !node.isTypeOnly && resolver.isValueAliasDeclaration(node) ? node : undefined;
91366         }
91367         /**
91368          * Determines whether to emit an import equals declaration.
91369          *
91370          * @param node The import equals declaration node.
91371          */
91372         function shouldEmitImportEqualsDeclaration(node) {
91373             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
91374             // - current file is not external module
91375             // - import declaration is top level and target is value imported by entity name
91376             return shouldEmitAliasDeclaration(node)
91377                 || (!ts.isExternalModule(currentSourceFile)
91378                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
91379         }
91380         /**
91381          * Visits an import equals declaration.
91382          *
91383          * @param node The import equals declaration node.
91384          */
91385         function visitImportEqualsDeclaration(node) {
91386             // Always elide type-only imports
91387             if (node.isTypeOnly) {
91388                 return undefined;
91389             }
91390             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
91391                 var isReferenced = shouldEmitAliasDeclaration(node);
91392                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
91393                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
91394                     return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(
91395                     /*decorators*/ undefined, 
91396                     /*modifiers*/ undefined, 
91397                     /*importClause*/ undefined, node.moduleReference.expression, 
91398                     /*assertClause*/ undefined), node), node);
91399                 }
91400                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
91401             }
91402             if (!shouldEmitImportEqualsDeclaration(node)) {
91403                 return undefined;
91404             }
91405             var moduleReference = ts.createExpressionFromEntityName(factory, node.moduleReference);
91406             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
91407             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
91408                 //  export var ${name} = ${moduleReference};
91409                 //  var ${name} = ${moduleReference};
91410                 return ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
91411                     ts.setOriginalNode(factory.createVariableDeclaration(node.name, 
91412                     /*exclamationToken*/ undefined, 
91413                     /*type*/ undefined, moduleReference), node)
91414                 ])), node), node);
91415             }
91416             else {
91417                 // exports.${name} = ${moduleReference};
91418                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
91419             }
91420         }
91421         /**
91422          * Gets a value indicating whether the node is exported from a namespace.
91423          *
91424          * @param node The node to test.
91425          */
91426         function isExportOfNamespace(node) {
91427             return currentNamespace !== undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
91428         }
91429         /**
91430          * Gets a value indicating whether the node is exported from an external module.
91431          *
91432          * @param node The node to test.
91433          */
91434         function isExternalModuleExport(node) {
91435             return currentNamespace === undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
91436         }
91437         /**
91438          * Gets a value indicating whether the node is a named export from an external module.
91439          *
91440          * @param node The node to test.
91441          */
91442         function isNamedExternalModuleExport(node) {
91443             return isExternalModuleExport(node)
91444                 && !ts.hasSyntacticModifier(node, 512 /* Default */);
91445         }
91446         /**
91447          * Gets a value indicating whether the node is the default export of an external module.
91448          *
91449          * @param node The node to test.
91450          */
91451         function isDefaultExternalModuleExport(node) {
91452             return isExternalModuleExport(node)
91453                 && ts.hasSyntacticModifier(node, 512 /* Default */);
91454         }
91455         /**
91456          * Creates a statement for the provided expression. This is used in calls to `map`.
91457          */
91458         function expressionToStatement(expression) {
91459             return factory.createExpressionStatement(expression);
91460         }
91461         function addExportMemberAssignment(statements, node) {
91462             var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node));
91463             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
91464             var statement = factory.createExpressionStatement(expression);
91465             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
91466             statements.push(statement);
91467         }
91468         function createNamespaceExport(exportName, exportValue, location) {
91469             return ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
91470         }
91471         function createNamespaceExportExpression(exportName, exportValue, location) {
91472             return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
91473         }
91474         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
91475             return factory.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
91476         }
91477         /**
91478          * Gets the declaration name used inside of a namespace or enum.
91479          */
91480         function getNamespaceParameterName(node) {
91481             var name = factory.getGeneratedNameForNode(node);
91482             ts.setSourceMapRange(name, node.name);
91483             return name;
91484         }
91485         /**
91486          * Gets the expression used to refer to a namespace or enum within the body
91487          * of its declaration.
91488          */
91489         function getNamespaceContainerName(node) {
91490             return factory.getGeneratedNameForNode(node);
91491         }
91492         /**
91493          * Gets a local alias for a class declaration if it is a decorated class with an internal
91494          * reference to the static side of the class. This is necessary to avoid issues with
91495          * double-binding semantics for the class name.
91496          */
91497         function getClassAliasIfNeeded(node) {
91498             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
91499                 enableSubstitutionForClassAliases();
91500                 var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
91501                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
91502                 hoistVariableDeclaration(classAlias);
91503                 return classAlias;
91504             }
91505         }
91506         function getClassPrototype(node) {
91507             return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype");
91508         }
91509         function getClassMemberPrefix(node, member) {
91510             return ts.isStatic(member)
91511                 ? factory.getDeclarationName(node)
91512                 : getClassPrototype(node);
91513         }
91514         function enableSubstitutionForNonQualifiedEnumMembers() {
91515             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
91516                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
91517                 context.enableSubstitution(79 /* Identifier */);
91518             }
91519         }
91520         function enableSubstitutionForClassAliases() {
91521             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
91522                 enabledSubstitutions |= 1 /* ClassAliases */;
91523                 // We need to enable substitutions for identifiers. This allows us to
91524                 // substitute class names inside of a class declaration.
91525                 context.enableSubstitution(79 /* Identifier */);
91526                 // Keep track of class aliases.
91527                 classAliases = [];
91528             }
91529         }
91530         function enableSubstitutionForNamespaceExports() {
91531             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
91532                 enabledSubstitutions |= 2 /* NamespaceExports */;
91533                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
91534                 // substitute the names of exported members of a namespace.
91535                 context.enableSubstitution(79 /* Identifier */);
91536                 context.enableSubstitution(295 /* ShorthandPropertyAssignment */);
91537                 // We need to be notified when entering and exiting namespaces.
91538                 context.enableEmitNotification(260 /* ModuleDeclaration */);
91539             }
91540         }
91541         function isTransformedModuleDeclaration(node) {
91542             return ts.getOriginalNode(node).kind === 260 /* ModuleDeclaration */;
91543         }
91544         function isTransformedEnumDeclaration(node) {
91545             return ts.getOriginalNode(node).kind === 259 /* EnumDeclaration */;
91546         }
91547         /**
91548          * Hook for node emit.
91549          *
91550          * @param hint A hint as to the intended usage of the node.
91551          * @param node The node to emit.
91552          * @param emit A callback used to emit the node in the printer.
91553          */
91554         function onEmitNode(hint, node, emitCallback) {
91555             var savedApplicableSubstitutions = applicableSubstitutions;
91556             var savedCurrentSourceFile = currentSourceFile;
91557             if (ts.isSourceFile(node)) {
91558                 currentSourceFile = node;
91559             }
91560             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
91561                 applicableSubstitutions |= 2 /* NamespaceExports */;
91562             }
91563             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
91564                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
91565             }
91566             previousOnEmitNode(hint, node, emitCallback);
91567             applicableSubstitutions = savedApplicableSubstitutions;
91568             currentSourceFile = savedCurrentSourceFile;
91569         }
91570         /**
91571          * Hooks node substitutions.
91572          *
91573          * @param hint A hint as to the intended usage of the node.
91574          * @param node The node to substitute.
91575          */
91576         function onSubstituteNode(hint, node) {
91577             node = previousOnSubstituteNode(hint, node);
91578             if (hint === 1 /* Expression */) {
91579                 return substituteExpression(node);
91580             }
91581             else if (ts.isShorthandPropertyAssignment(node)) {
91582                 return substituteShorthandPropertyAssignment(node);
91583             }
91584             return node;
91585         }
91586         function substituteShorthandPropertyAssignment(node) {
91587             if (enabledSubstitutions & 2 /* NamespaceExports */) {
91588                 var name = node.name;
91589                 var exportedName = trySubstituteNamespaceExportedName(name);
91590                 if (exportedName) {
91591                     // A shorthand property with an assignment initializer is probably part of a
91592                     // destructuring assignment
91593                     if (node.objectAssignmentInitializer) {
91594                         var initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer);
91595                         return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
91596                     }
91597                     return ts.setTextRange(factory.createPropertyAssignment(name, exportedName), node);
91598                 }
91599             }
91600             return node;
91601         }
91602         function substituteExpression(node) {
91603             switch (node.kind) {
91604                 case 79 /* Identifier */:
91605                     return substituteExpressionIdentifier(node);
91606                 case 205 /* PropertyAccessExpression */:
91607                     return substitutePropertyAccessExpression(node);
91608                 case 206 /* ElementAccessExpression */:
91609                     return substituteElementAccessExpression(node);
91610             }
91611             return node;
91612         }
91613         function substituteExpressionIdentifier(node) {
91614             return trySubstituteClassAlias(node)
91615                 || trySubstituteNamespaceExportedName(node)
91616                 || node;
91617         }
91618         function trySubstituteClassAlias(node) {
91619             if (enabledSubstitutions & 1 /* ClassAliases */) {
91620                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
91621                     // Due to the emit for class decorators, any reference to the class from inside of the class body
91622                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
91623                     // behavior of class names in ES6.
91624                     // Also, when emitting statics for class expressions, we must substitute a class alias for
91625                     // constructor references in static property initializers.
91626                     var declaration = resolver.getReferencedValueDeclaration(node);
91627                     if (declaration) {
91628                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
91629                         if (classAlias) {
91630                             var clone_2 = factory.cloneNode(classAlias);
91631                             ts.setSourceMapRange(clone_2, node);
91632                             ts.setCommentRange(clone_2, node);
91633                             return clone_2;
91634                         }
91635                     }
91636                 }
91637             }
91638             return undefined;
91639         }
91640         function trySubstituteNamespaceExportedName(node) {
91641             // If this is explicitly a local name, do not substitute.
91642             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91643                 // If we are nested within a namespace declaration, we may need to qualifiy
91644                 // an identifier that is exported from a merged namespace.
91645                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
91646                 if (container && container.kind !== 303 /* SourceFile */) {
91647                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 260 /* ModuleDeclaration */) ||
91648                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 259 /* EnumDeclaration */);
91649                     if (substitute) {
91650                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), 
91651                         /*location*/ node);
91652                     }
91653                 }
91654             }
91655             return undefined;
91656         }
91657         function substitutePropertyAccessExpression(node) {
91658             return substituteConstantValue(node);
91659         }
91660         function substituteElementAccessExpression(node) {
91661             return substituteConstantValue(node);
91662         }
91663         function substituteConstantValue(node) {
91664             var constantValue = tryGetConstEnumValue(node);
91665             if (constantValue !== undefined) {
91666                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
91667                 ts.setConstantValue(node, constantValue);
91668                 var substitute = typeof constantValue === "string" ? factory.createStringLiteral(constantValue) : factory.createNumericLiteral(constantValue);
91669                 if (!compilerOptions.removeComments) {
91670                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
91671                     var propertyName = ts.isPropertyAccessExpression(originalNode)
91672                         ? ts.declarationNameToString(originalNode.name)
91673                         : ts.getTextOfNode(originalNode.argumentExpression);
91674                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " ".concat(propertyName, " "));
91675                 }
91676                 return substitute;
91677             }
91678             return node;
91679         }
91680         function tryGetConstEnumValue(node) {
91681             if (compilerOptions.isolatedModules) {
91682                 return undefined;
91683             }
91684             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
91685         }
91686         function shouldEmitAliasDeclaration(node) {
91687             return compilerOptions.preserveValueImports
91688                 ? resolver.isValueAliasDeclaration(node)
91689                 : resolver.isReferencedAliasDeclaration(node);
91690         }
91691     }
91692     ts.transformTypeScript = transformTypeScript;
91693 })(ts || (ts = {}));
91694 /*@internal*/
91695 var ts;
91696 (function (ts) {
91697     var ClassPropertySubstitutionFlags;
91698     (function (ClassPropertySubstitutionFlags) {
91699         /**
91700          * Enables substitutions for class expressions with static fields
91701          * which have initializers that reference the class name.
91702          */
91703         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
91704         /**
91705          * Enables substitutions for class expressions with static fields
91706          * which have initializers that reference the 'this' or 'super'.
91707          */
91708         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassStaticThisOrSuperReference"] = 2] = "ClassStaticThisOrSuperReference";
91709     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
91710     var PrivateIdentifierKind;
91711     (function (PrivateIdentifierKind) {
91712         PrivateIdentifierKind["Field"] = "f";
91713         PrivateIdentifierKind["Method"] = "m";
91714         PrivateIdentifierKind["Accessor"] = "a";
91715     })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {}));
91716     var ClassFacts;
91717     (function (ClassFacts) {
91718         ClassFacts[ClassFacts["None"] = 0] = "None";
91719         ClassFacts[ClassFacts["ClassWasDecorated"] = 1] = "ClassWasDecorated";
91720         ClassFacts[ClassFacts["NeedsClassConstructorReference"] = 2] = "NeedsClassConstructorReference";
91721         ClassFacts[ClassFacts["NeedsClassSuperReference"] = 4] = "NeedsClassSuperReference";
91722         ClassFacts[ClassFacts["NeedsSubstitutionForThisInClassStaticField"] = 8] = "NeedsSubstitutionForThisInClassStaticField";
91723     })(ClassFacts || (ClassFacts = {}));
91724     /**
91725      * Transforms ECMAScript Class Syntax.
91726      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
91727      * For now, this transforms public field declarations using TypeScript class semantics,
91728      * where declarations are elided and initializers are transformed as assignments in the constructor.
91729      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
91730      */
91731     function transformClassFields(context) {
91732         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable;
91733         var resolver = context.getEmitResolver();
91734         var compilerOptions = context.getCompilerOptions();
91735         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
91736         var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions);
91737         var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 99 /* ESNext */;
91738         // We don't need to transform `super` property access when targeting ES5, ES3 because
91739         // the es2015 transformation handles those.
91740         var shouldTransformSuperInStaticInitializers = (languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields) && languageVersion >= 2 /* ES2015 */;
91741         var shouldTransformThisInStaticInitializers = languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields;
91742         var previousOnSubstituteNode = context.onSubstituteNode;
91743         context.onSubstituteNode = onSubstituteNode;
91744         var previousOnEmitNode = context.onEmitNode;
91745         context.onEmitNode = onEmitNode;
91746         var enabledSubstitutions;
91747         var classAliases;
91748         /**
91749          * Tracks what computed name expressions originating from elided names must be inlined
91750          * at the next execution site, in document order
91751          */
91752         var pendingExpressions;
91753         /**
91754          * Tracks what computed name expression statements and static property initializers must be
91755          * emitted at the next execution site, in document order (for decorated classes).
91756          */
91757         var pendingStatements;
91758         var classLexicalEnvironmentStack = [];
91759         var classLexicalEnvironmentMap = new ts.Map();
91760         var currentClassLexicalEnvironment;
91761         var currentComputedPropertyNameClassLexicalEnvironment;
91762         var currentStaticPropertyDeclarationOrStaticBlock;
91763         return ts.chainBundle(context, transformSourceFile);
91764         function transformSourceFile(node) {
91765             var options = context.getCompilerOptions();
91766             if (node.isDeclarationFile
91767                 || useDefineForClassFields && ts.getEmitScriptTarget(options) === 99 /* ESNext */) {
91768                 return node;
91769             }
91770             var visited = ts.visitEachChild(node, visitor, context);
91771             ts.addEmitHelpers(visited, context.readEmitHelpers());
91772             return visited;
91773         }
91774         function visitorWorker(node, valueIsDiscarded) {
91775             if (node.transformFlags & 8388608 /* ContainsClassFields */) {
91776                 switch (node.kind) {
91777                     case 225 /* ClassExpression */:
91778                     case 256 /* ClassDeclaration */:
91779                         return visitClassLike(node);
91780                     case 166 /* PropertyDeclaration */:
91781                         return visitPropertyDeclaration(node);
91782                     case 236 /* VariableStatement */:
91783                         return visitVariableStatement(node);
91784                     case 80 /* PrivateIdentifier */:
91785                         return visitPrivateIdentifier(node);
91786                     case 169 /* ClassStaticBlockDeclaration */:
91787                         return visitClassStaticBlockDeclaration(node);
91788                 }
91789             }
91790             if (node.transformFlags & 8388608 /* ContainsClassFields */ ||
91791                 node.transformFlags & 33554432 /* ContainsLexicalSuper */ &&
91792                     shouldTransformSuperInStaticInitializers &&
91793                     currentStaticPropertyDeclarationOrStaticBlock &&
91794                     currentClassLexicalEnvironment) {
91795                 switch (node.kind) {
91796                     case 218 /* PrefixUnaryExpression */:
91797                     case 219 /* PostfixUnaryExpression */:
91798                         return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded);
91799                     case 220 /* BinaryExpression */:
91800                         return visitBinaryExpression(node, valueIsDiscarded);
91801                     case 207 /* CallExpression */:
91802                         return visitCallExpression(node);
91803                     case 209 /* TaggedTemplateExpression */:
91804                         return visitTaggedTemplateExpression(node);
91805                     case 205 /* PropertyAccessExpression */:
91806                         return visitPropertyAccessExpression(node);
91807                     case 206 /* ElementAccessExpression */:
91808                         return visitElementAccessExpression(node);
91809                     case 237 /* ExpressionStatement */:
91810                         return visitExpressionStatement(node);
91811                     case 241 /* ForStatement */:
91812                         return visitForStatement(node);
91813                     case 255 /* FunctionDeclaration */:
91814                     case 212 /* FunctionExpression */:
91815                     case 170 /* Constructor */:
91816                     case 168 /* MethodDeclaration */:
91817                     case 171 /* GetAccessor */:
91818                     case 172 /* SetAccessor */: {
91819                         var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
91820                         currentStaticPropertyDeclarationOrStaticBlock = undefined;
91821                         var result = ts.visitEachChild(node, visitor, context);
91822                         currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
91823                         return result;
91824                     }
91825                 }
91826             }
91827             return ts.visitEachChild(node, visitor, context);
91828         }
91829         function discardedValueVisitor(node) {
91830             return visitorWorker(node, /*valueIsDiscarded*/ true);
91831         }
91832         function visitor(node) {
91833             return visitorWorker(node, /*valueIsDiscarded*/ false);
91834         }
91835         function heritageClauseVisitor(node) {
91836             switch (node.kind) {
91837                 case 290 /* HeritageClause */:
91838                     return ts.visitEachChild(node, heritageClauseVisitor, context);
91839                 case 227 /* ExpressionWithTypeArguments */:
91840                     return visitExpressionWithTypeArguments(node);
91841             }
91842             return visitor(node);
91843         }
91844         function visitorDestructuringTarget(node) {
91845             switch (node.kind) {
91846                 case 204 /* ObjectLiteralExpression */:
91847                 case 203 /* ArrayLiteralExpression */:
91848                     return visitAssignmentPattern(node);
91849                 default:
91850                     return visitor(node);
91851             }
91852         }
91853         /**
91854          * If we visit a private name, this means it is an undeclared private name.
91855          * Replace it with an empty identifier to indicate a problem with the code,
91856          * unless we are in a statement position - otherwise this will not trigger
91857          * a SyntaxError.
91858          */
91859         function visitPrivateIdentifier(node) {
91860             if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
91861                 return node;
91862             }
91863             if (ts.isStatement(node.parent)) {
91864                 return node;
91865             }
91866             return ts.setOriginalNode(factory.createIdentifier(""), node);
91867         }
91868         /**
91869          * Visits `#id in expr`
91870          */
91871         function visitPrivateIdentifierInInExpression(node) {
91872             if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
91873                 return node;
91874             }
91875             var privId = node.left;
91876             ts.Debug.assertNode(privId, ts.isPrivateIdentifier);
91877             ts.Debug.assert(node.operatorToken.kind === 101 /* InKeyword */);
91878             var info = accessPrivateIdentifier(privId);
91879             if (info) {
91880                 var receiver = ts.visitNode(node.right, visitor, ts.isExpression);
91881                 return ts.setOriginalNode(context.getEmitHelperFactory().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), node);
91882             }
91883             // Private name has not been declared. Subsequent transformers will handle this error
91884             return ts.visitEachChild(node, visitor, context);
91885         }
91886         /**
91887          * Visits the members of a class that has fields.
91888          *
91889          * @param node The node to visit.
91890          */
91891         function classElementVisitor(node) {
91892             switch (node.kind) {
91893                 case 170 /* Constructor */:
91894                     // Constructors for classes using class fields are transformed in
91895                     // `visitClassDeclaration` or `visitClassExpression`.
91896                     return undefined;
91897                 case 171 /* GetAccessor */:
91898                 case 172 /* SetAccessor */:
91899                 case 168 /* MethodDeclaration */:
91900                     return visitMethodOrAccessorDeclaration(node);
91901                 case 166 /* PropertyDeclaration */:
91902                     return visitPropertyDeclaration(node);
91903                 case 161 /* ComputedPropertyName */:
91904                     return visitComputedPropertyName(node);
91905                 case 233 /* SemicolonClassElement */:
91906                     return node;
91907                 default:
91908                     return visitor(node);
91909             }
91910         }
91911         function visitVariableStatement(node) {
91912             var savedPendingStatements = pendingStatements;
91913             pendingStatements = [];
91914             var visitedNode = ts.visitEachChild(node, visitor, context);
91915             var statement = ts.some(pendingStatements) ? __spreadArray([visitedNode], pendingStatements, true) :
91916                 visitedNode;
91917             pendingStatements = savedPendingStatements;
91918             return statement;
91919         }
91920         function visitComputedPropertyName(name) {
91921             var node = ts.visitEachChild(name, visitor, context);
91922             if (ts.some(pendingExpressions)) {
91923                 var expressions = pendingExpressions;
91924                 expressions.push(node.expression);
91925                 pendingExpressions = [];
91926                 node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
91927             }
91928             return node;
91929         }
91930         function visitMethodOrAccessorDeclaration(node) {
91931             ts.Debug.assert(!ts.some(node.decorators));
91932             if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) {
91933                 return ts.visitEachChild(node, classElementVisitor, context);
91934             }
91935             // leave invalid code untransformed
91936             var info = accessPrivateIdentifier(node.name);
91937             ts.Debug.assert(info, "Undeclared private name for property declaration.");
91938             if (!info.isValid) {
91939                 return node;
91940             }
91941             var functionName = getHoistedFunctionName(node);
91942             if (functionName) {
91943                 getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, 
91944                 /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), 
91945                 /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context))));
91946             }
91947             // remove method declaration from class
91948             return undefined;
91949         }
91950         function getHoistedFunctionName(node) {
91951             ts.Debug.assert(ts.isPrivateIdentifier(node.name));
91952             var info = accessPrivateIdentifier(node.name);
91953             ts.Debug.assert(info, "Undeclared private name for property declaration.");
91954             if (info.kind === "m" /* Method */) {
91955                 return info.methodName;
91956             }
91957             if (info.kind === "a" /* Accessor */) {
91958                 if (ts.isGetAccessor(node)) {
91959                     return info.getterName;
91960                 }
91961                 if (ts.isSetAccessor(node)) {
91962                     return info.setterName;
91963                 }
91964             }
91965         }
91966         function visitPropertyDeclaration(node) {
91967             ts.Debug.assert(!ts.some(node.decorators));
91968             if (ts.isPrivateIdentifier(node.name)) {
91969                 if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
91970                     // Initializer is elided as the field is initialized in transformConstructor.
91971                     return factory.updatePropertyDeclaration(node, 
91972                     /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
91973                     /*questionOrExclamationToken*/ undefined, 
91974                     /*type*/ undefined, 
91975                     /*initializer*/ undefined);
91976                 }
91977                 // leave invalid code untransformed
91978                 var info = accessPrivateIdentifier(node.name);
91979                 ts.Debug.assert(info, "Undeclared private name for property declaration.");
91980                 if (!info.isValid) {
91981                     return node;
91982                 }
91983             }
91984             // Create a temporary variable to store a computed property name (if necessary).
91985             // If it's not inlineable, then we emit an expression after the class which assigns
91986             // the property name to the temporary variable.
91987             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields);
91988             if (expr && !ts.isSimpleInlineableExpression(expr)) {
91989                 getPendingExpressions().push(expr);
91990             }
91991             return undefined;
91992         }
91993         function createPrivateIdentifierAccess(info, receiver) {
91994             return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression));
91995         }
91996         function createPrivateIdentifierAccessHelper(info, receiver) {
91997             ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1));
91998             switch (info.kind) {
91999                 case "a" /* Accessor */:
92000                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName);
92001                 case "m" /* Method */:
92002                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName);
92003                 case "f" /* Field */:
92004                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName);
92005                 default:
92006                     ts.Debug.assertNever(info, "Unknown private element type");
92007             }
92008         }
92009         function visitPropertyAccessExpression(node) {
92010             if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifier(node.name)) {
92011                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
92012                 if (privateIdentifierInfo) {
92013                     return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node);
92014                 }
92015             }
92016             if (shouldTransformSuperInStaticInitializers &&
92017                 ts.isSuperProperty(node) &&
92018                 ts.isIdentifier(node.name) &&
92019                 currentStaticPropertyDeclarationOrStaticBlock &&
92020                 currentClassLexicalEnvironment) {
92021                 var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
92022                 if (facts & 1 /* ClassWasDecorated */) {
92023                     return visitInvalidSuperProperty(node);
92024                 }
92025                 if (classConstructor && superClassReference) {
92026                     // converts `super.x` into `Reflect.get(_baseTemp, "x", _classTemp)`
92027                     var superProperty = factory.createReflectGetCall(superClassReference, factory.createStringLiteralFromNode(node.name), classConstructor);
92028                     ts.setOriginalNode(superProperty, node.expression);
92029                     ts.setTextRange(superProperty, node.expression);
92030                     return superProperty;
92031                 }
92032             }
92033             return ts.visitEachChild(node, visitor, context);
92034         }
92035         function visitElementAccessExpression(node) {
92036             if (shouldTransformSuperInStaticInitializers &&
92037                 ts.isSuperProperty(node) &&
92038                 currentStaticPropertyDeclarationOrStaticBlock &&
92039                 currentClassLexicalEnvironment) {
92040                 var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
92041                 if (facts & 1 /* ClassWasDecorated */) {
92042                     return visitInvalidSuperProperty(node);
92043                 }
92044                 if (classConstructor && superClassReference) {
92045                     // converts `super[x]` into `Reflect.get(_baseTemp, x, _classTemp)`
92046                     var superProperty = factory.createReflectGetCall(superClassReference, ts.visitNode(node.argumentExpression, visitor, ts.isExpression), classConstructor);
92047                     ts.setOriginalNode(superProperty, node.expression);
92048                     ts.setTextRange(superProperty, node.expression);
92049                     return superProperty;
92050                 }
92051             }
92052             return ts.visitEachChild(node, visitor, context);
92053         }
92054         function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) {
92055             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
92056                 if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
92057                     var info = void 0;
92058                     if (info = accessPrivateIdentifier(node.operand.name)) {
92059                         var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
92060                         var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
92061                         var expression = createPrivateIdentifierAccess(info, readExpression);
92062                         var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
92063                         expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp);
92064                         expression = createPrivateIdentifierAssignment(info, initializeExpression || readExpression, expression, 63 /* EqualsToken */);
92065                         ts.setOriginalNode(expression, node);
92066                         ts.setTextRange(expression, node);
92067                         if (temp) {
92068                             expression = factory.createComma(expression, temp);
92069                             ts.setTextRange(expression, node);
92070                         }
92071                         return expression;
92072                     }
92073                 }
92074                 else if (shouldTransformSuperInStaticInitializers &&
92075                     ts.isSuperProperty(node.operand) &&
92076                     currentStaticPropertyDeclarationOrStaticBlock &&
92077                     currentClassLexicalEnvironment) {
92078                     // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)`
92079                     // converts `++super[f()]` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = ++_b), _classTemp), _c)`
92080                     // converts `--super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = --_a), _classTemp), _b)`
92081                     // converts `--super[f()]` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = --_b), _classTemp), _c)`
92082                     // converts `super.a++` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = _a++), _classTemp), _b)`
92083                     // converts `super[f()]++` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b++), _classTemp), _c)`
92084                     // converts `super.a--` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = _a--), _classTemp), _b)`
92085                     // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)`
92086                     var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
92087                     if (facts & 1 /* ClassWasDecorated */) {
92088                         var operand = visitInvalidSuperProperty(node.operand);
92089                         return ts.isPrefixUnaryExpression(node) ?
92090                             factory.updatePrefixUnaryExpression(node, operand) :
92091                             factory.updatePostfixUnaryExpression(node, operand);
92092                     }
92093                     if (classConstructor && superClassReference) {
92094                         var setterName = void 0;
92095                         var getterName = void 0;
92096                         if (ts.isPropertyAccessExpression(node.operand)) {
92097                             if (ts.isIdentifier(node.operand.name)) {
92098                                 getterName = setterName = factory.createStringLiteralFromNode(node.operand.name);
92099                             }
92100                         }
92101                         else {
92102                             if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) {
92103                                 getterName = setterName = node.operand.argumentExpression;
92104                             }
92105                             else {
92106                                 getterName = factory.createTempVariable(hoistVariableDeclaration);
92107                                 setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression));
92108                             }
92109                         }
92110                         if (setterName && getterName) {
92111                             var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor);
92112                             ts.setTextRange(expression, node.operand);
92113                             var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
92114                             expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp);
92115                             expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor);
92116                             ts.setOriginalNode(expression, node);
92117                             ts.setTextRange(expression, node);
92118                             if (temp) {
92119                                 expression = factory.createComma(expression, temp);
92120                                 ts.setTextRange(expression, node);
92121                             }
92122                             return expression;
92123                         }
92124                     }
92125                 }
92126             }
92127             return ts.visitEachChild(node, visitor, context);
92128         }
92129         function visitForStatement(node) {
92130             return factory.updateForStatement(node, ts.visitNode(node.initializer, discardedValueVisitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, discardedValueVisitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context));
92131         }
92132         function visitExpressionStatement(node) {
92133             return factory.updateExpressionStatement(node, ts.visitNode(node.expression, discardedValueVisitor, ts.isExpression));
92134         }
92135         function createCopiableReceiverExpr(receiver) {
92136             var clone = ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
92137             if (ts.isSimpleInlineableExpression(receiver)) {
92138                 return { readExpression: clone, initializeExpression: undefined };
92139             }
92140             var readExpression = factory.createTempVariable(hoistVariableDeclaration);
92141             var initializeExpression = factory.createAssignment(readExpression, clone);
92142             return { readExpression: readExpression, initializeExpression: initializeExpression };
92143         }
92144         function visitCallExpression(node) {
92145             if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
92146                 // Transform call expressions of private names to properly bind the `this` parameter.
92147                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
92148                 if (ts.isCallChain(node)) {
92149                     return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), 
92150                     /*questionDotToken*/ undefined, 
92151                     /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression), true));
92152                 }
92153                 return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), 
92154                 /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression), true));
92155             }
92156             if (shouldTransformSuperInStaticInitializers &&
92157                 ts.isSuperProperty(node.expression) &&
92158                 currentStaticPropertyDeclarationOrStaticBlock &&
92159                 (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.classConstructor)) {
92160                 // converts `super.f(...)` into `Reflect.get(_baseTemp, "f", _classTemp).call(_classTemp, ...)`
92161                 var invocation = factory.createFunctionCallCall(ts.visitNode(node.expression, visitor, ts.isExpression), currentClassLexicalEnvironment.classConstructor, ts.visitNodes(node.arguments, visitor, ts.isExpression));
92162                 ts.setOriginalNode(invocation, node);
92163                 ts.setTextRange(invocation, node);
92164                 return invocation;
92165             }
92166             return ts.visitEachChild(node, visitor, context);
92167         }
92168         function visitTaggedTemplateExpression(node) {
92169             if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
92170                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
92171                 var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
92172                 return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), 
92173                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), 
92174                 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
92175             }
92176             if (shouldTransformSuperInStaticInitializers &&
92177                 ts.isSuperProperty(node.tag) &&
92178                 currentStaticPropertyDeclarationOrStaticBlock &&
92179                 (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.classConstructor)) {
92180                 // converts `` super.f`x` `` into `` Reflect.get(_baseTemp, "f", _classTemp).bind(_classTemp)`x` ``
92181                 var invocation = factory.createFunctionBindCall(ts.visitNode(node.tag, visitor, ts.isExpression), currentClassLexicalEnvironment.classConstructor, []);
92182                 ts.setOriginalNode(invocation, node);
92183                 ts.setTextRange(invocation, node);
92184                 return factory.updateTaggedTemplateExpression(node, invocation, 
92185                 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
92186             }
92187             return ts.visitEachChild(node, visitor, context);
92188         }
92189         function transformClassStaticBlockDeclaration(node) {
92190             if (shouldTransformPrivateElementsOrClassStaticBlocks) {
92191                 if (currentClassLexicalEnvironment) {
92192                     classLexicalEnvironmentMap.set(ts.getOriginalNodeId(node), currentClassLexicalEnvironment);
92193                 }
92194                 startLexicalEnvironment();
92195                 var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
92196                 currentStaticPropertyDeclarationOrStaticBlock = node;
92197                 var statements = ts.visitNodes(node.body.statements, visitor, ts.isStatement);
92198                 statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
92199                 currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
92200                 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
92201                 ts.setOriginalNode(iife, node);
92202                 ts.setTextRange(iife, node);
92203                 ts.addEmitFlags(iife, 2 /* AdviseOnEmitNode */);
92204                 return iife;
92205             }
92206         }
92207         function visitBinaryExpression(node, valueIsDiscarded) {
92208             if (ts.isDestructuringAssignment(node)) {
92209                 var savedPendingExpressions = pendingExpressions;
92210                 pendingExpressions = undefined;
92211                 node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
92212                 var expr = ts.some(pendingExpressions) ?
92213                     factory.inlineExpressions(ts.compact(__spreadArray(__spreadArray([], pendingExpressions, true), [node], false))) :
92214                     node;
92215                 pendingExpressions = savedPendingExpressions;
92216                 return expr;
92217             }
92218             if (ts.isAssignmentExpression(node)) {
92219                 if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
92220                     var info = accessPrivateIdentifier(node.left.name);
92221                     if (info) {
92222                         return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node);
92223                     }
92224                 }
92225                 else if (shouldTransformSuperInStaticInitializers &&
92226                     ts.isSuperProperty(node.left) &&
92227                     currentStaticPropertyDeclarationOrStaticBlock &&
92228                     currentClassLexicalEnvironment) {
92229                     var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
92230                     if (facts & 1 /* ClassWasDecorated */) {
92231                         return factory.updateBinaryExpression(node, visitInvalidSuperProperty(node.left), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
92232                     }
92233                     if (classConstructor && superClassReference) {
92234                         var setterName = ts.isElementAccessExpression(node.left) ? ts.visitNode(node.left.argumentExpression, visitor, ts.isExpression) :
92235                             ts.isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) :
92236                                 undefined;
92237                         if (setterName) {
92238                             // converts `super.x = 1` into `(Reflect.set(_baseTemp, "x", _a = 1, _classTemp), _a)`
92239                             // converts `super[f()] = 1` into `(Reflect.set(_baseTemp, f(), _a = 1, _classTemp), _a)`
92240                             // converts `super.x += 1` into `(Reflect.set(_baseTemp, "x", _a = Reflect.get(_baseTemp, "x", _classtemp) + 1, _classTemp), _a)`
92241                             // converts `super[f()] += 1` into `(Reflect.set(_baseTemp, _a = f(), _b = Reflect.get(_baseTemp, _a, _classtemp) + 1, _classTemp), _b)`
92242                             var expression = ts.visitNode(node.right, visitor, ts.isExpression);
92243                             if (ts.isCompoundAssignment(node.operatorToken.kind)) {
92244                                 var getterName = setterName;
92245                                 if (!ts.isSimpleInlineableExpression(setterName)) {
92246                                     getterName = factory.createTempVariable(hoistVariableDeclaration);
92247                                     setterName = factory.createAssignment(getterName, setterName);
92248                                 }
92249                                 var superPropertyGet = factory.createReflectGetCall(superClassReference, getterName, classConstructor);
92250                                 ts.setOriginalNode(superPropertyGet, node.left);
92251                                 ts.setTextRange(superPropertyGet, node.left);
92252                                 expression = factory.createBinaryExpression(superPropertyGet, ts.getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), expression);
92253                                 ts.setTextRange(expression, node);
92254                             }
92255                             var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
92256                             if (temp) {
92257                                 expression = factory.createAssignment(temp, expression);
92258                                 ts.setTextRange(temp, node);
92259                             }
92260                             expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor);
92261                             ts.setOriginalNode(expression, node);
92262                             ts.setTextRange(expression, node);
92263                             if (temp) {
92264                                 expression = factory.createComma(expression, temp);
92265                                 ts.setTextRange(expression, node);
92266                             }
92267                             return expression;
92268                         }
92269                     }
92270                 }
92271             }
92272             if (node.operatorToken.kind === 101 /* InKeyword */ && ts.isPrivateIdentifier(node.left)) {
92273                 return visitPrivateIdentifierInInExpression(node);
92274             }
92275             return ts.visitEachChild(node, visitor, context);
92276         }
92277         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
92278             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
92279             right = ts.visitNode(right, visitor, ts.isExpression);
92280             if (ts.isCompoundAssignment(operator)) {
92281                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
92282                 receiver = initializeExpression || readExpression;
92283                 right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right);
92284             }
92285             ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1));
92286             switch (info.kind) {
92287                 case "a" /* Accessor */:
92288                     return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName);
92289                 case "m" /* Method */:
92290                     return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, 
92291                     /* f */ undefined);
92292                 case "f" /* Field */:
92293                     return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName);
92294                 default:
92295                     ts.Debug.assertNever(info, "Unknown private element type");
92296             }
92297         }
92298         /**
92299          * Set up the environment for a class.
92300          */
92301         function visitClassLike(node) {
92302             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
92303                 return ts.visitEachChild(node, visitor, context);
92304             }
92305             var savedPendingExpressions = pendingExpressions;
92306             pendingExpressions = undefined;
92307             startClassLexicalEnvironment();
92308             if (shouldTransformPrivateElementsOrClassStaticBlocks) {
92309                 var name = ts.getNameOfDeclaration(node);
92310                 if (name && ts.isIdentifier(name)) {
92311                     getPrivateIdentifierEnvironment().className = ts.idText(name);
92312                 }
92313                 var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
92314                 if (ts.some(privateInstanceMethodsAndAccessors)) {
92315                     getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name);
92316                 }
92317             }
92318             var result = ts.isClassDeclaration(node) ?
92319                 visitClassDeclaration(node) :
92320                 visitClassExpression(node);
92321             endClassLexicalEnvironment();
92322             pendingExpressions = savedPendingExpressions;
92323             return result;
92324         }
92325         function doesClassElementNeedTransform(node) {
92326             return ts.isPropertyDeclaration(node) || ts.isClassStaticBlockDeclaration(node) || (shouldTransformPrivateElementsOrClassStaticBlocks && node.name && ts.isPrivateIdentifier(node.name));
92327         }
92328         function getPrivateInstanceMethodsAndAccessors(node) {
92329             return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName);
92330         }
92331         function getClassFacts(node) {
92332             var facts = 0 /* None */;
92333             var original = ts.getOriginalNode(node);
92334             if (ts.isClassDeclaration(original) && ts.classOrConstructorParameterIsDecorated(original)) {
92335                 facts |= 1 /* ClassWasDecorated */;
92336             }
92337             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
92338                 var member = _a[_i];
92339                 if (!ts.isStatic(member))
92340                     continue;
92341                 if (member.name && ts.isPrivateIdentifier(member.name) && shouldTransformPrivateElementsOrClassStaticBlocks) {
92342                     facts |= 2 /* NeedsClassConstructorReference */;
92343                 }
92344                 if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) {
92345                     if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* ContainsLexicalThis */) {
92346                         facts |= 8 /* NeedsSubstitutionForThisInClassStaticField */;
92347                         if (!(facts & 1 /* ClassWasDecorated */)) {
92348                             facts |= 2 /* NeedsClassConstructorReference */;
92349                         }
92350                     }
92351                     if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* ContainsLexicalSuper */) {
92352                         if (!(facts & 1 /* ClassWasDecorated */)) {
92353                             facts |= 2 /* NeedsClassConstructorReference */ | 4 /* NeedsClassSuperReference */;
92354                         }
92355                     }
92356                 }
92357             }
92358             return facts;
92359         }
92360         function visitExpressionWithTypeArguments(node) {
92361             var facts = (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.facts) || 0 /* None */;
92362             if (facts & 4 /* NeedsClassSuperReference */) {
92363                 var temp = factory.createTempVariable(hoistVariableDeclaration, /*reserveInNestedScopes*/ true);
92364                 getClassLexicalEnvironment().superClassReference = temp;
92365                 return factory.updateExpressionWithTypeArguments(node, factory.createAssignment(temp, ts.visitNode(node.expression, visitor, ts.isExpression)), 
92366                 /*typeArguments*/ undefined);
92367             }
92368             return ts.visitEachChild(node, visitor, context);
92369         }
92370         function visitClassDeclaration(node) {
92371             var facts = getClassFacts(node);
92372             if (facts) {
92373                 getClassLexicalEnvironment().facts = facts;
92374             }
92375             if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) {
92376                 enableSubstitutionForClassStaticThisOrSuperReference();
92377             }
92378             var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node);
92379             // If a class has private static fields, or a static field has a `this` or `super` reference,
92380             // then we need to allocate a temp variable to hold on to that reference.
92381             var pendingClassReferenceAssignment;
92382             if (facts & 2 /* NeedsClassConstructorReference */) {
92383                 var temp = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
92384                 getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp);
92385                 pendingClassReferenceAssignment = factory.createAssignment(temp, factory.getInternalName(node));
92386             }
92387             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
92388             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */);
92389             var statements = [
92390                 factory.updateClassDeclaration(node, 
92391                 /*decorators*/ undefined, node.modifiers, node.name, 
92392                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
92393             ];
92394             if (pendingClassReferenceAssignment) {
92395                 getPendingExpressions().unshift(pendingClassReferenceAssignment);
92396             }
92397             // Write any pending expressions from elided or moved computed property names
92398             if (ts.some(pendingExpressions)) {
92399                 statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
92400             }
92401             // Emit static property assignment. Because classDeclaration is lexically evaluated,
92402             // it is safe to emit static property assignment after classDeclaration
92403             // From ES6 specification:
92404             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
92405             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
92406             if (ts.some(staticProperties)) {
92407                 addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node));
92408             }
92409             return statements;
92410         }
92411         function visitClassExpression(node) {
92412             var facts = getClassFacts(node);
92413             if (facts) {
92414                 getClassLexicalEnvironment().facts = facts;
92415             }
92416             if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) {
92417                 enableSubstitutionForClassStaticThisOrSuperReference();
92418             }
92419             // If this class expression is a transformation of a decorated class declaration,
92420             // then we want to output the pendingExpressions as statements, not as inlined
92421             // expressions with the class statement.
92422             //
92423             // In this case, we use pendingStatements to produce the same output as the
92424             // class declaration transformation. The VariableStatement visitor will insert
92425             // these statements after the class expression variable statement.
92426             var isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */);
92427             var staticPropertiesOrClassStaticBlocks = ts.getStaticPropertiesAndClassStaticBlock(node);
92428             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
92429             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */);
92430             var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
92431             var temp;
92432             function createClassTempVar() {
92433                 var classCheckFlags = resolver.getNodeCheckFlags(node);
92434                 var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */;
92435                 var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */;
92436                 return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference);
92437             }
92438             if (facts & 2 /* NeedsClassConstructorReference */) {
92439                 temp = createClassTempVar();
92440                 getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp);
92441             }
92442             var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, 
92443             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
92444             var hasTransformableStatics = ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifier(p.name)); });
92445             if (hasTransformableStatics || ts.some(pendingExpressions)) {
92446                 if (isDecoratedClassDeclaration) {
92447                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
92448                     // Write any pending expressions from elided or moved computed property names
92449                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
92450                         pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
92451                     }
92452                     if (pendingStatements && ts.some(staticPropertiesOrClassStaticBlocks)) {
92453                         addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, factory.getInternalName(node));
92454                     }
92455                     if (temp) {
92456                         return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]);
92457                     }
92458                     return classExpression;
92459                 }
92460                 else {
92461                     var expressions = [];
92462                     temp || (temp = createClassTempVar());
92463                     if (isClassWithConstructorReference) {
92464                         // record an alias as the class name is not in scope for statics.
92465                         enableSubstitutionForClassAliases();
92466                         var alias = factory.cloneNode(temp);
92467                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
92468                         classAliases[ts.getOriginalNodeId(node)] = alias;
92469                     }
92470                     // To preserve the behavior of the old emitter, we explicitly indent
92471                     // the body of a class with static initializers.
92472                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
92473                     expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)));
92474                     // Add any pending expressions leftover from elided or relocated computed property names
92475                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
92476                     ts.addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp));
92477                     expressions.push(ts.startOnNewLine(temp));
92478                     return factory.inlineExpressions(expressions);
92479                 }
92480             }
92481             return classExpression;
92482         }
92483         function visitClassStaticBlockDeclaration(node) {
92484             if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
92485                 return ts.visitEachChild(node, classElementVisitor, context);
92486             }
92487             // ClassStaticBlockDeclaration for classes are transformed in `visitClassDeclaration` or `visitClassExpression`.
92488             return undefined;
92489         }
92490         function transformClassMembers(node, isDerivedClass) {
92491             if (shouldTransformPrivateElementsOrClassStaticBlocks) {
92492                 // Declare private names.
92493                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
92494                     var member = _a[_i];
92495                     if (ts.isPrivateIdentifierClassElementDeclaration(member)) {
92496                         addPrivateIdentifierToEnvironment(member);
92497                     }
92498                 }
92499                 if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) {
92500                     createBrandCheckWeakSetForPrivateMethods();
92501                 }
92502             }
92503             var members = [];
92504             var constructor = transformConstructor(node, isDerivedClass);
92505             if (constructor) {
92506                 members.push(constructor);
92507             }
92508             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
92509             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
92510         }
92511         function createBrandCheckWeakSetForPrivateMethods() {
92512             var weakSetName = getPrivateIdentifierEnvironment().weakSetName;
92513             ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
92514             getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), 
92515             /*typeArguments*/ undefined, [])));
92516         }
92517         function isClassElementThatRequiresConstructorStatement(member) {
92518             if (ts.isStatic(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) {
92519                 return false;
92520             }
92521             if (useDefineForClassFields) {
92522                 // If we are using define semantics and targeting ESNext or higher,
92523                 // then we don't need to transform any class properties.
92524                 return languageVersion < 99 /* ESNext */;
92525             }
92526             return ts.isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierClassElementDeclaration(member);
92527         }
92528         function transformConstructor(node, isDerivedClass) {
92529             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
92530             var elements = node.members.filter(isClassElementThatRequiresConstructorStatement);
92531             if (!ts.some(elements)) {
92532                 return constructor;
92533             }
92534             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
92535             var body = transformConstructorBody(node, constructor, isDerivedClass);
92536             if (!body) {
92537                 return undefined;
92538             }
92539             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(
92540             /*decorators*/ undefined, 
92541             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
92542         }
92543         function transformConstructorBody(node, constructor, isDerivedClass) {
92544             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
92545             if (!useDefineForClassFields) {
92546                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
92547             }
92548             var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
92549             var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors);
92550             // Only generate synthetic constructor when there are property initializers to move.
92551             if (!constructor && !needsConstructorBody) {
92552                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
92553             }
92554             resumeLexicalEnvironment();
92555             var indexOfFirstStatement = 0;
92556             var statements = [];
92557             if (!constructor && isDerivedClass) {
92558                 // Add a synthetic `super` call:
92559                 //
92560                 //  super(...arguments);
92561                 //
92562                 statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), 
92563                 /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))])));
92564             }
92565             if (constructor) {
92566                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
92567             }
92568             // Add the property initializers. Transforms this:
92569             //
92570             //  public x = 1;
92571             //
92572             // Into this:
92573             //
92574             //  constructor() {
92575             //      this.x = 1;
92576             //  }
92577             //
92578             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
92579                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
92580                 if (afterParameterProperties === -1) {
92581                     afterParameterProperties = constructor.body.statements.length;
92582                 }
92583                 if (afterParameterProperties > indexOfFirstStatement) {
92584                     if (!useDefineForClassFields) {
92585                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
92586                     }
92587                     indexOfFirstStatement = afterParameterProperties;
92588                 }
92589             }
92590             var receiver = factory.createThis();
92591             // private methods can be called in property initializers, they should execute first.
92592             addMethodStatements(statements, privateMethodsAndAccessors, receiver);
92593             addPropertyOrClassStaticBlockStatements(statements, properties, receiver);
92594             // Add existing statements, skipping the initial super call.
92595             if (constructor) {
92596                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
92597             }
92598             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
92599             return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
92600             /*location*/ constructor ? constructor.body.statements : node.members), 
92601             /*multiLine*/ true), 
92602             /*location*/ constructor ? constructor.body : undefined);
92603         }
92604         /**
92605          * Generates assignment statements for property initializers.
92606          *
92607          * @param properties An array of property declarations to transform.
92608          * @param receiver The receiver on which each property should be assigned.
92609          */
92610         function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) {
92611             for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
92612                 var property = properties_7[_i];
92613                 var expression = ts.isClassStaticBlockDeclaration(property) ?
92614                     transformClassStaticBlockDeclaration(property) :
92615                     transformProperty(property, receiver);
92616                 if (!expression) {
92617                     continue;
92618                 }
92619                 var statement = factory.createExpressionStatement(expression);
92620                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
92621                 ts.setCommentRange(statement, property);
92622                 ts.setOriginalNode(statement, property);
92623                 statements.push(statement);
92624             }
92625         }
92626         /**
92627          * Generates assignment expressions for property initializers.
92628          *
92629          * @param propertiesOrClassStaticBlocks An array of property declarations to transform.
92630          * @param receiver The receiver on which each property should be assigned.
92631          */
92632         function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks, receiver) {
92633             var expressions = [];
92634             for (var _i = 0, propertiesOrClassStaticBlocks_1 = propertiesOrClassStaticBlocks; _i < propertiesOrClassStaticBlocks_1.length; _i++) {
92635                 var property = propertiesOrClassStaticBlocks_1[_i];
92636                 var expression = ts.isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver);
92637                 if (!expression) {
92638                     continue;
92639                 }
92640                 ts.startOnNewLine(expression);
92641                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
92642                 ts.setCommentRange(expression, property);
92643                 ts.setOriginalNode(expression, property);
92644                 expressions.push(expression);
92645             }
92646             return expressions;
92647         }
92648         /**
92649          * Transforms a property initializer into an assignment statement.
92650          *
92651          * @param property The property declaration.
92652          * @param receiver The object receiving the property assignment.
92653          */
92654         function transformProperty(property, receiver) {
92655             var savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
92656             var transformed = transformPropertyWorker(property, receiver);
92657             if (transformed && ts.hasStaticModifier(property) && (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.facts)) {
92658                 // capture the lexical environment for the member
92659                 ts.setOriginalNode(transformed, property);
92660                 ts.addEmitFlags(transformed, 2 /* AdviseOnEmitNode */);
92661                 classLexicalEnvironmentMap.set(ts.getOriginalNodeId(transformed), currentClassLexicalEnvironment);
92662             }
92663             currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
92664             return transformed;
92665         }
92666         function transformPropertyWorker(property, receiver) {
92667             var _a;
92668             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
92669             var emitAssignment = !useDefineForClassFields;
92670             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
92671                 ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
92672                 : property.name;
92673             if (ts.hasStaticModifier(property)) {
92674                 currentStaticPropertyDeclarationOrStaticBlock = property;
92675             }
92676             if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifier(propertyName)) {
92677                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
92678                 if (privateIdentifierInfo) {
92679                     if (privateIdentifierInfo.kind === "f" /* Field */) {
92680                         if (!privateIdentifierInfo.isStatic) {
92681                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier);
92682                         }
92683                         else {
92684                             return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression));
92685                         }
92686                     }
92687                     else {
92688                         return undefined;
92689                     }
92690                 }
92691                 else {
92692                     ts.Debug.fail("Undeclared private name for property declaration.");
92693                 }
92694             }
92695             if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) {
92696                 return undefined;
92697             }
92698             var propertyOriginalNode = ts.getOriginalNode(property);
92699             if (ts.hasSyntacticModifier(propertyOriginalNode, 128 /* Abstract */)) {
92700                 return undefined;
92701             }
92702             var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero()
92703                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
92704                     : factory.createVoidZero();
92705             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
92706                 var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
92707                 return factory.createAssignment(memberAccess, initializer);
92708             }
92709             else {
92710                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
92711                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
92712                         : propertyName;
92713                 var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
92714                 return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
92715             }
92716         }
92717         function enableSubstitutionForClassAliases() {
92718             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
92719                 enabledSubstitutions |= 1 /* ClassAliases */;
92720                 // We need to enable substitutions for identifiers. This allows us to
92721                 // substitute class names inside of a class declaration.
92722                 context.enableSubstitution(79 /* Identifier */);
92723                 // Keep track of class aliases.
92724                 classAliases = [];
92725             }
92726         }
92727         function enableSubstitutionForClassStaticThisOrSuperReference() {
92728             if ((enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */) === 0) {
92729                 enabledSubstitutions |= 2 /* ClassStaticThisOrSuperReference */;
92730                 // substitute `this` in a static field initializer
92731                 context.enableSubstitution(108 /* ThisKeyword */);
92732                 // these push a new lexical environment that is not the class lexical environment
92733                 context.enableEmitNotification(255 /* FunctionDeclaration */);
92734                 context.enableEmitNotification(212 /* FunctionExpression */);
92735                 context.enableEmitNotification(170 /* Constructor */);
92736                 // these push a new lexical environment that is not the class lexical environment, except
92737                 // when they have a computed property name
92738                 context.enableEmitNotification(171 /* GetAccessor */);
92739                 context.enableEmitNotification(172 /* SetAccessor */);
92740                 context.enableEmitNotification(168 /* MethodDeclaration */);
92741                 context.enableEmitNotification(166 /* PropertyDeclaration */);
92742                 // class lexical environments are restored when entering a computed property name
92743                 context.enableEmitNotification(161 /* ComputedPropertyName */);
92744             }
92745         }
92746         /**
92747          * Generates brand-check initializer for private methods.
92748          *
92749          * @param statements Statement list that should be used to append new statements.
92750          * @param methods An array of method declarations.
92751          * @param receiver The receiver on which each method should be assigned.
92752          */
92753         function addMethodStatements(statements, methods, receiver) {
92754             if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.some(methods)) {
92755                 return;
92756             }
92757             var weakSetName = getPrivateIdentifierEnvironment().weakSetName;
92758             ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
92759             statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName)));
92760         }
92761         function visitInvalidSuperProperty(node) {
92762             return ts.isPropertyAccessExpression(node) ?
92763                 factory.updatePropertyAccessExpression(node, factory.createVoidZero(), node.name) :
92764                 factory.updateElementAccessExpression(node, factory.createVoidZero(), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
92765         }
92766         function onEmitNode(hint, node, emitCallback) {
92767             var original = ts.getOriginalNode(node);
92768             if (original.id) {
92769                 var classLexicalEnvironment = classLexicalEnvironmentMap.get(original.id);
92770                 if (classLexicalEnvironment) {
92771                     var savedClassLexicalEnvironment = currentClassLexicalEnvironment;
92772                     var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
92773                     currentClassLexicalEnvironment = classLexicalEnvironment;
92774                     currentComputedPropertyNameClassLexicalEnvironment = classLexicalEnvironment;
92775                     previousOnEmitNode(hint, node, emitCallback);
92776                     currentClassLexicalEnvironment = savedClassLexicalEnvironment;
92777                     currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
92778                     return;
92779                 }
92780             }
92781             switch (node.kind) {
92782                 case 212 /* FunctionExpression */:
92783                     if (ts.isArrowFunction(original) || ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */) {
92784                         break;
92785                     }
92786                 // falls through
92787                 case 255 /* FunctionDeclaration */:
92788                 case 170 /* Constructor */: {
92789                     var savedClassLexicalEnvironment = currentClassLexicalEnvironment;
92790                     var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
92791                     currentClassLexicalEnvironment = undefined;
92792                     currentComputedPropertyNameClassLexicalEnvironment = undefined;
92793                     previousOnEmitNode(hint, node, emitCallback);
92794                     currentClassLexicalEnvironment = savedClassLexicalEnvironment;
92795                     currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
92796                     return;
92797                 }
92798                 case 171 /* GetAccessor */:
92799                 case 172 /* SetAccessor */:
92800                 case 168 /* MethodDeclaration */:
92801                 case 166 /* PropertyDeclaration */: {
92802                     var savedClassLexicalEnvironment = currentClassLexicalEnvironment;
92803                     var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
92804                     currentComputedPropertyNameClassLexicalEnvironment = currentClassLexicalEnvironment;
92805                     currentClassLexicalEnvironment = undefined;
92806                     previousOnEmitNode(hint, node, emitCallback);
92807                     currentClassLexicalEnvironment = savedClassLexicalEnvironment;
92808                     currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
92809                     return;
92810                 }
92811                 case 161 /* ComputedPropertyName */: {
92812                     var savedClassLexicalEnvironment = currentClassLexicalEnvironment;
92813                     var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
92814                     currentClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
92815                     currentComputedPropertyNameClassLexicalEnvironment = undefined;
92816                     previousOnEmitNode(hint, node, emitCallback);
92817                     currentClassLexicalEnvironment = savedClassLexicalEnvironment;
92818                     currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
92819                     return;
92820                 }
92821             }
92822             previousOnEmitNode(hint, node, emitCallback);
92823         }
92824         /**
92825          * Hooks node substitutions.
92826          *
92827          * @param hint The context for the emitter.
92828          * @param node The node to substitute.
92829          */
92830         function onSubstituteNode(hint, node) {
92831             node = previousOnSubstituteNode(hint, node);
92832             if (hint === 1 /* Expression */) {
92833                 return substituteExpression(node);
92834             }
92835             return node;
92836         }
92837         function substituteExpression(node) {
92838             switch (node.kind) {
92839                 case 79 /* Identifier */:
92840                     return substituteExpressionIdentifier(node);
92841                 case 108 /* ThisKeyword */:
92842                     return substituteThisExpression(node);
92843             }
92844             return node;
92845         }
92846         function substituteThisExpression(node) {
92847             if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && currentClassLexicalEnvironment) {
92848                 var facts = currentClassLexicalEnvironment.facts, classConstructor = currentClassLexicalEnvironment.classConstructor;
92849                 if (facts & 1 /* ClassWasDecorated */) {
92850                     return factory.createParenthesizedExpression(factory.createVoidZero());
92851                 }
92852                 if (classConstructor) {
92853                     return ts.setTextRange(ts.setOriginalNode(factory.cloneNode(classConstructor), node), node);
92854                 }
92855             }
92856             return node;
92857         }
92858         function substituteExpressionIdentifier(node) {
92859             return trySubstituteClassAlias(node) || node;
92860         }
92861         function trySubstituteClassAlias(node) {
92862             if (enabledSubstitutions & 1 /* ClassAliases */) {
92863                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
92864                     // Due to the emit for class decorators, any reference to the class from inside of the class body
92865                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
92866                     // behavior of class names in ES6.
92867                     // Also, when emitting statics for class expressions, we must substitute a class alias for
92868                     // constructor references in static property initializers.
92869                     var declaration = resolver.getReferencedValueDeclaration(node);
92870                     if (declaration) {
92871                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
92872                         if (classAlias) {
92873                             var clone_3 = factory.cloneNode(classAlias);
92874                             ts.setSourceMapRange(clone_3, node);
92875                             ts.setCommentRange(clone_3, node);
92876                             return clone_3;
92877                         }
92878                     }
92879                 }
92880             }
92881             return undefined;
92882         }
92883         /**
92884          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
92885          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
92886          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
92887          */
92888         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
92889             if (ts.isComputedPropertyName(name)) {
92890                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
92891                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
92892                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
92893                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
92894                 if (!alreadyTransformed && !inlinable && shouldHoist) {
92895                     var generatedName = factory.getGeneratedNameForNode(name);
92896                     if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) {
92897                         addBlockScopedVariable(generatedName);
92898                     }
92899                     else {
92900                         hoistVariableDeclaration(generatedName);
92901                     }
92902                     return factory.createAssignment(generatedName, expression);
92903                 }
92904                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
92905             }
92906         }
92907         function startClassLexicalEnvironment() {
92908             classLexicalEnvironmentStack.push(currentClassLexicalEnvironment);
92909             currentClassLexicalEnvironment = undefined;
92910         }
92911         function endClassLexicalEnvironment() {
92912             currentClassLexicalEnvironment = classLexicalEnvironmentStack.pop();
92913         }
92914         function getClassLexicalEnvironment() {
92915             return currentClassLexicalEnvironment || (currentClassLexicalEnvironment = {
92916                 facts: 0 /* None */,
92917                 classConstructor: undefined,
92918                 superClassReference: undefined,
92919                 privateIdentifierEnvironment: undefined,
92920             });
92921         }
92922         function getPrivateIdentifierEnvironment() {
92923             var lex = getClassLexicalEnvironment();
92924             lex.privateIdentifierEnvironment || (lex.privateIdentifierEnvironment = {
92925                 className: "",
92926                 identifiers: new ts.Map()
92927             });
92928             return lex.privateIdentifierEnvironment;
92929         }
92930         function getPendingExpressions() {
92931             return pendingExpressions || (pendingExpressions = []);
92932         }
92933         function addPrivateIdentifierToEnvironment(node) {
92934             var _a;
92935             var text = ts.getTextOfPropertyName(node.name);
92936             var lex = getClassLexicalEnvironment();
92937             var classConstructor = lex.classConstructor;
92938             var privateEnv = getPrivateIdentifierEnvironment();
92939             var weakSetName = privateEnv.weakSetName;
92940             var assignmentExpressions = [];
92941             var privateName = node.name.escapedText;
92942             var previousInfo = privateEnv.identifiers.get(privateName);
92943             var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined;
92944             if (ts.hasStaticModifier(node)) {
92945                 ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment");
92946                 if (ts.isPropertyDeclaration(node)) {
92947                     var variableName = createHoistedVariableForPrivateName(text, node);
92948                     privateEnv.identifiers.set(privateName, {
92949                         kind: "f" /* Field */,
92950                         variableName: variableName,
92951                         brandCheckIdentifier: classConstructor,
92952                         isStatic: true,
92953                         isValid: isValid,
92954                     });
92955                 }
92956                 else if (ts.isMethodDeclaration(node)) {
92957                     var functionName = createHoistedVariableForPrivateName(text, node);
92958                     privateEnv.identifiers.set(privateName, {
92959                         kind: "m" /* Method */,
92960                         methodName: functionName,
92961                         brandCheckIdentifier: classConstructor,
92962                         isStatic: true,
92963                         isValid: isValid,
92964                     });
92965                 }
92966                 else if (ts.isGetAccessorDeclaration(node)) {
92967                     var getterName = createHoistedVariableForPrivateName(text + "_get", node);
92968                     if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) {
92969                         previousInfo.getterName = getterName;
92970                     }
92971                     else {
92972                         privateEnv.identifiers.set(privateName, {
92973                             kind: "a" /* Accessor */,
92974                             getterName: getterName,
92975                             setterName: undefined,
92976                             brandCheckIdentifier: classConstructor,
92977                             isStatic: true,
92978                             isValid: isValid,
92979                         });
92980                     }
92981                 }
92982                 else if (ts.isSetAccessorDeclaration(node)) {
92983                     var setterName = createHoistedVariableForPrivateName(text + "_set", node);
92984                     if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) {
92985                         previousInfo.setterName = setterName;
92986                     }
92987                     else {
92988                         privateEnv.identifiers.set(privateName, {
92989                             kind: "a" /* Accessor */,
92990                             getterName: undefined,
92991                             setterName: setterName,
92992                             brandCheckIdentifier: classConstructor,
92993                             isStatic: true,
92994                             isValid: isValid,
92995                         });
92996                     }
92997                 }
92998                 else {
92999                     ts.Debug.assertNever(node, "Unknown class element type.");
93000                 }
93001             }
93002             else if (ts.isPropertyDeclaration(node)) {
93003                 var weakMapName = createHoistedVariableForPrivateName(text, node);
93004                 privateEnv.identifiers.set(privateName, {
93005                     kind: "f" /* Field */,
93006                     brandCheckIdentifier: weakMapName,
93007                     isStatic: false,
93008                     variableName: undefined,
93009                     isValid: isValid,
93010                 });
93011                 assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), 
93012                 /*typeArguments*/ undefined, [])));
93013             }
93014             else if (ts.isMethodDeclaration(node)) {
93015                 ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
93016                 privateEnv.identifiers.set(privateName, {
93017                     kind: "m" /* Method */,
93018                     methodName: createHoistedVariableForPrivateName(text, node),
93019                     brandCheckIdentifier: weakSetName,
93020                     isStatic: false,
93021                     isValid: isValid,
93022                 });
93023             }
93024             else if (ts.isAccessor(node)) {
93025                 ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
93026                 if (ts.isGetAccessor(node)) {
93027                     var getterName = createHoistedVariableForPrivateName(text + "_get", node);
93028                     if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) {
93029                         previousInfo.getterName = getterName;
93030                     }
93031                     else {
93032                         privateEnv.identifiers.set(privateName, {
93033                             kind: "a" /* Accessor */,
93034                             getterName: getterName,
93035                             setterName: undefined,
93036                             brandCheckIdentifier: weakSetName,
93037                             isStatic: false,
93038                             isValid: isValid,
93039                         });
93040                     }
93041                 }
93042                 else {
93043                     var setterName = createHoistedVariableForPrivateName(text + "_set", node);
93044                     if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) {
93045                         previousInfo.setterName = setterName;
93046                     }
93047                     else {
93048                         privateEnv.identifiers.set(privateName, {
93049                             kind: "a" /* Accessor */,
93050                             getterName: undefined,
93051                             setterName: setterName,
93052                             brandCheckIdentifier: weakSetName,
93053                             isStatic: false,
93054                             isValid: isValid,
93055                         });
93056                     }
93057                 }
93058             }
93059             else {
93060                 ts.Debug.assertNever(node, "Unknown class element type.");
93061             }
93062             (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions);
93063         }
93064         function createHoistedVariableForClass(name, node) {
93065             var className = getPrivateIdentifierEnvironment().className;
93066             var prefix = className ? "_".concat(className) : "";
93067             var identifier = factory.createUniqueName("".concat(prefix, "_").concat(name), 16 /* Optimistic */);
93068             if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) {
93069                 addBlockScopedVariable(identifier);
93070             }
93071             else {
93072                 hoistVariableDeclaration(identifier);
93073             }
93074             return identifier;
93075         }
93076         function createHoistedVariableForPrivateName(privateName, node) {
93077             return createHoistedVariableForClass(privateName.substring(1), node.name);
93078         }
93079         function accessPrivateIdentifier(name) {
93080             var _a;
93081             if (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.privateIdentifierEnvironment) {
93082                 var info = currentClassLexicalEnvironment.privateIdentifierEnvironment.identifiers.get(name.escapedText);
93083                 if (info) {
93084                     return info;
93085                 }
93086             }
93087             for (var i = classLexicalEnvironmentStack.length - 1; i >= 0; --i) {
93088                 var env = classLexicalEnvironmentStack[i];
93089                 if (!env) {
93090                     continue;
93091                 }
93092                 var info = (_a = env.privateIdentifierEnvironment) === null || _a === void 0 ? void 0 : _a.identifiers.get(name.escapedText);
93093                 if (info) {
93094                     return info;
93095                 }
93096             }
93097             return undefined;
93098         }
93099         function wrapPrivateIdentifierForDestructuringTarget(node) {
93100             var parameter = factory.getGeneratedNameForNode(node);
93101             var info = accessPrivateIdentifier(node.name);
93102             if (!info) {
93103                 return ts.visitEachChild(node, visitor, context);
93104             }
93105             var receiver = node.expression;
93106             // We cannot copy `this` or `super` into the function because they will be bound
93107             // differently inside the function.
93108             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
93109                 receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
93110                 getPendingExpressions().push(factory.createBinaryExpression(receiver, 63 /* EqualsToken */, ts.visitNode(node.expression, visitor, ts.isExpression)));
93111             }
93112             return factory.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 63 /* EqualsToken */));
93113         }
93114         function visitArrayAssignmentTarget(node) {
93115             var target = ts.getTargetOfBindingOrAssignmentElement(node);
93116             if (target) {
93117                 var wrapped = void 0;
93118                 if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
93119                     wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
93120                 }
93121                 else if (shouldTransformSuperInStaticInitializers &&
93122                     ts.isSuperProperty(target) &&
93123                     currentStaticPropertyDeclarationOrStaticBlock &&
93124                     currentClassLexicalEnvironment) {
93125                     var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
93126                     if (facts & 1 /* ClassWasDecorated */) {
93127                         wrapped = visitInvalidSuperProperty(target);
93128                     }
93129                     else if (classConstructor && superClassReference) {
93130                         var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) :
93131                             ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) :
93132                                 undefined;
93133                         if (name) {
93134                             var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
93135                             wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor));
93136                         }
93137                     }
93138                 }
93139                 if (wrapped) {
93140                     if (ts.isAssignmentExpression(node)) {
93141                         return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
93142                     }
93143                     else if (ts.isSpreadElement(node)) {
93144                         return factory.updateSpreadElement(node, wrapped);
93145                     }
93146                     else {
93147                         return wrapped;
93148                     }
93149                 }
93150             }
93151             return ts.visitNode(node, visitorDestructuringTarget);
93152         }
93153         function visitObjectAssignmentTarget(node) {
93154             if (ts.isObjectBindingOrAssignmentElement(node) && !ts.isShorthandPropertyAssignment(node)) {
93155                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
93156                 var wrapped = void 0;
93157                 if (target) {
93158                     if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
93159                         wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
93160                     }
93161                     else if (shouldTransformSuperInStaticInitializers &&
93162                         ts.isSuperProperty(target) &&
93163                         currentStaticPropertyDeclarationOrStaticBlock &&
93164                         currentClassLexicalEnvironment) {
93165                         var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts;
93166                         if (facts & 1 /* ClassWasDecorated */) {
93167                             wrapped = visitInvalidSuperProperty(target);
93168                         }
93169                         else if (classConstructor && superClassReference) {
93170                             var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) :
93171                                 ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) :
93172                                     undefined;
93173                             if (name) {
93174                                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
93175                                 wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor));
93176                             }
93177                         }
93178                     }
93179                 }
93180                 if (ts.isPropertyAssignment(node)) {
93181                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
93182                     return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor, ts.isPropertyName), wrapped ?
93183                         initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped :
93184                         ts.visitNode(node.initializer, visitorDestructuringTarget, ts.isExpression));
93185                 }
93186                 if (ts.isSpreadAssignment(node)) {
93187                     return factory.updateSpreadAssignment(node, wrapped || ts.visitNode(node.expression, visitorDestructuringTarget, ts.isExpression));
93188                 }
93189                 ts.Debug.assert(wrapped === undefined, "Should not have generated a wrapped target");
93190             }
93191             return ts.visitNode(node, visitor);
93192         }
93193         function visitAssignmentPattern(node) {
93194             if (ts.isArrayLiteralExpression(node)) {
93195                 // Transforms private names in destructuring assignment array bindings.
93196                 // Transforms SuperProperty assignments in destructuring assignment array bindings in static initializers.
93197                 //
93198                 // Source:
93199                 // ([ this.#myProp ] = [ "hello" ]);
93200                 //
93201                 // Transformation:
93202                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
93203                 return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
93204             }
93205             else {
93206                 // Transforms private names in destructuring assignment object bindings.
93207                 // Transforms SuperProperty assignments in destructuring assignment object bindings in static initializers.
93208                 //
93209                 // Source:
93210                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
93211                 //
93212                 // Transformation:
93213                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
93214                 return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
93215             }
93216         }
93217     }
93218     ts.transformClassFields = transformClassFields;
93219     function createPrivateStaticFieldInitializer(variableName, initializer) {
93220         return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([
93221             ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero())
93222         ]));
93223     }
93224     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
93225         return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), 
93226         /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]);
93227     }
93228     function createPrivateInstanceMethodInitializer(receiver, weakSetName) {
93229         return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), 
93230         /*typeArguments*/ undefined, [receiver]);
93231     }
93232     function isReservedPrivateName(node) {
93233         return node.escapedText === "#constructor";
93234     }
93235 })(ts || (ts = {}));
93236 /*@internal*/
93237 var ts;
93238 (function (ts) {
93239     var ES2017SubstitutionFlags;
93240     (function (ES2017SubstitutionFlags) {
93241         /** Enables substitutions for async methods with `super` calls. */
93242         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
93243     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
93244     var ContextFlags;
93245     (function (ContextFlags) {
93246         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
93247         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
93248     })(ContextFlags || (ContextFlags = {}));
93249     function transformES2017(context) {
93250         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
93251         var resolver = context.getEmitResolver();
93252         var compilerOptions = context.getCompilerOptions();
93253         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93254         /**
93255          * Keeps track of whether expression substitution has been enabled for specific edge cases.
93256          * They are persisted between each SourceFile transformation and should not be reset.
93257          */
93258         var enabledSubstitutions;
93259         /**
93260          * This keeps track of containers where `super` is valid, for use with
93261          * just-in-time substitution for `super` expressions inside of async methods.
93262          */
93263         var enclosingSuperContainerFlags = 0;
93264         var enclosingFunctionParameterNames;
93265         /**
93266          * Keeps track of property names accessed on super (`super.x`) within async functions.
93267          */
93268         var capturedSuperProperties;
93269         /** Whether the async function contains an element access on super (`super[x]`). */
93270         var hasSuperElementAccess;
93271         /** A set of node IDs for generated super accessors (variable statements). */
93272         var substitutedSuperAccessors = [];
93273         var contextFlags = 0;
93274         // Save the previous transformation hooks.
93275         var previousOnEmitNode = context.onEmitNode;
93276         var previousOnSubstituteNode = context.onSubstituteNode;
93277         // Set new transformation hooks.
93278         context.onEmitNode = onEmitNode;
93279         context.onSubstituteNode = onSubstituteNode;
93280         return ts.chainBundle(context, transformSourceFile);
93281         function transformSourceFile(node) {
93282             if (node.isDeclarationFile) {
93283                 return node;
93284             }
93285             setContextFlag(1 /* NonTopLevel */, false);
93286             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
93287             var visited = ts.visitEachChild(node, visitor, context);
93288             ts.addEmitHelpers(visited, context.readEmitHelpers());
93289             return visited;
93290         }
93291         function setContextFlag(flag, val) {
93292             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
93293         }
93294         function inContext(flags) {
93295             return (contextFlags & flags) !== 0;
93296         }
93297         function inTopLevelContext() {
93298             return !inContext(1 /* NonTopLevel */);
93299         }
93300         function inHasLexicalThisContext() {
93301             return inContext(2 /* HasLexicalThis */);
93302         }
93303         function doWithContext(flags, cb, value) {
93304             var contextFlagsToSet = flags & ~contextFlags;
93305             if (contextFlagsToSet) {
93306                 setContextFlag(contextFlagsToSet, /*val*/ true);
93307                 var result = cb(value);
93308                 setContextFlag(contextFlagsToSet, /*val*/ false);
93309                 return result;
93310             }
93311             return cb(value);
93312         }
93313         function visitDefault(node) {
93314             return ts.visitEachChild(node, visitor, context);
93315         }
93316         function visitor(node) {
93317             if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) {
93318                 return node;
93319             }
93320             switch (node.kind) {
93321                 case 131 /* AsyncKeyword */:
93322                     // ES2017 async modifier should be elided for targets < ES2017
93323                     return undefined;
93324                 case 217 /* AwaitExpression */:
93325                     return visitAwaitExpression(node);
93326                 case 168 /* MethodDeclaration */:
93327                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
93328                 case 255 /* FunctionDeclaration */:
93329                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
93330                 case 212 /* FunctionExpression */:
93331                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
93332                 case 213 /* ArrowFunction */:
93333                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
93334                 case 205 /* PropertyAccessExpression */:
93335                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 106 /* SuperKeyword */) {
93336                         capturedSuperProperties.add(node.name.escapedText);
93337                     }
93338                     return ts.visitEachChild(node, visitor, context);
93339                 case 206 /* ElementAccessExpression */:
93340                     if (capturedSuperProperties && node.expression.kind === 106 /* SuperKeyword */) {
93341                         hasSuperElementAccess = true;
93342                     }
93343                     return ts.visitEachChild(node, visitor, context);
93344                 case 171 /* GetAccessor */:
93345                 case 172 /* SetAccessor */:
93346                 case 170 /* Constructor */:
93347                 case 256 /* ClassDeclaration */:
93348                 case 225 /* ClassExpression */:
93349                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
93350                 default:
93351                     return ts.visitEachChild(node, visitor, context);
93352             }
93353         }
93354         function asyncBodyVisitor(node) {
93355             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
93356                 switch (node.kind) {
93357                     case 236 /* VariableStatement */:
93358                         return visitVariableStatementInAsyncBody(node);
93359                     case 241 /* ForStatement */:
93360                         return visitForStatementInAsyncBody(node);
93361                     case 242 /* ForInStatement */:
93362                         return visitForInStatementInAsyncBody(node);
93363                     case 243 /* ForOfStatement */:
93364                         return visitForOfStatementInAsyncBody(node);
93365                     case 291 /* CatchClause */:
93366                         return visitCatchClauseInAsyncBody(node);
93367                     case 234 /* Block */:
93368                     case 248 /* SwitchStatement */:
93369                     case 262 /* CaseBlock */:
93370                     case 288 /* CaseClause */:
93371                     case 289 /* DefaultClause */:
93372                     case 251 /* TryStatement */:
93373                     case 239 /* DoStatement */:
93374                     case 240 /* WhileStatement */:
93375                     case 238 /* IfStatement */:
93376                     case 247 /* WithStatement */:
93377                     case 249 /* LabeledStatement */:
93378                         return ts.visitEachChild(node, asyncBodyVisitor, context);
93379                     default:
93380                         return ts.Debug.assertNever(node, "Unhandled node.");
93381                 }
93382             }
93383             return visitor(node);
93384         }
93385         function visitCatchClauseInAsyncBody(node) {
93386             var catchClauseNames = new ts.Set();
93387             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
93388             // names declared in a catch variable are block scoped
93389             var catchClauseUnshadowedNames;
93390             catchClauseNames.forEach(function (_, escapedName) {
93391                 if (enclosingFunctionParameterNames.has(escapedName)) {
93392                     if (!catchClauseUnshadowedNames) {
93393                         catchClauseUnshadowedNames = new ts.Set(enclosingFunctionParameterNames);
93394                     }
93395                     catchClauseUnshadowedNames.delete(escapedName);
93396                 }
93397             });
93398             if (catchClauseUnshadowedNames) {
93399                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
93400                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
93401                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
93402                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
93403                 return result;
93404             }
93405             else {
93406                 return ts.visitEachChild(node, asyncBodyVisitor, context);
93407             }
93408         }
93409         function visitVariableStatementInAsyncBody(node) {
93410             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
93411                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
93412                 return expression ? factory.createExpressionStatement(expression) : undefined;
93413             }
93414             return ts.visitEachChild(node, visitor, context);
93415         }
93416         function visitForInStatementInAsyncBody(node) {
93417             return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer)
93418                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
93419                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context));
93420         }
93421         function visitForOfStatementInAsyncBody(node) {
93422             return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
93423                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
93424                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context));
93425         }
93426         function visitForStatementInAsyncBody(node) {
93427             var initializer = node.initializer; // TODO: GH#18217
93428             return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer)
93429                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
93430                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context));
93431         }
93432         /**
93433          * Visits an AwaitExpression node.
93434          *
93435          * This function will be called any time a ES2017 await expression is encountered.
93436          *
93437          * @param node The node to visit.
93438          */
93439         function visitAwaitExpression(node) {
93440             // do not downlevel a top-level await as it is module syntax...
93441             if (inTopLevelContext()) {
93442                 return ts.visitEachChild(node, visitor, context);
93443             }
93444             return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
93445             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
93446         }
93447         /**
93448          * Visits a MethodDeclaration node.
93449          *
93450          * This function will be called when one of the following conditions are met:
93451          * - The node is marked as async
93452          *
93453          * @param node The node to visit.
93454          */
93455         function visitMethodDeclaration(node) {
93456             return factory.updateMethodDeclaration(node, 
93457             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
93458             /*questionToken*/ undefined, 
93459             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
93460             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
93461                 ? transformAsyncFunctionBody(node)
93462                 : ts.visitFunctionBody(node.body, visitor, context));
93463         }
93464         /**
93465          * Visits a FunctionDeclaration node.
93466          *
93467          * This function will be called when one of the following conditions are met:
93468          * - The node is marked async
93469          *
93470          * @param node The node to visit.
93471          */
93472         function visitFunctionDeclaration(node) {
93473             return factory.updateFunctionDeclaration(node, 
93474             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
93475             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
93476             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
93477                 ? transformAsyncFunctionBody(node)
93478                 : ts.visitFunctionBody(node.body, visitor, context));
93479         }
93480         /**
93481          * Visits a FunctionExpression node.
93482          *
93483          * This function will be called when one of the following conditions are met:
93484          * - The node is marked async
93485          *
93486          * @param node The node to visit.
93487          */
93488         function visitFunctionExpression(node) {
93489             return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
93490             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
93491             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
93492                 ? transformAsyncFunctionBody(node)
93493                 : ts.visitFunctionBody(node.body, visitor, context));
93494         }
93495         /**
93496          * Visits an ArrowFunction.
93497          *
93498          * This function will be called when one of the following conditions are met:
93499          * - The node is marked async
93500          *
93501          * @param node The node to visit.
93502          */
93503         function visitArrowFunction(node) {
93504             return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
93505             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
93506             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
93507                 ? transformAsyncFunctionBody(node)
93508                 : ts.visitFunctionBody(node.body, visitor, context));
93509         }
93510         function recordDeclarationName(_a, names) {
93511             var name = _a.name;
93512             if (ts.isIdentifier(name)) {
93513                 names.add(name.escapedText);
93514             }
93515             else {
93516                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
93517                     var element = _b[_i];
93518                     if (!ts.isOmittedExpression(element)) {
93519                         recordDeclarationName(element, names);
93520                     }
93521                 }
93522             }
93523         }
93524         function isVariableDeclarationListWithCollidingName(node) {
93525             return !!node
93526                 && ts.isVariableDeclarationList(node)
93527                 && !(node.flags & 3 /* BlockScoped */)
93528                 && node.declarations.some(collidesWithParameterName);
93529         }
93530         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
93531             hoistVariableDeclarationList(node);
93532             var variables = ts.getInitializedVariables(node);
93533             if (variables.length === 0) {
93534                 if (hasReceiver) {
93535                     return ts.visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
93536                 }
93537                 return undefined;
93538             }
93539             return factory.inlineExpressions(ts.map(variables, transformInitializedVariable));
93540         }
93541         function hoistVariableDeclarationList(node) {
93542             ts.forEach(node.declarations, hoistVariable);
93543         }
93544         function hoistVariable(_a) {
93545             var name = _a.name;
93546             if (ts.isIdentifier(name)) {
93547                 hoistVariableDeclaration(name);
93548             }
93549             else {
93550                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
93551                     var element = _b[_i];
93552                     if (!ts.isOmittedExpression(element)) {
93553                         hoistVariable(element);
93554                     }
93555                 }
93556             }
93557         }
93558         function transformInitializedVariable(node) {
93559             var converted = ts.setSourceMapRange(factory.createAssignment(factory.converters.convertToAssignmentElementTarget(node.name), node.initializer), node);
93560             return ts.visitNode(converted, visitor, ts.isExpression);
93561         }
93562         function collidesWithParameterName(_a) {
93563             var name = _a.name;
93564             if (ts.isIdentifier(name)) {
93565                 return enclosingFunctionParameterNames.has(name.escapedText);
93566             }
93567             else {
93568                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
93569                     var element = _b[_i];
93570                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
93571                         return true;
93572                     }
93573                 }
93574             }
93575             return false;
93576         }
93577         function transformAsyncFunctionBody(node) {
93578             resumeLexicalEnvironment();
93579             var original = ts.getOriginalNode(node, ts.isFunctionLike);
93580             var nodeType = original.type;
93581             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
93582             var isArrowFunction = node.kind === 213 /* ArrowFunction */;
93583             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
93584             // An async function is emit as an outer function that calls an inner
93585             // generator function. To preserve lexical bindings, we pass the current
93586             // `this` and `arguments` objects to `__awaiter`. The generator function
93587             // passed to `__awaiter` is executed inside of the callback to the
93588             // promise constructor.
93589             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
93590             enclosingFunctionParameterNames = new ts.Set();
93591             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
93592                 var parameter = _a[_i];
93593                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
93594             }
93595             var savedCapturedSuperProperties = capturedSuperProperties;
93596             var savedHasSuperElementAccess = hasSuperElementAccess;
93597             if (!isArrowFunction) {
93598                 capturedSuperProperties = new ts.Set();
93599                 hasSuperElementAccess = false;
93600             }
93601             var result;
93602             if (!isArrowFunction) {
93603                 var statements = [];
93604                 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
93605                 statements.push(factory.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
93606                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
93607                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
93608                 // This step isn't needed if we eventually transform this to ES5.
93609                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
93610                 if (emitSuperHelpers) {
93611                     enableSubstitutionForAsyncMethodsWithSuper();
93612                     if (capturedSuperProperties.size) {
93613                         var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
93614                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
93615                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
93616                     }
93617                 }
93618                 var block = factory.createBlock(statements, /*multiLine*/ true);
93619                 ts.setTextRange(block, node.body);
93620                 if (emitSuperHelpers && hasSuperElementAccess) {
93621                     // Emit helpers for super element access expressions (`super[x]`).
93622                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
93623                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
93624                     }
93625                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
93626                         ts.addEmitHelper(block, ts.asyncSuperHelper);
93627                     }
93628                 }
93629                 result = block;
93630             }
93631             else {
93632                 var expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
93633                 var declarations = endLexicalEnvironment();
93634                 if (ts.some(declarations)) {
93635                     var block = factory.converters.convertToFunctionBlock(expression);
93636                     result = factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
93637                 }
93638                 else {
93639                     result = expression;
93640                 }
93641             }
93642             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
93643             if (!isArrowFunction) {
93644                 capturedSuperProperties = savedCapturedSuperProperties;
93645                 hasSuperElementAccess = savedHasSuperElementAccess;
93646             }
93647             return result;
93648         }
93649         function transformAsyncFunctionBodyWorker(body, start) {
93650             if (ts.isBlock(body)) {
93651                 return factory.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
93652             }
93653             else {
93654                 return factory.converters.convertToFunctionBlock(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
93655             }
93656         }
93657         function getPromiseConstructor(type) {
93658             var typeName = type && ts.getEntityNameFromTypeNode(type);
93659             if (typeName && ts.isEntityName(typeName)) {
93660                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
93661                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
93662                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
93663                     return typeName;
93664                 }
93665             }
93666             return undefined;
93667         }
93668         function enableSubstitutionForAsyncMethodsWithSuper() {
93669             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
93670                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
93671                 // We need to enable substitutions for call, property access, and element access
93672                 // if we need to rewrite super calls.
93673                 context.enableSubstitution(207 /* CallExpression */);
93674                 context.enableSubstitution(205 /* PropertyAccessExpression */);
93675                 context.enableSubstitution(206 /* ElementAccessExpression */);
93676                 // We need to be notified when entering and exiting declarations that bind super.
93677                 context.enableEmitNotification(256 /* ClassDeclaration */);
93678                 context.enableEmitNotification(168 /* MethodDeclaration */);
93679                 context.enableEmitNotification(171 /* GetAccessor */);
93680                 context.enableEmitNotification(172 /* SetAccessor */);
93681                 context.enableEmitNotification(170 /* Constructor */);
93682                 // We need to be notified when entering the generated accessor arrow functions.
93683                 context.enableEmitNotification(236 /* VariableStatement */);
93684             }
93685         }
93686         /**
93687          * Hook for node emit.
93688          *
93689          * @param hint A hint as to the intended usage of the node.
93690          * @param node The node to emit.
93691          * @param emit A callback used to emit the node in the printer.
93692          */
93693         function onEmitNode(hint, node, emitCallback) {
93694             // If we need to support substitutions for `super` in an async method,
93695             // we should track it here.
93696             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
93697                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
93698                 if (superContainerFlags !== enclosingSuperContainerFlags) {
93699                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
93700                     enclosingSuperContainerFlags = superContainerFlags;
93701                     previousOnEmitNode(hint, node, emitCallback);
93702                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
93703                     return;
93704                 }
93705             }
93706             // Disable substitution in the generated super accessor itself.
93707             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
93708                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
93709                 enclosingSuperContainerFlags = 0;
93710                 previousOnEmitNode(hint, node, emitCallback);
93711                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
93712                 return;
93713             }
93714             previousOnEmitNode(hint, node, emitCallback);
93715         }
93716         /**
93717          * Hooks node substitutions.
93718          *
93719          * @param hint A hint as to the intended usage of the node.
93720          * @param node The node to substitute.
93721          */
93722         function onSubstituteNode(hint, node) {
93723             node = previousOnSubstituteNode(hint, node);
93724             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
93725                 return substituteExpression(node);
93726             }
93727             return node;
93728         }
93729         function substituteExpression(node) {
93730             switch (node.kind) {
93731                 case 205 /* PropertyAccessExpression */:
93732                     return substitutePropertyAccessExpression(node);
93733                 case 206 /* ElementAccessExpression */:
93734                     return substituteElementAccessExpression(node);
93735                 case 207 /* CallExpression */:
93736                     return substituteCallExpression(node);
93737             }
93738             return node;
93739         }
93740         function substitutePropertyAccessExpression(node) {
93741             if (node.expression.kind === 106 /* SuperKeyword */) {
93742                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
93743             }
93744             return node;
93745         }
93746         function substituteElementAccessExpression(node) {
93747             if (node.expression.kind === 106 /* SuperKeyword */) {
93748                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
93749             }
93750             return node;
93751         }
93752         function substituteCallExpression(node) {
93753             var expression = node.expression;
93754             if (ts.isSuperProperty(expression)) {
93755                 var argumentExpression = ts.isPropertyAccessExpression(expression)
93756                     ? substitutePropertyAccessExpression(expression)
93757                     : substituteElementAccessExpression(expression);
93758                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
93759                 /*typeArguments*/ undefined, __spreadArray([
93760                     factory.createThis()
93761                 ], node.arguments, true));
93762             }
93763             return node;
93764         }
93765         function isSuperContainer(node) {
93766             var kind = node.kind;
93767             return kind === 256 /* ClassDeclaration */
93768                 || kind === 170 /* Constructor */
93769                 || kind === 168 /* MethodDeclaration */
93770                 || kind === 171 /* GetAccessor */
93771                 || kind === 172 /* SetAccessor */;
93772         }
93773         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
93774             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
93775                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
93776                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
93777             }
93778             else {
93779                 return ts.setTextRange(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
93780                 /*typeArguments*/ undefined, [argumentExpression]), location);
93781             }
93782         }
93783     }
93784     ts.transformES2017 = transformES2017;
93785     /** Creates a variable named `_super` with accessor properties for the given property names. */
93786     function createSuperAccessVariableStatement(factory, resolver, node, names) {
93787         // Create a variable declaration with a getter/setter (if binding) definition for each name:
93788         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
93789         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
93790         var accessors = [];
93791         names.forEach(function (_, key) {
93792             var name = ts.unescapeLeadingUnderscores(key);
93793             var getterAndSetter = [];
93794             getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(
93795             /* modifiers */ undefined, 
93796             /* typeParameters */ undefined, 
93797             /* parameters */ [], 
93798             /* type */ undefined, 
93799             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
93800             if (hasBinding) {
93801                 getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(
93802                 /* modifiers */ undefined, 
93803                 /* typeParameters */ undefined, 
93804                 /* parameters */ [
93805                     factory.createParameterDeclaration(
93806                     /* decorators */ undefined, 
93807                     /* modifiers */ undefined, 
93808                     /* dotDotDotToken */ undefined, "v", 
93809                     /* questionToken */ undefined, 
93810                     /* type */ undefined, 
93811                     /* initializer */ undefined)
93812                 ], 
93813                 /* type */ undefined, 
93814                 /* equalsGreaterThanToken */ undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), factory.createIdentifier("v")))));
93815             }
93816             accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter)));
93817         });
93818         return factory.createVariableStatement(
93819         /* modifiers */ undefined, factory.createVariableDeclarationList([
93820             factory.createVariableDeclaration(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), 
93821             /*exclamationToken*/ undefined, 
93822             /* type */ undefined, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), 
93823             /* typeArguments */ undefined, [
93824                 factory.createNull(),
93825                 factory.createObjectLiteralExpression(accessors, /* multiline */ true)
93826             ]))
93827         ], 2 /* Const */));
93828     }
93829     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
93830 })(ts || (ts = {}));
93831 /*@internal*/
93832 var ts;
93833 (function (ts) {
93834     var ESNextSubstitutionFlags;
93835     (function (ESNextSubstitutionFlags) {
93836         /** Enables substitutions for async methods with `super` calls. */
93837         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
93838     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
93839     // Facts we track as we traverse the tree
93840     var HierarchyFacts;
93841     (function (HierarchyFacts) {
93842         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
93843         //
93844         // Ancestor facts
93845         //
93846         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
93847         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
93848         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
93849         //
93850         // Ancestor masks
93851         //
93852         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
93853         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
93854         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
93855         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
93856         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
93857         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
93858         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
93859         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
93860         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
93861         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
93862     })(HierarchyFacts || (HierarchyFacts = {}));
93863     function transformES2018(context) {
93864         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
93865         var resolver = context.getEmitResolver();
93866         var compilerOptions = context.getCompilerOptions();
93867         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93868         var previousOnEmitNode = context.onEmitNode;
93869         context.onEmitNode = onEmitNode;
93870         var previousOnSubstituteNode = context.onSubstituteNode;
93871         context.onSubstituteNode = onSubstituteNode;
93872         var exportedVariableStatement = false;
93873         var enabledSubstitutions;
93874         var enclosingFunctionFlags;
93875         var enclosingSuperContainerFlags = 0;
93876         var hierarchyFacts = 0;
93877         var currentSourceFile;
93878         var taggedTemplateStringDeclarations;
93879         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
93880         var capturedSuperProperties;
93881         /** Whether the async function contains an element access on super (`super[x]`). */
93882         var hasSuperElementAccess;
93883         /** A set of node IDs for generated super accessors. */
93884         var substitutedSuperAccessors = [];
93885         return ts.chainBundle(context, transformSourceFile);
93886         function affectsSubtree(excludeFacts, includeFacts) {
93887             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
93888         }
93889         /**
93890          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
93891          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
93892          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
93893          */
93894         function enterSubtree(excludeFacts, includeFacts) {
93895             var ancestorFacts = hierarchyFacts;
93896             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
93897             return ancestorFacts;
93898         }
93899         /**
93900          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
93901          * subtree.
93902          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
93903          */
93904         function exitSubtree(ancestorFacts) {
93905             hierarchyFacts = ancestorFacts;
93906         }
93907         function recordTaggedTemplateString(temp) {
93908             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
93909         }
93910         function transformSourceFile(node) {
93911             if (node.isDeclarationFile) {
93912                 return node;
93913             }
93914             currentSourceFile = node;
93915             var visited = visitSourceFile(node);
93916             ts.addEmitHelpers(visited, context.readEmitHelpers());
93917             currentSourceFile = undefined;
93918             taggedTemplateStringDeclarations = undefined;
93919             return visited;
93920         }
93921         function visitor(node) {
93922             return visitorWorker(node, /*expressionResultIsUnused*/ false);
93923         }
93924         function visitorWithUnusedExpressionResult(node) {
93925             return visitorWorker(node, /*expressionResultIsUnused*/ true);
93926         }
93927         function visitorNoAsyncModifier(node) {
93928             if (node.kind === 131 /* AsyncKeyword */) {
93929                 return undefined;
93930             }
93931             return node;
93932         }
93933         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
93934             if (affectsSubtree(excludeFacts, includeFacts)) {
93935                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
93936                 var result = cb(value);
93937                 exitSubtree(ancestorFacts);
93938                 return result;
93939             }
93940             return cb(value);
93941         }
93942         function visitDefault(node) {
93943             return ts.visitEachChild(node, visitor, context);
93944         }
93945         /**
93946          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
93947          * expression of an `ExpressionStatement`).
93948          */
93949         function visitorWorker(node, expressionResultIsUnused) {
93950             if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) {
93951                 return node;
93952             }
93953             switch (node.kind) {
93954                 case 217 /* AwaitExpression */:
93955                     return visitAwaitExpression(node);
93956                 case 223 /* YieldExpression */:
93957                     return visitYieldExpression(node);
93958                 case 246 /* ReturnStatement */:
93959                     return visitReturnStatement(node);
93960                 case 249 /* LabeledStatement */:
93961                     return visitLabeledStatement(node);
93962                 case 204 /* ObjectLiteralExpression */:
93963                     return visitObjectLiteralExpression(node);
93964                 case 220 /* BinaryExpression */:
93965                     return visitBinaryExpression(node, expressionResultIsUnused);
93966                 case 349 /* CommaListExpression */:
93967                     return visitCommaListExpression(node, expressionResultIsUnused);
93968                 case 291 /* CatchClause */:
93969                     return visitCatchClause(node);
93970                 case 236 /* VariableStatement */:
93971                     return visitVariableStatement(node);
93972                 case 253 /* VariableDeclaration */:
93973                     return visitVariableDeclaration(node);
93974                 case 239 /* DoStatement */:
93975                 case 240 /* WhileStatement */:
93976                 case 242 /* ForInStatement */:
93977                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
93978                 case 243 /* ForOfStatement */:
93979                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
93980                 case 241 /* ForStatement */:
93981                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
93982                 case 216 /* VoidExpression */:
93983                     return visitVoidExpression(node);
93984                 case 170 /* Constructor */:
93985                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93986                 case 168 /* MethodDeclaration */:
93987                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93988                 case 171 /* GetAccessor */:
93989                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93990                 case 172 /* SetAccessor */:
93991                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93992                 case 255 /* FunctionDeclaration */:
93993                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93994                 case 212 /* FunctionExpression */:
93995                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
93996                 case 213 /* ArrowFunction */:
93997                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
93998                 case 163 /* Parameter */:
93999                     return visitParameter(node);
94000                 case 237 /* ExpressionStatement */:
94001                     return visitExpressionStatement(node);
94002                 case 211 /* ParenthesizedExpression */:
94003                     return visitParenthesizedExpression(node, expressionResultIsUnused);
94004                 case 209 /* TaggedTemplateExpression */:
94005                     return visitTaggedTemplateExpression(node);
94006                 case 205 /* PropertyAccessExpression */:
94007                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 106 /* SuperKeyword */) {
94008                         capturedSuperProperties.add(node.name.escapedText);
94009                     }
94010                     return ts.visitEachChild(node, visitor, context);
94011                 case 206 /* ElementAccessExpression */:
94012                     if (capturedSuperProperties && node.expression.kind === 106 /* SuperKeyword */) {
94013                         hasSuperElementAccess = true;
94014                     }
94015                     return ts.visitEachChild(node, visitor, context);
94016                 case 256 /* ClassDeclaration */:
94017                 case 225 /* ClassExpression */:
94018                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
94019                 default:
94020                     return ts.visitEachChild(node, visitor, context);
94021             }
94022         }
94023         function visitAwaitExpression(node) {
94024             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
94025                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(ts.visitNode(node.expression, visitor, ts.isExpression))), 
94026                 /*location*/ node), node);
94027             }
94028             return ts.visitEachChild(node, visitor, context);
94029         }
94030         function visitYieldExpression(node) {
94031             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
94032                 if (node.asteriskToken) {
94033                     var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression);
94034                     return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
94035                     /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node);
94036                 }
94037                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
94038                 /*asteriskToken*/ undefined, createDownlevelAwait(node.expression
94039                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
94040                     : factory.createVoidZero())), node), node);
94041             }
94042             return ts.visitEachChild(node, visitor, context);
94043         }
94044         function visitReturnStatement(node) {
94045             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
94046                 return factory.updateReturnStatement(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : factory.createVoidZero()));
94047             }
94048             return ts.visitEachChild(node, visitor, context);
94049         }
94050         function visitLabeledStatement(node) {
94051             if (enclosingFunctionFlags & 2 /* Async */) {
94052                 var statement = ts.unwrapInnermostStatementOfLabel(node);
94053                 if (statement.kind === 243 /* ForOfStatement */ && statement.awaitModifier) {
94054                     return visitForOfStatement(statement, node);
94055                 }
94056                 return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node);
94057             }
94058             return ts.visitEachChild(node, visitor, context);
94059         }
94060         function chunkObjectLiteralElements(elements) {
94061             var chunkObject;
94062             var objects = [];
94063             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
94064                 var e = elements_4[_i];
94065                 if (e.kind === 296 /* SpreadAssignment */) {
94066                     if (chunkObject) {
94067                         objects.push(factory.createObjectLiteralExpression(chunkObject));
94068                         chunkObject = undefined;
94069                     }
94070                     var target = e.expression;
94071                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
94072                 }
94073                 else {
94074                     chunkObject = ts.append(chunkObject, e.kind === 294 /* PropertyAssignment */
94075                         ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
94076                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
94077                 }
94078             }
94079             if (chunkObject) {
94080                 objects.push(factory.createObjectLiteralExpression(chunkObject));
94081             }
94082             return objects;
94083         }
94084         function visitObjectLiteralExpression(node) {
94085             if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94086                 // spread elements emit like so:
94087                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
94088                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
94089                 // If the first element is a spread element, then the first argument to __assign is {}:
94090                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
94091                 //
94092                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
94093                 // example:
94094                 //      var k = { a: 1, b: 2 };
94095                 //      var o = { a: 3, ...k, b: k.a++ };
94096                 //      // expected: { a: 1, b: 1 }
94097                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
94098                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
94099                 //
94100                 // This also occurs for spread elements, not just property assignments:
94101                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
94102                 //      var l = { c: 3 };
94103                 //      var o = { ...k, ...l };
94104                 //      // expected: { a: 1, b: 2, z: 9 }
94105                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
94106                 // end up with `{ a: 1, b: 2, c: 3 }`
94107                 var objects = chunkObjectLiteralElements(node.properties);
94108                 if (objects.length && objects[0].kind !== 204 /* ObjectLiteralExpression */) {
94109                     objects.unshift(factory.createObjectLiteralExpression());
94110                 }
94111                 var expression = objects[0];
94112                 if (objects.length > 1) {
94113                     for (var i = 1; i < objects.length; i++) {
94114                         expression = emitHelpers().createAssignHelper([expression, objects[i]]);
94115                     }
94116                     return expression;
94117                 }
94118                 else {
94119                     return emitHelpers().createAssignHelper(objects);
94120                 }
94121             }
94122             return ts.visitEachChild(node, visitor, context);
94123         }
94124         function visitExpressionStatement(node) {
94125             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
94126         }
94127         /**
94128          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
94129          * expression of an `ExpressionStatement`).
94130          */
94131         function visitParenthesizedExpression(node, expressionResultIsUnused) {
94132             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
94133         }
94134         function visitSourceFile(node) {
94135             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
94136                 0 /* StrictModeSourceFileIncludes */ :
94137                 1 /* SourceFileIncludes */);
94138             exportedVariableStatement = false;
94139             var visited = ts.visitEachChild(node, visitor, context);
94140             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
94141                 factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
94142             ]);
94143             var result = factory.updateSourceFile(visited, ts.setTextRange(factory.createNodeArray(statement), node.statements));
94144             exitSubtree(ancestorFacts);
94145             return result;
94146         }
94147         function visitTaggedTemplateExpression(node) {
94148             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
94149         }
94150         /**
94151          * Visits a BinaryExpression that contains a destructuring assignment.
94152          *
94153          * @param node A BinaryExpression node.
94154          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
94155          * expression of an `ExpressionStatement`).
94156          */
94157         function visitBinaryExpression(node, expressionResultIsUnused) {
94158             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94159                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused);
94160             }
94161             if (node.operatorToken.kind === 27 /* CommaToken */) {
94162                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
94163             }
94164             return ts.visitEachChild(node, visitor, context);
94165         }
94166         /**
94167          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
94168          * expression of an `ExpressionStatement`).
94169          */
94170         function visitCommaListExpression(node, expressionResultIsUnused) {
94171             if (expressionResultIsUnused) {
94172                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
94173             }
94174             var result;
94175             for (var i = 0; i < node.elements.length; i++) {
94176                 var element = node.elements[i];
94177                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
94178                 if (result || visited !== element) {
94179                     result || (result = node.elements.slice(0, i));
94180                     result.push(visited);
94181                 }
94182             }
94183             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
94184             return factory.updateCommaListExpression(node, elements);
94185         }
94186         function visitCatchClause(node) {
94187             if (node.variableDeclaration &&
94188                 ts.isBindingPattern(node.variableDeclaration.name) &&
94189                 node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94190                 var name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
94191                 var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
94192                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
94193                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
94194                 if (ts.some(visitedBindings)) {
94195                     block = factory.updateBlock(block, __spreadArray([
94196                         factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
94197                     ], block.statements, true));
94198                 }
94199                 return factory.updateCatchClause(node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), block);
94200             }
94201             return ts.visitEachChild(node, visitor, context);
94202         }
94203         function visitVariableStatement(node) {
94204             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94205                 var savedExportedVariableStatement = exportedVariableStatement;
94206                 exportedVariableStatement = true;
94207                 var visited = ts.visitEachChild(node, visitor, context);
94208                 exportedVariableStatement = savedExportedVariableStatement;
94209                 return visited;
94210             }
94211             return ts.visitEachChild(node, visitor, context);
94212         }
94213         /**
94214          * Visits a VariableDeclaration node with a binding pattern.
94215          *
94216          * @param node A VariableDeclaration node.
94217          */
94218         function visitVariableDeclaration(node) {
94219             if (exportedVariableStatement) {
94220                 var savedExportedVariableStatement = exportedVariableStatement;
94221                 exportedVariableStatement = false;
94222                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
94223                 exportedVariableStatement = savedExportedVariableStatement;
94224                 return visited;
94225             }
94226             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
94227         }
94228         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
94229             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
94230             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94231                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
94232                 /*rval*/ undefined, exportedVariableStatement);
94233             }
94234             return ts.visitEachChild(node, visitor, context);
94235         }
94236         function visitForStatement(node) {
94237             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.visitIterationBody(node.statement, visitor, context));
94238         }
94239         function visitVoidExpression(node) {
94240             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
94241         }
94242         /**
94243          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
94244          *
94245          * @param node A ForOfStatement.
94246          */
94247         function visitForOfStatement(node, outermostLabeledStatement) {
94248             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
94249             if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94250                 node = transformForOfStatementWithObjectRest(node);
94251             }
94252             var result = node.awaitModifier ?
94253                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
94254                 factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
94255             exitSubtree(ancestorFacts);
94256             return result;
94257         }
94258         function transformForOfStatementWithObjectRest(node) {
94259             var initializerWithoutParens = ts.skipParentheses(node.initializer);
94260             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
94261                 var bodyLocation = void 0;
94262                 var statementsLocation = void 0;
94263                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
94264                 var statements = [ts.createForOfBindingStatement(factory, initializerWithoutParens, temp)];
94265                 if (ts.isBlock(node.statement)) {
94266                     ts.addRange(statements, node.statement.statements);
94267                     bodyLocation = node.statement;
94268                     statementsLocation = node.statement.statements;
94269                 }
94270                 else if (node.statement) {
94271                     ts.append(statements, node.statement);
94272                     bodyLocation = node.statement;
94273                     statementsLocation = node.statement;
94274                 }
94275                 return factory.updateForOfStatement(node, node.awaitModifier, ts.setTextRange(factory.createVariableDeclarationList([
94276                     ts.setTextRange(factory.createVariableDeclaration(temp), node.initializer)
94277                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
94278                 /*multiLine*/ true), bodyLocation));
94279             }
94280             return node;
94281         }
94282         function convertForOfStatementHead(node, boundValue) {
94283             var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue);
94284             var bodyLocation;
94285             var statementsLocation;
94286             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
94287             var statement = ts.visitIterationBody(node.statement, visitor, context);
94288             if (ts.isBlock(statement)) {
94289                 ts.addRange(statements, statement.statements);
94290                 bodyLocation = statement;
94291                 statementsLocation = statement.statements;
94292             }
94293             else {
94294                 statements.push(statement);
94295             }
94296             return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
94297             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
94298         }
94299         function createDownlevelAwait(expression) {
94300             return enclosingFunctionFlags & 1 /* Generator */
94301                 ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
94302                 : factory.createAwaitExpression(expression);
94303         }
94304         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
94305             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
94306             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
94307             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
94308             var errorRecord = factory.createUniqueName("e");
94309             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
94310             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
94311             var callValues = ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
94312             var callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
94313             var getDone = factory.createPropertyAccessExpression(result, "done");
94314             var getValue = factory.createPropertyAccessExpression(result, "value");
94315             var callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
94316             hoistVariableDeclaration(errorRecord);
94317             hoistVariableDeclaration(returnMethod);
94318             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
94319             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
94320                 factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
94321                 callValues;
94322             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
94323             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
94324                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
94325                 factory.createVariableDeclaration(result)
94326             ]), node.expression), 2097152 /* NoHoisting */), 
94327             /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), 
94328             /*incrementor*/ undefined, 
94329             /*statement*/ convertForOfStatementHead(node, getValue)), 
94330             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
94331             return factory.createTryStatement(factory.createBlock([
94332                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
94333             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
94334                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
94335                     factory.createPropertyAssignment("error", catchVariable)
94336                 ])))
94337             ]), 1 /* SingleLine */)), factory.createBlock([
94338                 factory.createTryStatement(
94339                 /*tryBlock*/ factory.createBlock([
94340                     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 */)
94341                 ]), 
94342                 /*catchClause*/ undefined, 
94343                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
94344                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
94345                 ]), 1 /* SingleLine */))
94346             ]));
94347         }
94348         function visitParameter(node) {
94349             if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94350                 // Binding patterns are converted into a generated name and are
94351                 // evaluated inside the function body.
94352                 return factory.updateParameterDeclaration(node, 
94353                 /*decorators*/ undefined, 
94354                 /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), 
94355                 /*questionToken*/ undefined, 
94356                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
94357             }
94358             return ts.visitEachChild(node, visitor, context);
94359         }
94360         function visitConstructorDeclaration(node) {
94361             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94362             enclosingFunctionFlags = 0 /* Normal */;
94363             var updated = factory.updateConstructorDeclaration(node, 
94364             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
94365             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94366             return updated;
94367         }
94368         function visitGetAccessorDeclaration(node) {
94369             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94370             enclosingFunctionFlags = 0 /* Normal */;
94371             var updated = factory.updateGetAccessorDeclaration(node, 
94372             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
94373             /*type*/ undefined, transformFunctionBody(node));
94374             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94375             return updated;
94376         }
94377         function visitSetAccessorDeclaration(node) {
94378             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94379             enclosingFunctionFlags = 0 /* Normal */;
94380             var updated = factory.updateSetAccessorDeclaration(node, 
94381             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
94382             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94383             return updated;
94384         }
94385         function visitMethodDeclaration(node) {
94386             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94387             enclosingFunctionFlags = ts.getFunctionFlags(node);
94388             var updated = factory.updateMethodDeclaration(node, 
94389             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
94390                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
94391                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
94392                 ? undefined
94393                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
94394             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
94395             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
94396                 ? transformAsyncGeneratorFunctionBody(node)
94397                 : transformFunctionBody(node));
94398             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94399             return updated;
94400         }
94401         function visitFunctionDeclaration(node) {
94402             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94403             enclosingFunctionFlags = ts.getFunctionFlags(node);
94404             var updated = factory.updateFunctionDeclaration(node, 
94405             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
94406                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
94407                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
94408                 ? undefined
94409                 : node.asteriskToken, node.name, 
94410             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
94411             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
94412                 ? transformAsyncGeneratorFunctionBody(node)
94413                 : transformFunctionBody(node));
94414             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94415             return updated;
94416         }
94417         function visitArrowFunction(node) {
94418             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94419             enclosingFunctionFlags = ts.getFunctionFlags(node);
94420             var updated = factory.updateArrowFunction(node, node.modifiers, 
94421             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
94422             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
94423             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94424             return updated;
94425         }
94426         function visitFunctionExpression(node) {
94427             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
94428             enclosingFunctionFlags = ts.getFunctionFlags(node);
94429             var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
94430                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
94431                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
94432                 ? undefined
94433                 : node.asteriskToken, node.name, 
94434             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
94435             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
94436                 ? transformAsyncGeneratorFunctionBody(node)
94437                 : transformFunctionBody(node));
94438             enclosingFunctionFlags = savedEnclosingFunctionFlags;
94439             return updated;
94440         }
94441         function transformAsyncGeneratorFunctionBody(node) {
94442             resumeLexicalEnvironment();
94443             var statements = [];
94444             var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
94445             appendObjectRestAssignmentsIfNeeded(statements, node);
94446             var savedCapturedSuperProperties = capturedSuperProperties;
94447             var savedHasSuperElementAccess = hasSuperElementAccess;
94448             capturedSuperProperties = new ts.Set();
94449             hasSuperElementAccess = false;
94450             var returnStatement = factory.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory.createFunctionExpression(
94451             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), node.name && factory.getGeneratedNameForNode(node.name), 
94452             /*typeParameters*/ undefined, 
94453             /*parameters*/ [], 
94454             /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
94455             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
94456             // This step isn't needed if we eventually transform this to ES5.
94457             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
94458             if (emitSuperHelpers) {
94459                 enableSubstitutionForAsyncMethodsWithSuper();
94460                 var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
94461                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
94462                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
94463             }
94464             statements.push(returnStatement);
94465             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
94466             var block = factory.updateBlock(node.body, statements);
94467             if (emitSuperHelpers && hasSuperElementAccess) {
94468                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
94469                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
94470                 }
94471                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
94472                     ts.addEmitHelper(block, ts.asyncSuperHelper);
94473                 }
94474             }
94475             capturedSuperProperties = savedCapturedSuperProperties;
94476             hasSuperElementAccess = savedHasSuperElementAccess;
94477             return block;
94478         }
94479         function transformFunctionBody(node) {
94480             var _a;
94481             resumeLexicalEnvironment();
94482             var statementOffset = 0;
94483             var statements = [];
94484             var body = (_a = ts.visitNode(node.body, visitor, ts.isConciseBody)) !== null && _a !== void 0 ? _a : factory.createBlock([]);
94485             if (ts.isBlock(body)) {
94486                 statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
94487             }
94488             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
94489             var leadingStatements = endLexicalEnvironment();
94490             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
94491                 var block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
94492                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
94493                 ts.addRange(statements, block.statements.slice(statementOffset));
94494                 return factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(statements), block.statements));
94495             }
94496             return body;
94497         }
94498         function appendObjectRestAssignmentsIfNeeded(statements, node) {
94499             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
94500                 var parameter = _a[_i];
94501                 if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) {
94502                     var temp = factory.getGeneratedNameForNode(parameter);
94503                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
94504                     /*doNotRecordTempVariablesInLine*/ false, 
94505                     /*skipInitializer*/ true);
94506                     if (ts.some(declarations)) {
94507                         var statement = factory.createVariableStatement(
94508                         /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations));
94509                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94510                         statements = ts.append(statements, statement);
94511                     }
94512                 }
94513             }
94514             return statements;
94515         }
94516         function enableSubstitutionForAsyncMethodsWithSuper() {
94517             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
94518                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
94519                 // We need to enable substitutions for call, property access, and element access
94520                 // if we need to rewrite super calls.
94521                 context.enableSubstitution(207 /* CallExpression */);
94522                 context.enableSubstitution(205 /* PropertyAccessExpression */);
94523                 context.enableSubstitution(206 /* ElementAccessExpression */);
94524                 // We need to be notified when entering and exiting declarations that bind super.
94525                 context.enableEmitNotification(256 /* ClassDeclaration */);
94526                 context.enableEmitNotification(168 /* MethodDeclaration */);
94527                 context.enableEmitNotification(171 /* GetAccessor */);
94528                 context.enableEmitNotification(172 /* SetAccessor */);
94529                 context.enableEmitNotification(170 /* Constructor */);
94530                 // We need to be notified when entering the generated accessor arrow functions.
94531                 context.enableEmitNotification(236 /* VariableStatement */);
94532             }
94533         }
94534         /**
94535          * Called by the printer just before a node is printed.
94536          *
94537          * @param hint A hint as to the intended usage of the node.
94538          * @param node The node to be printed.
94539          * @param emitCallback The callback used to emit the node.
94540          */
94541         function onEmitNode(hint, node, emitCallback) {
94542             // If we need to support substitutions for `super` in an async method,
94543             // we should track it here.
94544             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
94545                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
94546                 if (superContainerFlags !== enclosingSuperContainerFlags) {
94547                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
94548                     enclosingSuperContainerFlags = superContainerFlags;
94549                     previousOnEmitNode(hint, node, emitCallback);
94550                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
94551                     return;
94552                 }
94553             }
94554             // Disable substitution in the generated super accessor itself.
94555             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
94556                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
94557                 enclosingSuperContainerFlags = 0;
94558                 previousOnEmitNode(hint, node, emitCallback);
94559                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
94560                 return;
94561             }
94562             previousOnEmitNode(hint, node, emitCallback);
94563         }
94564         /**
94565          * Hooks node substitutions.
94566          *
94567          * @param hint The context for the emitter.
94568          * @param node The node to substitute.
94569          */
94570         function onSubstituteNode(hint, node) {
94571             node = previousOnSubstituteNode(hint, node);
94572             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
94573                 return substituteExpression(node);
94574             }
94575             return node;
94576         }
94577         function substituteExpression(node) {
94578             switch (node.kind) {
94579                 case 205 /* PropertyAccessExpression */:
94580                     return substitutePropertyAccessExpression(node);
94581                 case 206 /* ElementAccessExpression */:
94582                     return substituteElementAccessExpression(node);
94583                 case 207 /* CallExpression */:
94584                     return substituteCallExpression(node);
94585             }
94586             return node;
94587         }
94588         function substitutePropertyAccessExpression(node) {
94589             if (node.expression.kind === 106 /* SuperKeyword */) {
94590                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
94591             }
94592             return node;
94593         }
94594         function substituteElementAccessExpression(node) {
94595             if (node.expression.kind === 106 /* SuperKeyword */) {
94596                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
94597             }
94598             return node;
94599         }
94600         function substituteCallExpression(node) {
94601             var expression = node.expression;
94602             if (ts.isSuperProperty(expression)) {
94603                 var argumentExpression = ts.isPropertyAccessExpression(expression)
94604                     ? substitutePropertyAccessExpression(expression)
94605                     : substituteElementAccessExpression(expression);
94606                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
94607                 /*typeArguments*/ undefined, __spreadArray([
94608                     factory.createThis()
94609                 ], node.arguments, true));
94610             }
94611             return node;
94612         }
94613         function isSuperContainer(node) {
94614             var kind = node.kind;
94615             return kind === 256 /* ClassDeclaration */
94616                 || kind === 170 /* Constructor */
94617                 || kind === 168 /* MethodDeclaration */
94618                 || kind === 171 /* GetAccessor */
94619                 || kind === 172 /* SetAccessor */;
94620         }
94621         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
94622             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
94623                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
94624                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
94625             }
94626             else {
94627                 return ts.setTextRange(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
94628                 /*typeArguments*/ undefined, [argumentExpression]), location);
94629             }
94630         }
94631     }
94632     ts.transformES2018 = transformES2018;
94633 })(ts || (ts = {}));
94634 /*@internal*/
94635 var ts;
94636 (function (ts) {
94637     function transformES2019(context) {
94638         var factory = context.factory;
94639         return ts.chainBundle(context, transformSourceFile);
94640         function transformSourceFile(node) {
94641             if (node.isDeclarationFile) {
94642                 return node;
94643             }
94644             return ts.visitEachChild(node, visitor, context);
94645         }
94646         function visitor(node) {
94647             if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) {
94648                 return node;
94649             }
94650             switch (node.kind) {
94651                 case 291 /* CatchClause */:
94652                     return visitCatchClause(node);
94653                 default:
94654                     return ts.visitEachChild(node, visitor, context);
94655             }
94656         }
94657         function visitCatchClause(node) {
94658             if (!node.variableDeclaration) {
94659                 return factory.updateCatchClause(node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
94660             }
94661             return ts.visitEachChild(node, visitor, context);
94662         }
94663     }
94664     ts.transformES2019 = transformES2019;
94665 })(ts || (ts = {}));
94666 /*@internal*/
94667 var ts;
94668 (function (ts) {
94669     function transformES2020(context) {
94670         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
94671         return ts.chainBundle(context, transformSourceFile);
94672         function transformSourceFile(node) {
94673             if (node.isDeclarationFile) {
94674                 return node;
94675             }
94676             return ts.visitEachChild(node, visitor, context);
94677         }
94678         function visitor(node) {
94679             if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) {
94680                 return node;
94681             }
94682             switch (node.kind) {
94683                 case 207 /* CallExpression */: {
94684                     var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false);
94685                     ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
94686                     return updated;
94687                 }
94688                 case 205 /* PropertyAccessExpression */:
94689                 case 206 /* ElementAccessExpression */:
94690                     if (ts.isOptionalChain(node)) {
94691                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
94692                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
94693                         return updated;
94694                     }
94695                     return ts.visitEachChild(node, visitor, context);
94696                 case 220 /* BinaryExpression */:
94697                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
94698                         return transformNullishCoalescingExpression(node);
94699                     }
94700                     return ts.visitEachChild(node, visitor, context);
94701                 case 214 /* DeleteExpression */:
94702                     return visitDeleteExpression(node);
94703                 default:
94704                     return ts.visitEachChild(node, visitor, context);
94705             }
94706         }
94707         function flattenChain(chain) {
94708             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
94709             var links = [chain];
94710             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
94711                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
94712                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
94713                 links.unshift(chain);
94714             }
94715             return { expression: chain.expression, chain: links };
94716         }
94717         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
94718             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
94719             if (ts.isSyntheticReference(expression)) {
94720                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
94721                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
94722                 return factory.createSyntheticReferenceExpression(factory.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
94723             }
94724             return factory.updateParenthesizedExpression(node, expression);
94725         }
94726         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
94727             if (ts.isOptionalChain(node)) {
94728                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
94729                 return visitOptionalExpression(node, captureThisArg, isDelete);
94730             }
94731             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
94732             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
94733             var thisArg;
94734             if (captureThisArg) {
94735                 if (!ts.isSimpleCopiableExpression(expression)) {
94736                     thisArg = factory.createTempVariable(hoistVariableDeclaration);
94737                     expression = factory.createAssignment(thisArg, expression);
94738                 }
94739                 else {
94740                     thisArg = expression;
94741                 }
94742             }
94743             expression = node.kind === 205 /* PropertyAccessExpression */
94744                 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
94745                 : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
94746             return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression;
94747         }
94748         function visitNonOptionalCallExpression(node, captureThisArg) {
94749             if (ts.isOptionalChain(node)) {
94750                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
94751                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
94752             }
94753             if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) {
94754                 // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()`
94755                 var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false);
94756                 var args = ts.visitNodes(node.arguments, visitor, ts.isExpression);
94757                 if (ts.isSyntheticReference(expression)) {
94758                     return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node);
94759                 }
94760                 return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args);
94761             }
94762             return ts.visitEachChild(node, visitor, context);
94763         }
94764         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
94765             switch (node.kind) {
94766                 case 211 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
94767                 case 205 /* PropertyAccessExpression */:
94768                 case 206 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
94769                 case 207 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
94770                 default: return ts.visitNode(node, visitor, ts.isExpression);
94771             }
94772         }
94773         function visitOptionalExpression(node, captureThisArg, isDelete) {
94774             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
94775             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
94776             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
94777             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
94778             var capturedLeft = leftExpression;
94779             if (!ts.isSimpleCopiableExpression(leftExpression)) {
94780                 capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
94781                 leftExpression = factory.createAssignment(capturedLeft, leftExpression);
94782             }
94783             var rightExpression = capturedLeft;
94784             var thisArg;
94785             for (var i = 0; i < chain.length; i++) {
94786                 var segment = chain[i];
94787                 switch (segment.kind) {
94788                     case 205 /* PropertyAccessExpression */:
94789                     case 206 /* ElementAccessExpression */:
94790                         if (i === chain.length - 1 && captureThisArg) {
94791                             if (!ts.isSimpleCopiableExpression(rightExpression)) {
94792                                 thisArg = factory.createTempVariable(hoistVariableDeclaration);
94793                                 rightExpression = factory.createAssignment(thisArg, rightExpression);
94794                             }
94795                             else {
94796                                 thisArg = rightExpression;
94797                             }
94798                         }
94799                         rightExpression = segment.kind === 205 /* PropertyAccessExpression */
94800                             ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
94801                             : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
94802                         break;
94803                     case 207 /* CallExpression */:
94804                         if (i === 0 && leftThisArg) {
94805                             rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 106 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
94806                         }
94807                         else {
94808                             rightExpression = factory.createCallExpression(rightExpression, 
94809                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
94810                         }
94811                         break;
94812                 }
94813                 ts.setOriginalNode(rightExpression, segment);
94814             }
94815             var target = isDelete
94816                 ? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
94817                 : factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
94818             ts.setTextRange(target, node);
94819             return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
94820         }
94821         function createNotNullCondition(left, right, invert) {
94822             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()));
94823         }
94824         function transformNullishCoalescingExpression(node) {
94825             var left = ts.visitNode(node.left, visitor, ts.isExpression);
94826             var right = left;
94827             if (!ts.isSimpleCopiableExpression(left)) {
94828                 right = factory.createTempVariable(hoistVariableDeclaration);
94829                 left = factory.createAssignment(right, left);
94830             }
94831             return ts.setTextRange(factory.createConditionalExpression(createNotNullCondition(left, right), 
94832             /*questionToken*/ undefined, right, 
94833             /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression)), node);
94834         }
94835         function visitDeleteExpression(node) {
94836             return ts.isOptionalChain(ts.skipParentheses(node.expression))
94837                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
94838                 : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression));
94839         }
94840     }
94841     ts.transformES2020 = transformES2020;
94842 })(ts || (ts = {}));
94843 /*@internal*/
94844 var ts;
94845 (function (ts) {
94846     function transformES2021(context) {
94847         var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory;
94848         return ts.chainBundle(context, transformSourceFile);
94849         function transformSourceFile(node) {
94850             if (node.isDeclarationFile) {
94851                 return node;
94852             }
94853             return ts.visitEachChild(node, visitor, context);
94854         }
94855         function visitor(node) {
94856             if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) {
94857                 return node;
94858             }
94859             switch (node.kind) {
94860                 case 220 /* BinaryExpression */:
94861                     var binaryExpression = node;
94862                     if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
94863                         return transformLogicalAssignment(binaryExpression);
94864                     }
94865                 // falls through
94866                 default:
94867                     return ts.visitEachChild(node, visitor, context);
94868             }
94869         }
94870         function transformLogicalAssignment(binaryExpression) {
94871             var operator = binaryExpression.operatorToken;
94872             var nonAssignmentOperator = ts.getNonAssignmentOperatorForCompoundAssignment(operator.kind);
94873             var left = ts.skipParentheses(ts.visitNode(binaryExpression.left, visitor, ts.isLeftHandSideExpression));
94874             var assignmentTarget = left;
94875             var right = ts.skipParentheses(ts.visitNode(binaryExpression.right, visitor, ts.isExpression));
94876             if (ts.isAccessExpression(left)) {
94877                 var propertyAccessTargetSimpleCopiable = ts.isSimpleCopiableExpression(left.expression);
94878                 var propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression :
94879                     factory.createTempVariable(hoistVariableDeclaration);
94880                 var propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment(propertyAccessTarget, left.expression);
94881                 if (ts.isPropertyAccessExpression(left)) {
94882                     assignmentTarget = factory.createPropertyAccessExpression(propertyAccessTarget, left.name);
94883                     left = factory.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name);
94884                 }
94885                 else {
94886                     var elementAccessArgumentSimpleCopiable = ts.isSimpleCopiableExpression(left.argumentExpression);
94887                     var elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression :
94888                         factory.createTempVariable(hoistVariableDeclaration);
94889                     assignmentTarget = factory.createElementAccessExpression(propertyAccessTarget, elementAccessArgument);
94890                     left = factory.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment(elementAccessArgument, left.argumentExpression));
94891                 }
94892             }
94893             return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right)));
94894         }
94895     }
94896     ts.transformES2021 = transformES2021;
94897 })(ts || (ts = {}));
94898 /*@internal*/
94899 var ts;
94900 (function (ts) {
94901     function transformESNext(context) {
94902         return ts.chainBundle(context, transformSourceFile);
94903         function transformSourceFile(node) {
94904             if (node.isDeclarationFile) {
94905                 return node;
94906             }
94907             return ts.visitEachChild(node, visitor, context);
94908         }
94909         function visitor(node) {
94910             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
94911                 return node;
94912             }
94913             switch (node.kind) {
94914                 default:
94915                     return ts.visitEachChild(node, visitor, context);
94916             }
94917         }
94918     }
94919     ts.transformESNext = transformESNext;
94920 })(ts || (ts = {}));
94921 /*@internal*/
94922 var ts;
94923 (function (ts) {
94924     function transformJsx(context) {
94925         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
94926         var compilerOptions = context.getCompilerOptions();
94927         var currentSourceFile;
94928         var currentFileState;
94929         return ts.chainBundle(context, transformSourceFile);
94930         function getCurrentFileNameExpression() {
94931             if (currentFileState.filenameDeclaration) {
94932                 return currentFileState.filenameDeclaration.name;
94933             }
94934             var declaration = factory.createVariableDeclaration(factory.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclaimationToken*/ undefined, /*type*/ undefined, factory.createStringLiteral(currentSourceFile.fileName));
94935             currentFileState.filenameDeclaration = declaration;
94936             return currentFileState.filenameDeclaration.name;
94937         }
94938         function getJsxFactoryCalleePrimitive(isStaticChildren) {
94939             return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx";
94940         }
94941         function getJsxFactoryCallee(isStaticChildren) {
94942             var type = getJsxFactoryCalleePrimitive(isStaticChildren);
94943             return getImplicitImportForName(type);
94944         }
94945         function getImplicitJsxFragmentReference() {
94946             return getImplicitImportForName("Fragment");
94947         }
94948         function getImplicitImportForName(name) {
94949             var _a, _b;
94950             var importSource = name === "createElement"
94951                 ? currentFileState.importSpecifier
94952                 : ts.getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions);
94953             var existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) === null || _a === void 0 ? void 0 : _a.get(importSource)) === null || _b === void 0 ? void 0 : _b.get(name);
94954             if (existing) {
94955                 return existing.name;
94956             }
94957             if (!currentFileState.utilizedImplicitRuntimeImports) {
94958                 currentFileState.utilizedImplicitRuntimeImports = ts.createMap();
94959             }
94960             var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
94961             if (!specifierSourceImports) {
94962                 specifierSourceImports = ts.createMap();
94963                 currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
94964             }
94965             var generatedName = factory.createUniqueName("_".concat(name), 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */);
94966             var specifier = factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier(name), generatedName);
94967             generatedName.generatedImportReference = specifier;
94968             specifierSourceImports.set(name, specifier);
94969             return generatedName;
94970         }
94971         /**
94972          * Transform JSX-specific syntax in a SourceFile.
94973          *
94974          * @param node A SourceFile node.
94975          */
94976         function transformSourceFile(node) {
94977             if (node.isDeclarationFile) {
94978                 return node;
94979             }
94980             currentSourceFile = node;
94981             currentFileState = {};
94982             currentFileState.importSpecifier = ts.getJSXImplicitImportBase(compilerOptions, node);
94983             var visited = ts.visitEachChild(node, visitor, context);
94984             ts.addEmitHelpers(visited, context.readEmitHelpers());
94985             var statements = visited.statements;
94986             if (currentFileState.filenameDeclaration) {
94987                 statements = ts.insertStatementAfterCustomPrologue(statements.slice(), factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */)));
94988             }
94989             if (currentFileState.utilizedImplicitRuntimeImports) {
94990                 for (var _i = 0, _a = ts.arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries()); _i < _a.length; _i++) {
94991                     var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1];
94992                     if (ts.isExternalModule(node)) {
94993                         // Add `import` statement
94994                         var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined);
94995                         ts.setParentRecursive(importStatement, /*incremental*/ false);
94996                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement);
94997                     }
94998                     else if (ts.isExternalOrCommonJsModule(node)) {
94999                         // Add `require` statement
95000                         var requireStatement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([
95001                             factory.createVariableDeclaration(factory.createObjectBindingPattern(ts.map(ts.arrayFrom(importSpecifiersMap.values()), function (s) { return factory.createBindingElement(/*dotdotdot*/ undefined, s.propertyName, s.name); })), 
95002                             /*exclaimationToken*/ undefined, 
95003                             /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]))
95004                         ], 2 /* Const */));
95005                         ts.setParentRecursive(requireStatement, /*incremental*/ false);
95006                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), requireStatement);
95007                     }
95008                     else {
95009                         // Do nothing (script file) - consider an error in the checker?
95010                     }
95011                 }
95012             }
95013             if (statements !== visited.statements) {
95014                 visited = factory.updateSourceFile(visited, statements);
95015             }
95016             currentFileState = undefined;
95017             return visited;
95018         }
95019         function visitor(node) {
95020             if (node.transformFlags & 2 /* ContainsJsx */) {
95021                 return visitorWorker(node);
95022             }
95023             else {
95024                 return node;
95025             }
95026         }
95027         function visitorWorker(node) {
95028             switch (node.kind) {
95029                 case 277 /* JsxElement */:
95030                     return visitJsxElement(node, /*isChild*/ false);
95031                 case 278 /* JsxSelfClosingElement */:
95032                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
95033                 case 281 /* JsxFragment */:
95034                     return visitJsxFragment(node, /*isChild*/ false);
95035                 case 287 /* JsxExpression */:
95036                     return visitJsxExpression(node);
95037                 default:
95038                     return ts.visitEachChild(node, visitor, context);
95039             }
95040         }
95041         function transformJsxChildToExpression(node) {
95042             switch (node.kind) {
95043                 case 11 /* JsxText */:
95044                     return visitJsxText(node);
95045                 case 287 /* JsxExpression */:
95046                     return visitJsxExpression(node);
95047                 case 277 /* JsxElement */:
95048                     return visitJsxElement(node, /*isChild*/ true);
95049                 case 278 /* JsxSelfClosingElement */:
95050                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
95051                 case 281 /* JsxFragment */:
95052                     return visitJsxFragment(node, /*isChild*/ true);
95053                 default:
95054                     return ts.Debug.failBadSyntaxKind(node);
95055             }
95056         }
95057         /**
95058          * The react jsx/jsxs transform falls back to `createElement` when an explicit `key` argument comes after a spread
95059          */
95060         function hasKeyAfterPropsSpread(node) {
95061             var spread = false;
95062             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
95063                 var elem = _a[_i];
95064                 if (ts.isJsxSpreadAttribute(elem)) {
95065                     spread = true;
95066                 }
95067                 else if (spread && ts.isJsxAttribute(elem) && elem.name.escapedText === "key") {
95068                     return true;
95069                 }
95070             }
95071             return false;
95072         }
95073         function shouldUseCreateElement(node) {
95074             return currentFileState.importSpecifier === undefined || hasKeyAfterPropsSpread(node);
95075         }
95076         function visitJsxElement(node, isChild) {
95077             var tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
95078             return tagTransform(node.openingElement, node.children, isChild, /*location*/ node);
95079         }
95080         function visitJsxSelfClosingElement(node, isChild) {
95081             var tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
95082             return tagTransform(node, /*children*/ undefined, isChild, /*location*/ node);
95083         }
95084         function visitJsxFragment(node, isChild) {
95085             var tagTransform = currentFileState.importSpecifier === undefined ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX;
95086             return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node);
95087         }
95088         function convertJsxChildrenToChildrenPropObject(children) {
95089             var prop = convertJsxChildrenToChildrenPropAssignment(children);
95090             return prop && factory.createObjectLiteralExpression([prop]);
95091         }
95092         function convertJsxChildrenToChildrenPropAssignment(children) {
95093             var nonWhitespaceChildren = ts.getSemanticJsxChildren(children);
95094             if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) {
95095                 var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]);
95096                 return result_12 && factory.createPropertyAssignment("children", result_12);
95097             }
95098             var result = ts.mapDefined(children, transformJsxChildToExpression);
95099             return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined;
95100         }
95101         function visitJsxOpeningLikeElementJSX(node, children, isChild, location) {
95102             var tagName = getTagName(node);
95103             var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined;
95104             var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; });
95105             var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties;
95106             var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) :
95107                 factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {}
95108             return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location);
95109         }
95110         function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) {
95111             var _a;
95112             var nonWhitespaceChildren = ts.getSemanticJsxChildren(children);
95113             var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken);
95114             var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
95115             if (compilerOptions.jsx === 5 /* ReactJSXDev */) {
95116                 var originalFile = ts.getOriginalNode(currentSourceFile);
95117                 if (originalFile && ts.isSourceFile(originalFile)) {
95118                     // isStaticChildren development flag
95119                     args.push(isStaticChildren ? factory.createTrue() : factory.createFalse());
95120                     // __source development flag
95121                     var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos);
95122                     args.push(factory.createObjectLiteralExpression([
95123                         factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()),
95124                         factory.createPropertyAssignment("lineNumber", factory.createNumericLiteral(lineCol.line + 1)),
95125                         factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1))
95126                     ]));
95127                     // __self development flag
95128                     args.push(factory.createThis());
95129                 }
95130             }
95131             var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location);
95132             if (isChild) {
95133                 ts.startOnNewLine(element);
95134             }
95135             return element;
95136         }
95137         function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) {
95138             var tagName = getTagName(node);
95139             var attrs = node.attributes.properties;
95140             var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) :
95141                 factory.createNull(); // When there are no attributes, React wants "null"
95142             var callee = currentFileState.importSpecifier === undefined
95143                 ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
95144                 node)
95145                 : getImplicitImportForName("createElement");
95146             var element = ts.createExpressionForJsxElement(factory, callee, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), location);
95147             if (isChild) {
95148                 ts.startOnNewLine(element);
95149             }
95150             return element;
95151         }
95152         function visitJsxOpeningFragmentJSX(_node, children, isChild, location) {
95153             var childrenProps;
95154             if (children && children.length) {
95155                 var result = convertJsxChildrenToChildrenPropObject(children);
95156                 if (result) {
95157                     childrenProps = result;
95158                 }
95159             }
95160             return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), 
95161             /*keyAttr*/ undefined, children, isChild, location);
95162         }
95163         function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) {
95164             var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
95165             ts.mapDefined(children, transformJsxChildToExpression), node, location);
95166             if (isChild) {
95167                 ts.startOnNewLine(element);
95168             }
95169             return element;
95170         }
95171         function transformJsxSpreadAttributeToSpreadAssignment(node) {
95172             return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression));
95173         }
95174         function transformJsxAttributesToObjectProps(attrs, children) {
95175             var target = ts.getEmitScriptTarget(compilerOptions);
95176             return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) :
95177                 transformJsxAttributesToExpression(attrs, children);
95178         }
95179         function transformJsxAttributesToProps(attrs, children) {
95180             var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) {
95181                 return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); });
95182             }));
95183             if (children) {
95184                 props.push(children);
95185             }
95186             return props;
95187         }
95188         function transformJsxAttributesToExpression(attrs, children) {
95189             // Map spans of JsxAttribute nodes into object literals and spans
95190             // of JsxSpreadAttribute nodes into expressions.
95191             var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
95192                 ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
95193                 : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
95194             if (ts.isJsxSpreadAttribute(attrs[0])) {
95195                 // We must always emit at least one object literal before a spread
95196                 // argument.factory.createObjectLiteral
95197                 expressions.unshift(factory.createObjectLiteralExpression());
95198             }
95199             if (children) {
95200                 expressions.push(factory.createObjectLiteralExpression([children]));
95201             }
95202             return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions);
95203         }
95204         function transformJsxSpreadAttributeToExpression(node) {
95205             return ts.visitNode(node.expression, visitor, ts.isExpression);
95206         }
95207         function transformJsxAttributeToObjectLiteralElement(node) {
95208             var name = getAttributeName(node);
95209             var expression = transformJsxAttributeInitializer(node.initializer);
95210             return factory.createPropertyAssignment(name, expression);
95211         }
95212         function transformJsxAttributeInitializer(node) {
95213             if (node === undefined) {
95214                 return factory.createTrue();
95215             }
95216             else if (node.kind === 10 /* StringLiteral */) {
95217                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
95218                 // Need to be escaped to be handled correctly in a normal string
95219                 var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
95220                 var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
95221                 return ts.setTextRange(literal, node);
95222             }
95223             else if (node.kind === 287 /* JsxExpression */) {
95224                 if (node.expression === undefined) {
95225                     return factory.createTrue();
95226                 }
95227                 return ts.visitNode(node.expression, visitor, ts.isExpression);
95228             }
95229             else {
95230                 return ts.Debug.failBadSyntaxKind(node);
95231             }
95232         }
95233         function visitJsxText(node) {
95234             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
95235             return fixed === undefined ? undefined : factory.createStringLiteral(fixed);
95236         }
95237         /**
95238          * JSX trims whitespace at the end and beginning of lines, except that the
95239          * start/end of a tag is considered a start/end of a line only if that line is
95240          * on the same line as the closing tag. See examples in
95241          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
95242          * 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
95243          *
95244          * An equivalent algorithm would be:
95245          * - If there is only one line, return it.
95246          * - If there is only whitespace (but multiple lines), return `undefined`.
95247          * - Split the text into lines.
95248          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
95249          * - Decode entities on each line (individually).
95250          * - Remove empty lines and join the rest with " ".
95251          */
95252         function fixupWhitespaceAndDecodeEntities(text) {
95253             var acc;
95254             // First non-whitespace character on this line.
95255             var firstNonWhitespace = 0;
95256             // Last non-whitespace character on this line.
95257             var lastNonWhitespace = -1;
95258             // These initial values are special because the first line is:
95259             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
95260             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
95261             for (var i = 0; i < text.length; i++) {
95262                 var c = text.charCodeAt(i);
95263                 if (ts.isLineBreak(c)) {
95264                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
95265                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
95266                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
95267                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
95268                     }
95269                     // Reset firstNonWhitespace for the next line.
95270                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
95271                     firstNonWhitespace = -1;
95272                 }
95273                 else if (!ts.isWhiteSpaceSingleLine(c)) {
95274                     lastNonWhitespace = i;
95275                     if (firstNonWhitespace === -1) {
95276                         firstNonWhitespace = i;
95277                     }
95278                 }
95279             }
95280             return firstNonWhitespace !== -1
95281                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
95282                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
95283                 // Last line was all whitespace, so ignore it
95284                 : acc;
95285         }
95286         function addLineOfJsxText(acc, trimmedLine) {
95287             // We do not escape the string here as that is handled by the printer
95288             // when it emits the literal. We do, however, need to decode JSX entities.
95289             var decoded = decodeEntities(trimmedLine);
95290             return acc === undefined ? decoded : acc + " " + decoded;
95291         }
95292         /**
95293          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
95294          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
95295          */
95296         function decodeEntities(text) {
95297             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
95298                 if (decimal) {
95299                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
95300                 }
95301                 else if (hex) {
95302                     return ts.utf16EncodeAsString(parseInt(hex, 16));
95303                 }
95304                 else {
95305                     var ch = entities.get(word);
95306                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
95307                     return ch ? ts.utf16EncodeAsString(ch) : match;
95308                 }
95309             });
95310         }
95311         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
95312         function tryDecodeEntities(text) {
95313             var decoded = decodeEntities(text);
95314             return decoded === text ? undefined : decoded;
95315         }
95316         function getTagName(node) {
95317             if (node.kind === 277 /* JsxElement */) {
95318                 return getTagName(node.openingElement);
95319             }
95320             else {
95321                 var name = node.tagName;
95322                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
95323                     return factory.createStringLiteral(ts.idText(name));
95324                 }
95325                 else {
95326                     return ts.createExpressionFromEntityName(factory, name);
95327                 }
95328             }
95329         }
95330         /**
95331          * Emit an attribute name, which is quoted if it needs to be quoted. Because
95332          * these emit into an object literal property name, we don't need to be worried
95333          * about keywords, just non-identifier characters
95334          */
95335         function getAttributeName(node) {
95336             var name = node.name;
95337             var text = ts.idText(name);
95338             if (/^[A-Za-z_]\w*$/.test(text)) {
95339                 return name;
95340             }
95341             else {
95342                 return factory.createStringLiteral(text);
95343             }
95344         }
95345         function visitJsxExpression(node) {
95346             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
95347             return node.dotDotDotToken ? factory.createSpreadElement(expression) : expression;
95348         }
95349     }
95350     ts.transformJsx = transformJsx;
95351     var entities = new ts.Map(ts.getEntries({
95352         quot: 0x0022,
95353         amp: 0x0026,
95354         apos: 0x0027,
95355         lt: 0x003C,
95356         gt: 0x003E,
95357         nbsp: 0x00A0,
95358         iexcl: 0x00A1,
95359         cent: 0x00A2,
95360         pound: 0x00A3,
95361         curren: 0x00A4,
95362         yen: 0x00A5,
95363         brvbar: 0x00A6,
95364         sect: 0x00A7,
95365         uml: 0x00A8,
95366         copy: 0x00A9,
95367         ordf: 0x00AA,
95368         laquo: 0x00AB,
95369         not: 0x00AC,
95370         shy: 0x00AD,
95371         reg: 0x00AE,
95372         macr: 0x00AF,
95373         deg: 0x00B0,
95374         plusmn: 0x00B1,
95375         sup2: 0x00B2,
95376         sup3: 0x00B3,
95377         acute: 0x00B4,
95378         micro: 0x00B5,
95379         para: 0x00B6,
95380         middot: 0x00B7,
95381         cedil: 0x00B8,
95382         sup1: 0x00B9,
95383         ordm: 0x00BA,
95384         raquo: 0x00BB,
95385         frac14: 0x00BC,
95386         frac12: 0x00BD,
95387         frac34: 0x00BE,
95388         iquest: 0x00BF,
95389         Agrave: 0x00C0,
95390         Aacute: 0x00C1,
95391         Acirc: 0x00C2,
95392         Atilde: 0x00C3,
95393         Auml: 0x00C4,
95394         Aring: 0x00C5,
95395         AElig: 0x00C6,
95396         Ccedil: 0x00C7,
95397         Egrave: 0x00C8,
95398         Eacute: 0x00C9,
95399         Ecirc: 0x00CA,
95400         Euml: 0x00CB,
95401         Igrave: 0x00CC,
95402         Iacute: 0x00CD,
95403         Icirc: 0x00CE,
95404         Iuml: 0x00CF,
95405         ETH: 0x00D0,
95406         Ntilde: 0x00D1,
95407         Ograve: 0x00D2,
95408         Oacute: 0x00D3,
95409         Ocirc: 0x00D4,
95410         Otilde: 0x00D5,
95411         Ouml: 0x00D6,
95412         times: 0x00D7,
95413         Oslash: 0x00D8,
95414         Ugrave: 0x00D9,
95415         Uacute: 0x00DA,
95416         Ucirc: 0x00DB,
95417         Uuml: 0x00DC,
95418         Yacute: 0x00DD,
95419         THORN: 0x00DE,
95420         szlig: 0x00DF,
95421         agrave: 0x00E0,
95422         aacute: 0x00E1,
95423         acirc: 0x00E2,
95424         atilde: 0x00E3,
95425         auml: 0x00E4,
95426         aring: 0x00E5,
95427         aelig: 0x00E6,
95428         ccedil: 0x00E7,
95429         egrave: 0x00E8,
95430         eacute: 0x00E9,
95431         ecirc: 0x00EA,
95432         euml: 0x00EB,
95433         igrave: 0x00EC,
95434         iacute: 0x00ED,
95435         icirc: 0x00EE,
95436         iuml: 0x00EF,
95437         eth: 0x00F0,
95438         ntilde: 0x00F1,
95439         ograve: 0x00F2,
95440         oacute: 0x00F3,
95441         ocirc: 0x00F4,
95442         otilde: 0x00F5,
95443         ouml: 0x00F6,
95444         divide: 0x00F7,
95445         oslash: 0x00F8,
95446         ugrave: 0x00F9,
95447         uacute: 0x00FA,
95448         ucirc: 0x00FB,
95449         uuml: 0x00FC,
95450         yacute: 0x00FD,
95451         thorn: 0x00FE,
95452         yuml: 0x00FF,
95453         OElig: 0x0152,
95454         oelig: 0x0153,
95455         Scaron: 0x0160,
95456         scaron: 0x0161,
95457         Yuml: 0x0178,
95458         fnof: 0x0192,
95459         circ: 0x02C6,
95460         tilde: 0x02DC,
95461         Alpha: 0x0391,
95462         Beta: 0x0392,
95463         Gamma: 0x0393,
95464         Delta: 0x0394,
95465         Epsilon: 0x0395,
95466         Zeta: 0x0396,
95467         Eta: 0x0397,
95468         Theta: 0x0398,
95469         Iota: 0x0399,
95470         Kappa: 0x039A,
95471         Lambda: 0x039B,
95472         Mu: 0x039C,
95473         Nu: 0x039D,
95474         Xi: 0x039E,
95475         Omicron: 0x039F,
95476         Pi: 0x03A0,
95477         Rho: 0x03A1,
95478         Sigma: 0x03A3,
95479         Tau: 0x03A4,
95480         Upsilon: 0x03A5,
95481         Phi: 0x03A6,
95482         Chi: 0x03A7,
95483         Psi: 0x03A8,
95484         Omega: 0x03A9,
95485         alpha: 0x03B1,
95486         beta: 0x03B2,
95487         gamma: 0x03B3,
95488         delta: 0x03B4,
95489         epsilon: 0x03B5,
95490         zeta: 0x03B6,
95491         eta: 0x03B7,
95492         theta: 0x03B8,
95493         iota: 0x03B9,
95494         kappa: 0x03BA,
95495         lambda: 0x03BB,
95496         mu: 0x03BC,
95497         nu: 0x03BD,
95498         xi: 0x03BE,
95499         omicron: 0x03BF,
95500         pi: 0x03C0,
95501         rho: 0x03C1,
95502         sigmaf: 0x03C2,
95503         sigma: 0x03C3,
95504         tau: 0x03C4,
95505         upsilon: 0x03C5,
95506         phi: 0x03C6,
95507         chi: 0x03C7,
95508         psi: 0x03C8,
95509         omega: 0x03C9,
95510         thetasym: 0x03D1,
95511         upsih: 0x03D2,
95512         piv: 0x03D6,
95513         ensp: 0x2002,
95514         emsp: 0x2003,
95515         thinsp: 0x2009,
95516         zwnj: 0x200C,
95517         zwj: 0x200D,
95518         lrm: 0x200E,
95519         rlm: 0x200F,
95520         ndash: 0x2013,
95521         mdash: 0x2014,
95522         lsquo: 0x2018,
95523         rsquo: 0x2019,
95524         sbquo: 0x201A,
95525         ldquo: 0x201C,
95526         rdquo: 0x201D,
95527         bdquo: 0x201E,
95528         dagger: 0x2020,
95529         Dagger: 0x2021,
95530         bull: 0x2022,
95531         hellip: 0x2026,
95532         permil: 0x2030,
95533         prime: 0x2032,
95534         Prime: 0x2033,
95535         lsaquo: 0x2039,
95536         rsaquo: 0x203A,
95537         oline: 0x203E,
95538         frasl: 0x2044,
95539         euro: 0x20AC,
95540         image: 0x2111,
95541         weierp: 0x2118,
95542         real: 0x211C,
95543         trade: 0x2122,
95544         alefsym: 0x2135,
95545         larr: 0x2190,
95546         uarr: 0x2191,
95547         rarr: 0x2192,
95548         darr: 0x2193,
95549         harr: 0x2194,
95550         crarr: 0x21B5,
95551         lArr: 0x21D0,
95552         uArr: 0x21D1,
95553         rArr: 0x21D2,
95554         dArr: 0x21D3,
95555         hArr: 0x21D4,
95556         forall: 0x2200,
95557         part: 0x2202,
95558         exist: 0x2203,
95559         empty: 0x2205,
95560         nabla: 0x2207,
95561         isin: 0x2208,
95562         notin: 0x2209,
95563         ni: 0x220B,
95564         prod: 0x220F,
95565         sum: 0x2211,
95566         minus: 0x2212,
95567         lowast: 0x2217,
95568         radic: 0x221A,
95569         prop: 0x221D,
95570         infin: 0x221E,
95571         ang: 0x2220,
95572         and: 0x2227,
95573         or: 0x2228,
95574         cap: 0x2229,
95575         cup: 0x222A,
95576         int: 0x222B,
95577         there4: 0x2234,
95578         sim: 0x223C,
95579         cong: 0x2245,
95580         asymp: 0x2248,
95581         ne: 0x2260,
95582         equiv: 0x2261,
95583         le: 0x2264,
95584         ge: 0x2265,
95585         sub: 0x2282,
95586         sup: 0x2283,
95587         nsub: 0x2284,
95588         sube: 0x2286,
95589         supe: 0x2287,
95590         oplus: 0x2295,
95591         otimes: 0x2297,
95592         perp: 0x22A5,
95593         sdot: 0x22C5,
95594         lceil: 0x2308,
95595         rceil: 0x2309,
95596         lfloor: 0x230A,
95597         rfloor: 0x230B,
95598         lang: 0x2329,
95599         rang: 0x232A,
95600         loz: 0x25CA,
95601         spades: 0x2660,
95602         clubs: 0x2663,
95603         hearts: 0x2665,
95604         diams: 0x2666
95605     }));
95606 })(ts || (ts = {}));
95607 /*@internal*/
95608 var ts;
95609 (function (ts) {
95610     function transformES2016(context) {
95611         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
95612         return ts.chainBundle(context, transformSourceFile);
95613         function transformSourceFile(node) {
95614             if (node.isDeclarationFile) {
95615                 return node;
95616             }
95617             return ts.visitEachChild(node, visitor, context);
95618         }
95619         function visitor(node) {
95620             if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) {
95621                 return node;
95622             }
95623             switch (node.kind) {
95624                 case 220 /* BinaryExpression */:
95625                     return visitBinaryExpression(node);
95626                 default:
95627                     return ts.visitEachChild(node, visitor, context);
95628             }
95629         }
95630         function visitBinaryExpression(node) {
95631             switch (node.operatorToken.kind) {
95632                 case 67 /* AsteriskAsteriskEqualsToken */:
95633                     return visitExponentiationAssignmentExpression(node);
95634                 case 42 /* AsteriskAsteriskToken */:
95635                     return visitExponentiationExpression(node);
95636                 default:
95637                     return ts.visitEachChild(node, visitor, context);
95638             }
95639         }
95640         function visitExponentiationAssignmentExpression(node) {
95641             var target;
95642             var value;
95643             var left = ts.visitNode(node.left, visitor, ts.isExpression);
95644             var right = ts.visitNode(node.right, visitor, ts.isExpression);
95645             if (ts.isElementAccessExpression(left)) {
95646                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
95647                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
95648                 var argumentExpressionTemp = factory.createTempVariable(hoistVariableDeclaration);
95649                 target = ts.setTextRange(factory.createElementAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
95650                 value = ts.setTextRange(factory.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left);
95651             }
95652             else if (ts.isPropertyAccessExpression(left)) {
95653                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
95654                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
95655                 target = ts.setTextRange(factory.createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
95656                 value = ts.setTextRange(factory.createPropertyAccessExpression(expressionTemp, left.name), left);
95657             }
95658             else {
95659                 // Transforms `a **= b` into `a = Math.pow(a, b)`
95660                 target = left;
95661                 value = left;
95662             }
95663             return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node)), node);
95664         }
95665         function visitExponentiationExpression(node) {
95666             // Transforms `a ** b` into `Math.pow(a, b)`
95667             var left = ts.visitNode(node.left, visitor, ts.isExpression);
95668             var right = ts.visitNode(node.right, visitor, ts.isExpression);
95669             return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node);
95670         }
95671     }
95672     ts.transformES2016 = transformES2016;
95673 })(ts || (ts = {}));
95674 /*@internal*/
95675 var ts;
95676 (function (ts) {
95677     var ES2015SubstitutionFlags;
95678     (function (ES2015SubstitutionFlags) {
95679         /** Enables substitutions for captured `this` */
95680         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
95681         /** Enables substitutions for block-scoped bindings. */
95682         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
95683     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
95684     var LoopOutParameterFlags;
95685     (function (LoopOutParameterFlags) {
95686         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
95687         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
95688     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
95689     var CopyDirection;
95690     (function (CopyDirection) {
95691         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
95692         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
95693     })(CopyDirection || (CopyDirection = {}));
95694     var Jump;
95695     (function (Jump) {
95696         Jump[Jump["Break"] = 2] = "Break";
95697         Jump[Jump["Continue"] = 4] = "Continue";
95698         Jump[Jump["Return"] = 8] = "Return";
95699     })(Jump || (Jump = {}));
95700     // Facts we track as we traverse the tree
95701     var HierarchyFacts;
95702     (function (HierarchyFacts) {
95703         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
95704         //
95705         // Ancestor facts
95706         //
95707         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
95708         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
95709         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
95710         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
95711         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
95712         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
95713         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
95714         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
95715         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
95716         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
95717         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
95718         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
95719         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
95720         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
95721         HierarchyFacts[HierarchyFacts["StaticInitializer"] = 16384] = "StaticInitializer";
95722         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
95723         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
95724         //
95725         // Ancestor masks
95726         //
95727         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 32767] = "AncestorFactsMask";
95728         // We are always in *some* kind of block scope, but only specific block-scope containers are
95729         // top-level or Blocks.
95730         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
95731         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
95732         // A source file is a top-level block scope.
95733         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
95734         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
95735         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
95736         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
95737         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 32670] = "FunctionExcludes";
95738         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
95739         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 32662] = "AsyncFunctionBodyExcludes";
95740         // Arrow functions are lexically scoped to their container, but are new block scopes.
95741         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
95742         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
95743         // Constructors are both new lexical scopes and new block scopes. Constructors are also
95744         // always considered non-static members of a class.
95745         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
95746         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 32662] = "ConstructorExcludes";
95747         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
95748         // within an IterationStatement to indicate whether the embedded statement is an
95749         // IterationStatementBlock.
95750         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
95751         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
95752         // 'for' statements are new block scopes and have special handling for 'let' declarations.
95753         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
95754         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
95755         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
95756         // 'let' declarations.
95757         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
95758         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
95759         // Blocks (other than function bodies) are new block scopes.
95760         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
95761         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
95762         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
95763         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
95764         HierarchyFacts[HierarchyFacts["StaticInitializerIncludes"] = 16449] = "StaticInitializerIncludes";
95765         HierarchyFacts[HierarchyFacts["StaticInitializerExcludes"] = 32670] = "StaticInitializerExcludes";
95766         //
95767         // Subtree facts
95768         //
95769         HierarchyFacts[HierarchyFacts["NewTarget"] = 32768] = "NewTarget";
95770         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 65536] = "CapturedLexicalThis";
95771         //
95772         // Subtree masks
95773         //
95774         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -32768] = "SubtreeFactsMask";
95775         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
95776         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 98304] = "FunctionSubtreeExcludes";
95777     })(HierarchyFacts || (HierarchyFacts = {}));
95778     var SpreadSegmentKind;
95779     (function (SpreadSegmentKind) {
95780         SpreadSegmentKind[SpreadSegmentKind["None"] = 0] = "None";
95781         SpreadSegmentKind[SpreadSegmentKind["UnpackedSpread"] = 1] = "UnpackedSpread";
95782         SpreadSegmentKind[SpreadSegmentKind["PackedSpread"] = 2] = "PackedSpread";
95783     })(SpreadSegmentKind || (SpreadSegmentKind = {}));
95784     function createSpreadSegment(kind, expression) {
95785         return { kind: kind, expression: expression };
95786     }
95787     function transformES2015(context) {
95788         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
95789         var compilerOptions = context.getCompilerOptions();
95790         var resolver = context.getEmitResolver();
95791         var previousOnSubstituteNode = context.onSubstituteNode;
95792         var previousOnEmitNode = context.onEmitNode;
95793         context.onEmitNode = onEmitNode;
95794         context.onSubstituteNode = onSubstituteNode;
95795         var currentSourceFile;
95796         var currentText;
95797         var hierarchyFacts;
95798         var taggedTemplateStringDeclarations;
95799         function recordTaggedTemplateString(temp) {
95800             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
95801         }
95802         /**
95803          * Used to track if we are emitting body of the converted loop
95804          */
95805         var convertedLoopState;
95806         /**
95807          * Keeps track of whether substitutions have been enabled for specific cases.
95808          * They are persisted between each SourceFile transformation and should not
95809          * be reset.
95810          */
95811         var enabledSubstitutions;
95812         return ts.chainBundle(context, transformSourceFile);
95813         function transformSourceFile(node) {
95814             if (node.isDeclarationFile) {
95815                 return node;
95816             }
95817             currentSourceFile = node;
95818             currentText = node.text;
95819             var visited = visitSourceFile(node);
95820             ts.addEmitHelpers(visited, context.readEmitHelpers());
95821             currentSourceFile = undefined;
95822             currentText = undefined;
95823             taggedTemplateStringDeclarations = undefined;
95824             hierarchyFacts = 0 /* None */;
95825             return visited;
95826         }
95827         /**
95828          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
95829          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
95830          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
95831          */
95832         function enterSubtree(excludeFacts, includeFacts) {
95833             var ancestorFacts = hierarchyFacts;
95834             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 32767 /* AncestorFactsMask */;
95835             return ancestorFacts;
95836         }
95837         /**
95838          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
95839          * subtree, propagating specific facts from the subtree.
95840          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
95841          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
95842          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
95843          */
95844         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
95845             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -32768 /* SubtreeFactsMask */ | ancestorFacts;
95846         }
95847         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
95848             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
95849                 && node.kind === 246 /* ReturnStatement */
95850                 && !node.expression;
95851         }
95852         function isOrMayContainReturnCompletion(node) {
95853             return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */
95854                 && (ts.isReturnStatement(node)
95855                     || ts.isIfStatement(node)
95856                     || ts.isWithStatement(node)
95857                     || ts.isSwitchStatement(node)
95858                     || ts.isCaseBlock(node)
95859                     || ts.isCaseClause(node)
95860                     || ts.isDefaultClause(node)
95861                     || ts.isTryStatement(node)
95862                     || ts.isCatchClause(node)
95863                     || ts.isLabeledStatement(node)
95864                     || ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)
95865                     || ts.isBlock(node));
95866         }
95867         function shouldVisitNode(node) {
95868             return (node.transformFlags & 512 /* ContainsES2015 */) !== 0
95869                 || convertedLoopState !== undefined
95870                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node))
95871                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
95872                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
95873         }
95874         function visitor(node) {
95875             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ false) : node;
95876         }
95877         function visitorWithUnusedExpressionResult(node) {
95878             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ true) : node;
95879         }
95880         function classWrapperStatementVisitor(node) {
95881             if (shouldVisitNode(node)) {
95882                 var original = ts.getOriginalNode(node);
95883                 if (ts.isPropertyDeclaration(original) && ts.hasStaticModifier(original)) {
95884                     var ancestorFacts = enterSubtree(32670 /* StaticInitializerExcludes */, 16449 /* StaticInitializerIncludes */);
95885                     var result = visitorWorker(node, /*expressionResultIsUnused*/ false);
95886                     exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
95887                     return result;
95888                 }
95889                 return visitorWorker(node, /*expressionResultIsUnused*/ false);
95890             }
95891             return node;
95892         }
95893         function callExpressionVisitor(node) {
95894             if (node.kind === 106 /* SuperKeyword */) {
95895                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
95896             }
95897             return visitor(node);
95898         }
95899         function visitorWorker(node, expressionResultIsUnused) {
95900             switch (node.kind) {
95901                 case 124 /* StaticKeyword */:
95902                     return undefined; // elide static keyword
95903                 case 256 /* ClassDeclaration */:
95904                     return visitClassDeclaration(node);
95905                 case 225 /* ClassExpression */:
95906                     return visitClassExpression(node);
95907                 case 163 /* Parameter */:
95908                     return visitParameter(node);
95909                 case 255 /* FunctionDeclaration */:
95910                     return visitFunctionDeclaration(node);
95911                 case 213 /* ArrowFunction */:
95912                     return visitArrowFunction(node);
95913                 case 212 /* FunctionExpression */:
95914                     return visitFunctionExpression(node);
95915                 case 253 /* VariableDeclaration */:
95916                     return visitVariableDeclaration(node);
95917                 case 79 /* Identifier */:
95918                     return visitIdentifier(node);
95919                 case 254 /* VariableDeclarationList */:
95920                     return visitVariableDeclarationList(node);
95921                 case 248 /* SwitchStatement */:
95922                     return visitSwitchStatement(node);
95923                 case 262 /* CaseBlock */:
95924                     return visitCaseBlock(node);
95925                 case 234 /* Block */:
95926                     return visitBlock(node, /*isFunctionBody*/ false);
95927                 case 245 /* BreakStatement */:
95928                 case 244 /* ContinueStatement */:
95929                     return visitBreakOrContinueStatement(node);
95930                 case 249 /* LabeledStatement */:
95931                     return visitLabeledStatement(node);
95932                 case 239 /* DoStatement */:
95933                 case 240 /* WhileStatement */:
95934                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
95935                 case 241 /* ForStatement */:
95936                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
95937                 case 242 /* ForInStatement */:
95938                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
95939                 case 243 /* ForOfStatement */:
95940                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
95941                 case 237 /* ExpressionStatement */:
95942                     return visitExpressionStatement(node);
95943                 case 204 /* ObjectLiteralExpression */:
95944                     return visitObjectLiteralExpression(node);
95945                 case 291 /* CatchClause */:
95946                     return visitCatchClause(node);
95947                 case 295 /* ShorthandPropertyAssignment */:
95948                     return visitShorthandPropertyAssignment(node);
95949                 case 161 /* ComputedPropertyName */:
95950                     return visitComputedPropertyName(node);
95951                 case 203 /* ArrayLiteralExpression */:
95952                     return visitArrayLiteralExpression(node);
95953                 case 207 /* CallExpression */:
95954                     return visitCallExpression(node);
95955                 case 208 /* NewExpression */:
95956                     return visitNewExpression(node);
95957                 case 211 /* ParenthesizedExpression */:
95958                     return visitParenthesizedExpression(node, expressionResultIsUnused);
95959                 case 220 /* BinaryExpression */:
95960                     return visitBinaryExpression(node, expressionResultIsUnused);
95961                 case 349 /* CommaListExpression */:
95962                     return visitCommaListExpression(node, expressionResultIsUnused);
95963                 case 14 /* NoSubstitutionTemplateLiteral */:
95964                 case 15 /* TemplateHead */:
95965                 case 16 /* TemplateMiddle */:
95966                 case 17 /* TemplateTail */:
95967                     return visitTemplateLiteral(node);
95968                 case 10 /* StringLiteral */:
95969                     return visitStringLiteral(node);
95970                 case 8 /* NumericLiteral */:
95971                     return visitNumericLiteral(node);
95972                 case 209 /* TaggedTemplateExpression */:
95973                     return visitTaggedTemplateExpression(node);
95974                 case 222 /* TemplateExpression */:
95975                     return visitTemplateExpression(node);
95976                 case 223 /* YieldExpression */:
95977                     return visitYieldExpression(node);
95978                 case 224 /* SpreadElement */:
95979                     return visitSpreadElement(node);
95980                 case 106 /* SuperKeyword */:
95981                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
95982                 case 108 /* ThisKeyword */:
95983                     return visitThisKeyword(node);
95984                 case 230 /* MetaProperty */:
95985                     return visitMetaProperty(node);
95986                 case 168 /* MethodDeclaration */:
95987                     return visitMethodDeclaration(node);
95988                 case 171 /* GetAccessor */:
95989                 case 172 /* SetAccessor */:
95990                     return visitAccessorDeclaration(node);
95991                 case 236 /* VariableStatement */:
95992                     return visitVariableStatement(node);
95993                 case 246 /* ReturnStatement */:
95994                     return visitReturnStatement(node);
95995                 case 216 /* VoidExpression */:
95996                     return visitVoidExpression(node);
95997                 default:
95998                     return ts.visitEachChild(node, visitor, context);
95999             }
96000         }
96001         function visitSourceFile(node) {
96002             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
96003             var prologue = [];
96004             var statements = [];
96005             startLexicalEnvironment();
96006             var statementOffset = factory.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ false, visitor);
96007             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
96008             if (taggedTemplateStringDeclarations) {
96009                 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)));
96010             }
96011             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
96012             insertCaptureThisForNodeIfNeeded(prologue, node);
96013             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
96014             return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
96015         }
96016         function visitSwitchStatement(node) {
96017             if (convertedLoopState !== undefined) {
96018                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
96019                 // for switch statement allow only non-labeled break
96020                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
96021                 var result = ts.visitEachChild(node, visitor, context);
96022                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
96023                 return result;
96024             }
96025             return ts.visitEachChild(node, visitor, context);
96026         }
96027         function visitCaseBlock(node) {
96028             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
96029             var updated = ts.visitEachChild(node, visitor, context);
96030             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
96031             return updated;
96032         }
96033         function returnCapturedThis(node) {
96034             return ts.setOriginalNode(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
96035         }
96036         function visitReturnStatement(node) {
96037             if (convertedLoopState) {
96038                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
96039                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
96040                     node = returnCapturedThis(node);
96041                 }
96042                 return factory.createReturnStatement(factory.createObjectLiteralExpression([
96043                     factory.createPropertyAssignment(factory.createIdentifier("value"), node.expression
96044                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
96045                         : factory.createVoidZero())
96046                 ]));
96047             }
96048             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
96049                 return returnCapturedThis(node);
96050             }
96051             return ts.visitEachChild(node, visitor, context);
96052         }
96053         function visitThisKeyword(node) {
96054             if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) {
96055                 hierarchyFacts |= 65536 /* CapturedLexicalThis */;
96056             }
96057             if (convertedLoopState) {
96058                 if (hierarchyFacts & 2 /* ArrowFunction */) {
96059                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
96060                     convertedLoopState.containsLexicalThis = true;
96061                     return node;
96062                 }
96063                 return convertedLoopState.thisName || (convertedLoopState.thisName = factory.createUniqueName("this"));
96064             }
96065             return node;
96066         }
96067         function visitVoidExpression(node) {
96068             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
96069         }
96070         function visitIdentifier(node) {
96071             if (!convertedLoopState) {
96072                 return node;
96073             }
96074             if (resolver.isArgumentsLocalBinding(node)) {
96075                 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
96076             }
96077             return node;
96078         }
96079         function visitBreakOrContinueStatement(node) {
96080             if (convertedLoopState) {
96081                 // check if we can emit break/continue as is
96082                 // it is possible if either
96083                 //   - break/continue is labeled and label is located inside the converted loop
96084                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
96085                 var jump = node.kind === 245 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
96086                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
96087                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
96088                 if (!canUseBreakOrContinue) {
96089                     var labelMarker = void 0;
96090                     var label = node.label;
96091                     if (!label) {
96092                         if (node.kind === 245 /* BreakStatement */) {
96093                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
96094                             labelMarker = "break";
96095                         }
96096                         else {
96097                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
96098                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
96099                             labelMarker = "continue";
96100                         }
96101                     }
96102                     else {
96103                         if (node.kind === 245 /* BreakStatement */) {
96104                             labelMarker = "break-".concat(label.escapedText);
96105                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
96106                         }
96107                         else {
96108                             labelMarker = "continue-".concat(label.escapedText);
96109                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
96110                         }
96111                     }
96112                     var returnExpression = factory.createStringLiteral(labelMarker);
96113                     if (convertedLoopState.loopOutParameters.length) {
96114                         var outParams = convertedLoopState.loopOutParameters;
96115                         var expr = void 0;
96116                         for (var i = 0; i < outParams.length; i++) {
96117                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
96118                             if (i === 0) {
96119                                 expr = copyExpr;
96120                             }
96121                             else {
96122                                 expr = factory.createBinaryExpression(expr, 27 /* CommaToken */, copyExpr);
96123                             }
96124                         }
96125                         returnExpression = factory.createBinaryExpression(expr, 27 /* CommaToken */, returnExpression);
96126                     }
96127                     return factory.createReturnStatement(returnExpression);
96128                 }
96129             }
96130             return ts.visitEachChild(node, visitor, context);
96131         }
96132         /**
96133          * Visits a ClassDeclaration and transforms it into a variable statement.
96134          *
96135          * @param node A ClassDeclaration node.
96136          */
96137         function visitClassDeclaration(node) {
96138             // [source]
96139             //      class C { }
96140             //
96141             // [output]
96142             //      var C = (function () {
96143             //          function C() {
96144             //          }
96145             //          return C;
96146             //      }());
96147             var variable = factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ true), 
96148             /*exclamationToken*/ undefined, 
96149             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
96150             ts.setOriginalNode(variable, node);
96151             var statements = [];
96152             var statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([variable]));
96153             ts.setOriginalNode(statement, node);
96154             ts.setTextRange(statement, node);
96155             ts.startOnNewLine(statement);
96156             statements.push(statement);
96157             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
96158             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
96159                 var exportStatement = ts.hasSyntacticModifier(node, 512 /* Default */)
96160                     ? factory.createExportDefault(factory.getLocalName(node))
96161                     : factory.createExternalModuleExport(factory.getLocalName(node));
96162                 ts.setOriginalNode(exportStatement, statement);
96163                 statements.push(exportStatement);
96164             }
96165             var emitFlags = ts.getEmitFlags(node);
96166             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
96167                 // Add a DeclarationMarker as a marker for the end of the declaration
96168                 statements.push(factory.createEndOfDeclarationMarker(node));
96169                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
96170             }
96171             return ts.singleOrMany(statements);
96172         }
96173         /**
96174          * Visits a ClassExpression and transforms it into an expression.
96175          *
96176          * @param node A ClassExpression node.
96177          */
96178         function visitClassExpression(node) {
96179             // [source]
96180             //      C = class { }
96181             //
96182             // [output]
96183             //      C = (function () {
96184             //          function class_1() {
96185             //          }
96186             //          return class_1;
96187             //      }())
96188             return transformClassLikeDeclarationToExpression(node);
96189         }
96190         /**
96191          * Transforms a ClassExpression or ClassDeclaration into an expression.
96192          *
96193          * @param node A ClassExpression or ClassDeclaration node.
96194          */
96195         function transformClassLikeDeclarationToExpression(node) {
96196             // [source]
96197             //      class C extends D {
96198             //          constructor() {}
96199             //          method() {}
96200             //          get prop() {}
96201             //          set prop(v) {}
96202             //      }
96203             //
96204             // [output]
96205             //      (function (_super) {
96206             //          __extends(C, _super);
96207             //          function C() {
96208             //          }
96209             //          C.prototype.method = function () {}
96210             //          Object.defineProperty(C.prototype, "prop", {
96211             //              get: function() {},
96212             //              set: function() {},
96213             //              enumerable: true,
96214             //              configurable: true
96215             //          });
96216             //          return C;
96217             //      }(D))
96218             if (node.name) {
96219                 enableSubstitutionsForBlockScopedBindings();
96220             }
96221             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
96222             var classFunction = factory.createFunctionExpression(
96223             /*modifiers*/ undefined, 
96224             /*asteriskToken*/ undefined, 
96225             /*name*/ undefined, 
96226             /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */))] : [], 
96227             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
96228             // To preserve the behavior of the old emitter, we explicitly indent
96229             // the body of the function here if it was requested in an earlier
96230             // transformation.
96231             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
96232             // "inner" and "outer" below are added purely to preserve source map locations from
96233             // the old emitter
96234             var inner = factory.createPartiallyEmittedExpression(classFunction);
96235             ts.setTextRangeEnd(inner, node.end);
96236             ts.setEmitFlags(inner, 1536 /* NoComments */);
96237             var outer = factory.createPartiallyEmittedExpression(inner);
96238             ts.setTextRangeEnd(outer, ts.skipTrivia(currentText, node.pos));
96239             ts.setEmitFlags(outer, 1536 /* NoComments */);
96240             var result = factory.createParenthesizedExpression(factory.createCallExpression(outer, 
96241             /*typeArguments*/ undefined, extendsClauseElement
96242                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
96243                 : []));
96244             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
96245             return result;
96246         }
96247         /**
96248          * Transforms a ClassExpression or ClassDeclaration into a function body.
96249          *
96250          * @param node A ClassExpression or ClassDeclaration node.
96251          * @param extendsClauseElement The expression for the class `extends` clause.
96252          */
96253         function transformClassBody(node, extendsClauseElement) {
96254             var statements = [];
96255             var name = factory.getInternalName(node);
96256             var constructorLikeName = ts.isIdentifierANonContextualKeyword(name) ? factory.getGeneratedNameForNode(name) : name;
96257             startLexicalEnvironment();
96258             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
96259             addConstructor(statements, node, constructorLikeName, extendsClauseElement);
96260             addClassMembers(statements, node);
96261             // Create a synthetic text range for the return statement.
96262             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
96263             // The following partially-emitted expression exists purely to align our sourcemap
96264             // emit with the original emitter.
96265             var outer = factory.createPartiallyEmittedExpression(constructorLikeName);
96266             ts.setTextRangeEnd(outer, closingBraceLocation.end);
96267             ts.setEmitFlags(outer, 1536 /* NoComments */);
96268             var statement = factory.createReturnStatement(outer);
96269             ts.setTextRangePos(statement, closingBraceLocation.pos);
96270             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
96271             statements.push(statement);
96272             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
96273             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
96274             ts.setEmitFlags(block, 1536 /* NoComments */);
96275             return block;
96276         }
96277         /**
96278          * Adds a call to the `__extends` helper if needed for a class.
96279          *
96280          * @param statements The statements of the class body function.
96281          * @param node The ClassExpression or ClassDeclaration node.
96282          * @param extendsClauseElement The expression for the class `extends` clause.
96283          */
96284         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
96285             if (extendsClauseElement) {
96286                 statements.push(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExtendsHelper(factory.getInternalName(node))), 
96287                 /*location*/ extendsClauseElement));
96288             }
96289         }
96290         /**
96291          * Adds the constructor of the class to a class body function.
96292          *
96293          * @param statements The statements of the class body function.
96294          * @param node The ClassExpression or ClassDeclaration node.
96295          * @param extendsClauseElement The expression for the class `extends` clause.
96296          */
96297         function addConstructor(statements, node, name, extendsClauseElement) {
96298             var savedConvertedLoopState = convertedLoopState;
96299             convertedLoopState = undefined;
96300             var ancestorFacts = enterSubtree(32662 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
96301             var constructor = ts.getFirstConstructorWithBody(node);
96302             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
96303             var constructorFunction = factory.createFunctionDeclaration(
96304             /*decorators*/ undefined, 
96305             /*modifiers*/ undefined, 
96306             /*asteriskToken*/ undefined, name, 
96307             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
96308             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
96309             ts.setTextRange(constructorFunction, constructor || node);
96310             if (extendsClauseElement) {
96311                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
96312             }
96313             statements.push(constructorFunction);
96314             exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
96315             convertedLoopState = savedConvertedLoopState;
96316         }
96317         /**
96318          * Transforms the parameters of the constructor declaration of a class.
96319          *
96320          * @param constructor The constructor for the class.
96321          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
96322          *                            synthesized `super` call.
96323          */
96324         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
96325             // If the TypeScript transformer needed to synthesize a constructor for property
96326             // initializers, it would have also added a synthetic `...args` parameter and
96327             // `super` call.
96328             // If this is the case, we do not include the synthetic `...args` parameter and
96329             // will instead use the `arguments` object in ES5/3.
96330             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
96331                 || [];
96332         }
96333         function createDefaultConstructorBody(node, isDerivedClass) {
96334             // We must be here because the user didn't write a constructor
96335             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
96336             // If that's the case we can just immediately return the result of a 'super()' call.
96337             var statements = [];
96338             resumeLexicalEnvironment();
96339             factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
96340             if (isDerivedClass) {
96341                 // return _super !== null && _super.apply(this, arguments) || this;
96342                 statements.push(factory.createReturnStatement(createDefaultSuperCallOrThis()));
96343             }
96344             var statementsArray = factory.createNodeArray(statements);
96345             ts.setTextRange(statementsArray, node.members);
96346             var block = factory.createBlock(statementsArray, /*multiLine*/ true);
96347             ts.setTextRange(block, node);
96348             ts.setEmitFlags(block, 1536 /* NoComments */);
96349             return block;
96350         }
96351         /**
96352          * Transforms the body of a constructor declaration of a class.
96353          *
96354          * @param constructor The constructor for the class.
96355          * @param node The node which contains the constructor.
96356          * @param extendsClauseElement The expression for the class `extends` clause.
96357          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
96358          *                            synthesized `super` call.
96359          */
96360         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
96361             // determine whether the class is known syntactically to be a derived class (e.g. a
96362             // class that extends a value that is not syntactically known to be `null`).
96363             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* NullKeyword */;
96364             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
96365             // representation:
96366             //
96367             // ```
96368             // // es2015 (source)
96369             // class C extends Base { }
96370             //
96371             // // es5 (transformed)
96372             // var C = (function (_super) {
96373             //     function C() {
96374             //         return _super.apply(this, arguments) || this;
96375             //     }
96376             //     return C;
96377             // })(Base);
96378             // ```
96379             if (!constructor)
96380                 return createDefaultConstructorBody(node, isDerivedClass);
96381             // The prologue will contain all leading standard and custom prologue statements added by this transform
96382             var prologue = [];
96383             var statements = [];
96384             resumeLexicalEnvironment();
96385             // If a super call has already been synthesized,
96386             // we're going to assume that we should just transform everything after that.
96387             // The assumption is that no prior step in the pipeline has added any prologue directives.
96388             var statementOffset = 0;
96389             if (!hasSynthesizedSuper)
96390                 statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
96391             addDefaultValueAssignmentsIfNeeded(statements, constructor);
96392             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
96393             if (!hasSynthesizedSuper)
96394                 statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
96395             // If the first statement is a call to `super()`, visit the statement directly
96396             var superCallExpression;
96397             if (hasSynthesizedSuper) {
96398                 superCallExpression = createDefaultSuperCallOrThis();
96399             }
96400             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
96401                 var firstStatement = constructor.body.statements[statementOffset];
96402                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
96403                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
96404                 }
96405             }
96406             if (superCallExpression) {
96407                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
96408                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
96409             }
96410             // visit the remaining statements
96411             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
96412             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
96413             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
96414             if (isDerivedClass) {
96415                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) {
96416                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
96417                     // following representation:
96418                     //
96419                     // ```
96420                     // // es2015 (source)
96421                     // class C extends Base {
96422                     //     constructor() {
96423                     //         super("foo");
96424                     //     }
96425                     // }
96426                     //
96427                     // // es5 (transformed)
96428                     // var C = (function (_super) {
96429                     //     function C() {
96430                     //         return _super.call(this, "foo") || this;
96431                     //     }
96432                     //     return C;
96433                     // })(Base);
96434                     // ```
96435                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
96436                     var returnStatement = factory.createReturnStatement(superCallExpression);
96437                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
96438                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
96439                     statements.push(returnStatement);
96440                 }
96441                 else {
96442                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
96443                     //
96444                     // ```
96445                     // // es2015 (source)
96446                     // class C extends Base {
96447                     //     constructor() {
96448                     //         super("foo");
96449                     //         this.x = 1;
96450                     //     }
96451                     // }
96452                     //
96453                     // // es5 (transformed)
96454                     // var C = (function (_super) {
96455                     //     function C() {
96456                     //         var _this = _super.call(this, "foo") || this;
96457                     //         _this.x = 1;
96458                     //         return _this;
96459                     //     }
96460                     //     return C;
96461                     // })(Base);
96462                     // ```
96463                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
96464                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
96465                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
96466                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
96467                         statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
96468                     }
96469                 }
96470             }
96471             else {
96472                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
96473                 // captured when necessitated by an arrow function capturing the lexical `this`:
96474                 //
96475                 // ```
96476                 // // es2015
96477                 // class C {}
96478                 //
96479                 // // es5
96480                 // var C = (function () {
96481                 //     function C() {
96482                 //     }
96483                 //     return C;
96484                 // })();
96485                 // ```
96486                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
96487             }
96488             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), 
96489             /*location*/ constructor.body.statements), 
96490             /*multiLine*/ true);
96491             ts.setTextRange(block, constructor.body);
96492             return block;
96493         }
96494         /**
96495          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
96496          * It would generate obviously dead code, so we'll try to make things a little bit prettier
96497          * by doing a minimal check on whether some common patterns always explicitly return.
96498          */
96499         function isSufficientlyCoveredByReturnStatements(statement) {
96500             // A return statement is considered covered.
96501             if (statement.kind === 246 /* ReturnStatement */) {
96502                 return true;
96503             }
96504             // An if-statement with two covered branches is covered.
96505             else if (statement.kind === 238 /* IfStatement */) {
96506                 var ifStatement = statement;
96507                 if (ifStatement.elseStatement) {
96508                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
96509                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
96510                 }
96511             }
96512             // A block is covered if it has a last statement which is covered.
96513             else if (statement.kind === 234 /* Block */) {
96514                 var lastStatement = ts.lastOrUndefined(statement.statements);
96515                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
96516                     return true;
96517                 }
96518             }
96519             return false;
96520         }
96521         function createActualThis() {
96522             return ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */);
96523         }
96524         function createDefaultSuperCallOrThis() {
96525             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());
96526         }
96527         /**
96528          * Visits a parameter declaration.
96529          *
96530          * @param node A ParameterDeclaration node.
96531          */
96532         function visitParameter(node) {
96533             if (node.dotDotDotToken) {
96534                 // rest parameters are elided
96535                 return undefined;
96536             }
96537             else if (ts.isBindingPattern(node.name)) {
96538                 // Binding patterns are converted into a generated name and are
96539                 // evaluated inside the function body.
96540                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
96541                 /*decorators*/ undefined, 
96542                 /*modifiers*/ undefined, 
96543                 /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), 
96544                 /*questionToken*/ undefined, 
96545                 /*type*/ undefined, 
96546                 /*initializer*/ undefined), 
96547                 /*location*/ node), 
96548                 /*original*/ node);
96549             }
96550             else if (node.initializer) {
96551                 // Initializers are elided
96552                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
96553                 /*decorators*/ undefined, 
96554                 /*modifiers*/ undefined, 
96555                 /*dotDotDotToken*/ undefined, node.name, 
96556                 /*questionToken*/ undefined, 
96557                 /*type*/ undefined, 
96558                 /*initializer*/ undefined), 
96559                 /*location*/ node), 
96560                 /*original*/ node);
96561             }
96562             else {
96563                 return node;
96564             }
96565         }
96566         function hasDefaultValueOrBindingPattern(node) {
96567             return node.initializer !== undefined
96568                 || ts.isBindingPattern(node.name);
96569         }
96570         /**
96571          * Adds statements to the body of a function-like node if it contains parameters with
96572          * binding patterns or initializers.
96573          *
96574          * @param statements The statements for the new function body.
96575          * @param node A function-like node.
96576          */
96577         function addDefaultValueAssignmentsIfNeeded(statements, node) {
96578             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
96579                 return false;
96580             }
96581             var added = false;
96582             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
96583                 var parameter = _a[_i];
96584                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
96585                 // A rest parameter cannot have a binding pattern or an initializer,
96586                 // so let's just ignore it.
96587                 if (dotDotDotToken) {
96588                     continue;
96589                 }
96590                 if (ts.isBindingPattern(name)) {
96591                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
96592                 }
96593                 else if (initializer) {
96594                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
96595                     added = true;
96596                 }
96597             }
96598             return added;
96599         }
96600         /**
96601          * Adds statements to the body of a function-like node for parameters with binding patterns
96602          *
96603          * @param statements The statements for the new function body.
96604          * @param parameter The parameter for the function.
96605          * @param name The name of the parameter.
96606          * @param initializer The initializer for the parameter.
96607          */
96608         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
96609             // In cases where a binding pattern is simply '[]' or '{}',
96610             // we usually don't want to emit a var declaration; however, in the presence
96611             // of an initializer, we must emit that expression to preserve side effects.
96612             if (name.elements.length > 0) {
96613                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createVariableStatement(
96614                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
96615                 return true;
96616             }
96617             else if (initializer) {
96618                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createExpressionStatement(factory.createAssignment(factory.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
96619                 return true;
96620             }
96621             return false;
96622         }
96623         /**
96624          * Adds statements to the body of a function-like node for parameters with initializers.
96625          *
96626          * @param statements The statements for the new function body.
96627          * @param parameter The parameter for the function.
96628          * @param name The name of the parameter.
96629          * @param initializer The initializer for the parameter.
96630          */
96631         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
96632             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
96633             var statement = factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
96634                 factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(
96635                 // TODO(rbuckton): Does this need to be parented?
96636                 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 */))
96637             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
96638             ts.startOnNewLine(statement);
96639             ts.setTextRange(statement, parameter);
96640             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
96641             ts.insertStatementAfterCustomPrologue(statements, statement);
96642         }
96643         /**
96644          * Gets a value indicating whether we need to add statements to handle a rest parameter.
96645          *
96646          * @param node A ParameterDeclaration node.
96647          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
96648          *                                          part of a constructor declaration with a
96649          *                                          synthesized call to `super`
96650          */
96651         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
96652             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
96653         }
96654         /**
96655          * Adds statements to the body of a function-like node if it contains a rest parameter.
96656          *
96657          * @param statements The statements for the new function body.
96658          * @param node A function-like node.
96659          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
96660          *                                          part of a constructor declaration with a
96661          *                                          synthesized call to `super`
96662          */
96663         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
96664             var prologueStatements = [];
96665             var parameter = ts.lastOrUndefined(node.parameters);
96666             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
96667                 return false;
96668             }
96669             // `declarationName` is the name of the local declaration for the parameter.
96670             // TODO(rbuckton): Does this need to be parented?
96671             var declarationName = parameter.name.kind === 79 /* Identifier */ ? ts.setParent(ts.setTextRange(factory.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory.createTempVariable(/*recordTempVariable*/ undefined);
96672             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
96673             // `expressionName` is the name of the parameter used in expressions.
96674             var expressionName = parameter.name.kind === 79 /* Identifier */ ? factory.cloneNode(parameter.name) : declarationName;
96675             var restIndex = node.parameters.length - 1;
96676             var temp = factory.createLoopVariable();
96677             // var param = [];
96678             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
96679             /*modifiers*/ undefined, factory.createVariableDeclarationList([
96680                 factory.createVariableDeclaration(declarationName, 
96681                 /*exclamationToken*/ undefined, 
96682                 /*type*/ undefined, factory.createArrayLiteralExpression([]))
96683             ])), 
96684             /*location*/ parameter), 1048576 /* CustomPrologue */));
96685             // for (var _i = restIndex; _i < arguments.length; _i++) {
96686             //   param[_i - restIndex] = arguments[_i];
96687             // }
96688             var forStatement = factory.createForStatement(ts.setTextRange(factory.createVariableDeclarationList([
96689                 factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex))
96690             ]), parameter), ts.setTextRange(factory.createLessThan(temp, factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([
96691                 ts.startOnNewLine(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(expressionName, restIndex === 0
96692                     ? temp
96693                     : factory.createSubtract(temp, factory.createNumericLiteral(restIndex))), factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp))), 
96694                 /*location*/ parameter))
96695             ]));
96696             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
96697             ts.startOnNewLine(forStatement);
96698             prologueStatements.push(forStatement);
96699             if (parameter.name.kind !== 79 /* Identifier */) {
96700                 // do the actual destructuring of the rest parameter if necessary
96701                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
96702                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
96703             }
96704             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
96705             return true;
96706         }
96707         /**
96708          * Adds a statement to capture the `this` of a function declaration if it is needed.
96709          * NOTE: This must be executed *after* the subtree has been visited.
96710          *
96711          * @param statements The statements for the new function body.
96712          * @param node A node.
96713          */
96714         function insertCaptureThisForNodeIfNeeded(statements, node) {
96715             if (hierarchyFacts & 65536 /* CapturedLexicalThis */ && node.kind !== 213 /* ArrowFunction */) {
96716                 insertCaptureThisForNode(statements, node, factory.createThis());
96717                 return true;
96718             }
96719             return false;
96720         }
96721         function insertCaptureThisForNode(statements, node, initializer) {
96722             enableSubstitutionsForCapturedThis();
96723             var captureThisStatement = factory.createVariableStatement(
96724             /*modifiers*/ undefined, factory.createVariableDeclarationList([
96725                 factory.createVariableDeclaration(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), 
96726                 /*exclamationToken*/ undefined, 
96727                 /*type*/ undefined, initializer)
96728             ]));
96729             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
96730             ts.setSourceMapRange(captureThisStatement, node);
96731             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
96732         }
96733         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
96734             if (hierarchyFacts & 32768 /* NewTarget */) {
96735                 var newTarget = void 0;
96736                 switch (node.kind) {
96737                     case 213 /* ArrowFunction */:
96738                         return statements;
96739                     case 168 /* MethodDeclaration */:
96740                     case 171 /* GetAccessor */:
96741                     case 172 /* SetAccessor */:
96742                         // Methods and accessors cannot be constructors, so 'new.target' will
96743                         // always return 'undefined'.
96744                         newTarget = factory.createVoidZero();
96745                         break;
96746                     case 170 /* Constructor */:
96747                         // Class constructors can only be called with `new`, so `this.constructor`
96748                         // should be relatively safe to use.
96749                         newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor");
96750                         break;
96751                     case 255 /* FunctionDeclaration */:
96752                     case 212 /* FunctionExpression */:
96753                         // Functions can be called or constructed, and may have a `this` due to
96754                         // being a member or when calling an imported function via `other_1.f()`.
96755                         newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 102 /* InstanceOfKeyword */, factory.getLocalName(node))), 
96756                         /*questionToken*/ undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"), 
96757                         /*colonToken*/ undefined, factory.createVoidZero());
96758                         break;
96759                     default:
96760                         return ts.Debug.failBadSyntaxKind(node);
96761                 }
96762                 var captureNewTargetStatement = factory.createVariableStatement(
96763                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
96764                     factory.createVariableDeclaration(factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), 
96765                     /*exclamationToken*/ undefined, 
96766                     /*type*/ undefined, newTarget)
96767                 ]));
96768                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
96769                 if (copyOnWrite) {
96770                     statements = statements.slice();
96771                 }
96772                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
96773             }
96774             return statements;
96775         }
96776         /**
96777          * Adds statements to the class body function for a class to define the members of the
96778          * class.
96779          *
96780          * @param statements The statements for the class body function.
96781          * @param node The ClassExpression or ClassDeclaration node.
96782          */
96783         function addClassMembers(statements, node) {
96784             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
96785                 var member = _a[_i];
96786                 switch (member.kind) {
96787                     case 233 /* SemicolonClassElement */:
96788                         statements.push(transformSemicolonClassElementToStatement(member));
96789                         break;
96790                     case 168 /* MethodDeclaration */:
96791                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
96792                         break;
96793                     case 171 /* GetAccessor */:
96794                     case 172 /* SetAccessor */:
96795                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
96796                         if (member === accessors.firstAccessor) {
96797                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
96798                         }
96799                         break;
96800                     case 170 /* Constructor */:
96801                     case 169 /* ClassStaticBlockDeclaration */:
96802                         // Constructors are handled in visitClassExpression/visitClassDeclaration
96803                         break;
96804                     default:
96805                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
96806                         break;
96807                 }
96808             }
96809         }
96810         /**
96811          * Transforms a SemicolonClassElement into a statement for a class body function.
96812          *
96813          * @param member The SemicolonClassElement node.
96814          */
96815         function transformSemicolonClassElementToStatement(member) {
96816             return ts.setTextRange(factory.createEmptyStatement(), member);
96817         }
96818         /**
96819          * Transforms a MethodDeclaration into a statement for a class body function.
96820          *
96821          * @param receiver The receiver for the member.
96822          * @param member The MethodDeclaration node.
96823          */
96824         function transformClassMethodDeclarationToStatement(receiver, member, container) {
96825             var commentRange = ts.getCommentRange(member);
96826             var sourceMapRange = ts.getSourceMapRange(member);
96827             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
96828             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
96829             var e;
96830             if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) {
96831                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
96832                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
96833                         : propertyName;
96834                 e = factory.createObjectDefinePropertyCall(receiver, name, factory.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
96835             }
96836             else {
96837                 var memberName = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ member.name);
96838                 e = factory.createAssignment(memberName, memberFunction);
96839             }
96840             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
96841             ts.setSourceMapRange(memberFunction, sourceMapRange);
96842             var statement = ts.setTextRange(factory.createExpressionStatement(e), /*location*/ member);
96843             ts.setOriginalNode(statement, member);
96844             ts.setCommentRange(statement, commentRange);
96845             // The location for the statement is used to emit comments only.
96846             // No source map should be emitted for this statement to align with the
96847             // old emitter.
96848             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
96849             return statement;
96850         }
96851         /**
96852          * Transforms a set of related of get/set accessors into a statement for a class body function.
96853          *
96854          * @param receiver The receiver for the member.
96855          * @param accessors The set of related get/set accessors.
96856          */
96857         function transformAccessorsToStatement(receiver, accessors, container) {
96858             var statement = factory.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
96859             // The location for the statement is used to emit source maps only.
96860             // No comments should be emitted for this statement to align with the
96861             // old emitter.
96862             ts.setEmitFlags(statement, 1536 /* NoComments */);
96863             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
96864             return statement;
96865         }
96866         /**
96867          * Transforms a set of related get/set accessors into an expression for either a class
96868          * body function or an ObjectLiteralExpression with computed properties.
96869          *
96870          * @param receiver The receiver for the member.
96871          */
96872         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
96873             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
96874             // To align with source maps in the old emitter, the receiver and property name
96875             // arguments are both mapped contiguously to the accessor name.
96876             // TODO(rbuckton): Does this need to be parented?
96877             var target = ts.setParent(ts.setTextRange(factory.cloneNode(receiver), receiver), receiver.parent);
96878             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
96879             ts.setSourceMapRange(target, firstAccessor.name);
96880             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
96881             if (ts.isPrivateIdentifier(visitedAccessorName)) {
96882                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
96883             }
96884             var propertyName = ts.createExpressionForPropertyName(factory, visitedAccessorName);
96885             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
96886             ts.setSourceMapRange(propertyName, firstAccessor.name);
96887             var properties = [];
96888             if (getAccessor) {
96889                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
96890                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
96891                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
96892                 var getter = factory.createPropertyAssignment("get", getterFunction);
96893                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
96894                 properties.push(getter);
96895             }
96896             if (setAccessor) {
96897                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
96898                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
96899                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
96900                 var setter = factory.createPropertyAssignment("set", setterFunction);
96901                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
96902                 properties.push(setter);
96903             }
96904             properties.push(factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), factory.createPropertyAssignment("configurable", factory.createTrue()));
96905             var call = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
96906             /*typeArguments*/ undefined, [
96907                 target,
96908                 propertyName,
96909                 factory.createObjectLiteralExpression(properties, /*multiLine*/ true)
96910             ]);
96911             if (startsOnNewLine) {
96912                 ts.startOnNewLine(call);
96913             }
96914             return call;
96915         }
96916         /**
96917          * Visits an ArrowFunction and transforms it into a FunctionExpression.
96918          *
96919          * @param node An ArrowFunction node.
96920          */
96921         function visitArrowFunction(node) {
96922             if (node.transformFlags & 8192 /* ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) {
96923                 hierarchyFacts |= 65536 /* CapturedLexicalThis */;
96924             }
96925             var savedConvertedLoopState = convertedLoopState;
96926             convertedLoopState = undefined;
96927             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
96928             var func = factory.createFunctionExpression(
96929             /*modifiers*/ undefined, 
96930             /*asteriskToken*/ undefined, 
96931             /*name*/ undefined, 
96932             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
96933             /*type*/ undefined, transformFunctionBody(node));
96934             ts.setTextRange(func, node);
96935             ts.setOriginalNode(func, node);
96936             ts.setEmitFlags(func, 8 /* CapturesThis */);
96937             // If an arrow function contains
96938             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
96939             convertedLoopState = savedConvertedLoopState;
96940             return func;
96941         }
96942         /**
96943          * Visits a FunctionExpression node.
96944          *
96945          * @param node a FunctionExpression node.
96946          */
96947         function visitFunctionExpression(node) {
96948             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
96949                 ? enterSubtree(32662 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
96950                 : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
96951             var savedConvertedLoopState = convertedLoopState;
96952             convertedLoopState = undefined;
96953             var parameters = ts.visitParameterList(node.parameters, visitor, context);
96954             var body = transformFunctionBody(node);
96955             var name = hierarchyFacts & 32768 /* NewTarget */
96956                 ? factory.getLocalName(node)
96957                 : node.name;
96958             exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
96959             convertedLoopState = savedConvertedLoopState;
96960             return factory.updateFunctionExpression(node, 
96961             /*modifiers*/ undefined, node.asteriskToken, name, 
96962             /*typeParameters*/ undefined, parameters, 
96963             /*type*/ undefined, body);
96964         }
96965         /**
96966          * Visits a FunctionDeclaration node.
96967          *
96968          * @param node a FunctionDeclaration node.
96969          */
96970         function visitFunctionDeclaration(node) {
96971             var savedConvertedLoopState = convertedLoopState;
96972             convertedLoopState = undefined;
96973             var ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
96974             var parameters = ts.visitParameterList(node.parameters, visitor, context);
96975             var body = transformFunctionBody(node);
96976             var name = hierarchyFacts & 32768 /* NewTarget */
96977                 ? factory.getLocalName(node)
96978                 : node.name;
96979             exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
96980             convertedLoopState = savedConvertedLoopState;
96981             return factory.updateFunctionDeclaration(node, 
96982             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
96983             /*typeParameters*/ undefined, parameters, 
96984             /*type*/ undefined, body);
96985         }
96986         /**
96987          * Transforms a function-like node into a FunctionExpression.
96988          *
96989          * @param node The function-like node to transform.
96990          * @param location The source-map location for the new FunctionExpression.
96991          * @param name The name of the new FunctionExpression.
96992          */
96993         function transformFunctionLikeToExpression(node, location, name, container) {
96994             var savedConvertedLoopState = convertedLoopState;
96995             convertedLoopState = undefined;
96996             var ancestorFacts = container && ts.isClassLike(container) && !ts.isStatic(node)
96997                 ? enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
96998                 : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
96999             var parameters = ts.visitParameterList(node.parameters, visitor, context);
97000             var body = transformFunctionBody(node);
97001             if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 255 /* FunctionDeclaration */ || node.kind === 212 /* FunctionExpression */)) {
97002                 name = factory.getGeneratedNameForNode(node);
97003             }
97004             exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
97005             convertedLoopState = savedConvertedLoopState;
97006             return ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
97007             /*modifiers*/ undefined, node.asteriskToken, name, 
97008             /*typeParameters*/ undefined, parameters, 
97009             /*type*/ undefined, body), location), 
97010             /*original*/ node);
97011         }
97012         /**
97013          * Transforms the body of a function-like node.
97014          *
97015          * @param node A function-like node.
97016          */
97017         function transformFunctionBody(node) {
97018             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
97019             var singleLine = false; // indicates whether the block *may* be emitted as a single line
97020             var statementsLocation;
97021             var closeBraceLocation;
97022             var prologue = [];
97023             var statements = [];
97024             var body = node.body;
97025             var statementOffset;
97026             resumeLexicalEnvironment();
97027             if (ts.isBlock(body)) {
97028                 // ensureUseStrict is false because no new prologue-directive should be added.
97029                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
97030                 statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
97031                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction);
97032                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement);
97033             }
97034             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
97035             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
97036             if (ts.isBlock(body)) {
97037                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
97038                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
97039                 statementsLocation = body.statements;
97040                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
97041                 // If the original body was a multi-line block, this must be a multi-line block.
97042                 if (!multiLine && body.multiLine) {
97043                     multiLine = true;
97044                 }
97045             }
97046             else {
97047                 ts.Debug.assert(node.kind === 213 /* ArrowFunction */);
97048                 // To align with the old emitter, we use a synthetic end position on the location
97049                 // for the statement list we synthesize when we down-level an arrow function with
97050                 // an expression function body. This prevents both comments and source maps from
97051                 // being emitted for the end position only.
97052                 statementsLocation = ts.moveRangeEnd(body, -1);
97053                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
97054                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
97055                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
97056                         singleLine = true;
97057                     }
97058                     else {
97059                         multiLine = true;
97060                     }
97061                 }
97062                 var expression = ts.visitNode(body, visitor, ts.isExpression);
97063                 var returnStatement = factory.createReturnStatement(expression);
97064                 ts.setTextRange(returnStatement, body);
97065                 ts.moveSyntheticComments(returnStatement, body);
97066                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
97067                 statements.push(returnStatement);
97068                 // To align with the source map emit for the old emitter, we set a custom
97069                 // source map location for the close brace.
97070                 closeBraceLocation = body;
97071             }
97072             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
97073             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
97074             insertCaptureThisForNodeIfNeeded(prologue, node);
97075             // If we added any final generated statements, this must be a multi-line block
97076             if (ts.some(prologue)) {
97077                 multiLine = true;
97078             }
97079             statements.unshift.apply(statements, prologue);
97080             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
97081                 // no changes were made, preserve the tree
97082                 return body;
97083             }
97084             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), multiLine);
97085             ts.setTextRange(block, node.body);
97086             if (!multiLine && singleLine) {
97087                 ts.setEmitFlags(block, 1 /* SingleLine */);
97088             }
97089             if (closeBraceLocation) {
97090                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
97091             }
97092             ts.setOriginalNode(block, node.body);
97093             return block;
97094         }
97095         function visitBlock(node, isFunctionBody) {
97096             if (isFunctionBody) {
97097                 // A function body is not a block scope.
97098                 return ts.visitEachChild(node, visitor, context);
97099             }
97100             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
97101                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
97102                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
97103             var updated = ts.visitEachChild(node, visitor, context);
97104             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
97105             return updated;
97106         }
97107         /**
97108          * Visits an ExpressionStatement that contains a destructuring assignment.
97109          *
97110          * @param node An ExpressionStatement node.
97111          */
97112         function visitExpressionStatement(node) {
97113             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
97114         }
97115         /**
97116          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
97117          *
97118          * @param node A ParenthesizedExpression node.
97119          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
97120          * expression of an `ExpressionStatement`).
97121          */
97122         function visitParenthesizedExpression(node, expressionResultIsUnused) {
97123             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
97124         }
97125         /**
97126          * Visits a BinaryExpression that contains a destructuring assignment.
97127          *
97128          * @param node A BinaryExpression node.
97129          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
97130          * expression of an `ExpressionStatement`).
97131          */
97132         function visitBinaryExpression(node, expressionResultIsUnused) {
97133             // If we are here it is because this is a destructuring assignment.
97134             if (ts.isDestructuringAssignment(node)) {
97135                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !expressionResultIsUnused);
97136             }
97137             if (node.operatorToken.kind === 27 /* CommaToken */) {
97138                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
97139             }
97140             return ts.visitEachChild(node, visitor, context);
97141         }
97142         /**
97143          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
97144          * expression of an `ExpressionStatement`).
97145          */
97146         function visitCommaListExpression(node, expressionResultIsUnused) {
97147             if (expressionResultIsUnused) {
97148                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
97149             }
97150             var result;
97151             for (var i = 0; i < node.elements.length; i++) {
97152                 var element = node.elements[i];
97153                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
97154                 if (result || visited !== element) {
97155                     result || (result = node.elements.slice(0, i));
97156                     result.push(visited);
97157                 }
97158             }
97159             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
97160             return factory.updateCommaListExpression(node, elements);
97161         }
97162         function isVariableStatementOfTypeScriptClassWrapper(node) {
97163             return node.declarationList.declarations.length === 1
97164                 && !!node.declarationList.declarations[0].initializer
97165                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
97166         }
97167         function visitVariableStatement(node) {
97168             var ancestorFacts = enterSubtree(0 /* None */, ts.hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
97169             var updated;
97170             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
97171                 // we are inside a converted loop - hoist variable declarations
97172                 var assignments = void 0;
97173                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
97174                     var decl = _a[_i];
97175                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
97176                     if (decl.initializer) {
97177                         var assignment = void 0;
97178                         if (ts.isBindingPattern(decl.name)) {
97179                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
97180                         }
97181                         else {
97182                             assignment = factory.createBinaryExpression(decl.name, 63 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
97183                             ts.setTextRange(assignment, decl);
97184                         }
97185                         assignments = ts.append(assignments, assignment);
97186                     }
97187                 }
97188                 if (assignments) {
97189                     updated = ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(assignments)), node);
97190                 }
97191                 else {
97192                     // none of declarations has initializer - the entire variable statement can be deleted
97193                     updated = undefined;
97194                 }
97195             }
97196             else {
97197                 updated = ts.visitEachChild(node, visitor, context);
97198             }
97199             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
97200             return updated;
97201         }
97202         /**
97203          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
97204          *
97205          * @param node A VariableDeclarationList node.
97206          */
97207         function visitVariableDeclarationList(node) {
97208             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) {
97209                 if (node.flags & 3 /* BlockScoped */) {
97210                     enableSubstitutionsForBlockScopedBindings();
97211                 }
97212                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
97213                     ? visitVariableDeclarationInLetDeclarationList
97214                     : visitVariableDeclaration);
97215                 var declarationList = factory.createVariableDeclarationList(declarations);
97216                 ts.setOriginalNode(declarationList, node);
97217                 ts.setTextRange(declarationList, node);
97218                 ts.setCommentRange(declarationList, node);
97219                 // If the first or last declaration is a binding pattern, we need to modify
97220                 // the source map range for the declaration list.
97221                 if (node.transformFlags & 262144 /* ContainsBindingPattern */
97222                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
97223                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
97224                 }
97225                 return declarationList;
97226             }
97227             return ts.visitEachChild(node, visitor, context);
97228         }
97229         function getRangeUnion(declarations) {
97230             // declarations may not be sorted by position.
97231             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
97232             var pos = -1, end = -1;
97233             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
97234                 var node = declarations_9[_i];
97235                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
97236                 end = Math.max(end, node.end);
97237             }
97238             return ts.createRange(pos, end);
97239         }
97240         /**
97241          * Gets a value indicating whether we should emit an explicit initializer for a variable
97242          * declaration in a `let` declaration list.
97243          *
97244          * @param node A VariableDeclaration node.
97245          */
97246         function shouldEmitExplicitInitializerForLetDeclaration(node) {
97247             // Nested let bindings might need to be initialized explicitly to preserve
97248             // ES6 semantic:
97249             //
97250             //  { let x = 1; }
97251             //  { let x; } // x here should be undefined. not 1
97252             //
97253             // Top level bindings never collide with anything and thus don't require
97254             // explicit initialization. As for nested let bindings there are two cases:
97255             //
97256             // - Nested let bindings that were not renamed definitely should be
97257             //   initialized explicitly:
97258             //
97259             //    { let x = 1; }
97260             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
97261             //
97262             //   Without explicit initialization code in /*1*/ can be executed even if
97263             //   some-condition is evaluated to false.
97264             //
97265             // - Renaming introduces fresh name that should not collide with any
97266             //   existing names, however renamed bindings sometimes also should be
97267             //   explicitly initialized. One particular case: non-captured binding
97268             //   declared inside loop body (but not in loop initializer):
97269             //
97270             //    let x;
97271             //    for (;;) {
97272             //        let x;
97273             //    }
97274             //
97275             //   In downlevel codegen inner 'x' will be renamed so it won't collide
97276             //   with outer 'x' however it will should be reset on every iteration as
97277             //   if it was declared anew.
97278             //
97279             //   * Why non-captured binding?
97280             //     - Because if loop contains block scoped binding captured in some
97281             //       function then loop body will be rewritten to have a fresh scope
97282             //       on every iteration so everything will just work.
97283             //
97284             //   * Why loop initializer is excluded?
97285             //     - Since we've introduced a fresh name it already will be undefined.
97286             var flags = resolver.getNodeCheckFlags(node);
97287             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
97288             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
97289             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
97290                 || (isCapturedInFunction
97291                     && isDeclaredInLoop
97292                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
97293             var emitExplicitInitializer = !emittedAsTopLevel
97294                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
97295                 && (!resolver.isDeclarationWithCollidingName(node)
97296                     || (isDeclaredInLoop
97297                         && !isCapturedInFunction
97298                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
97299             return emitExplicitInitializer;
97300         }
97301         /**
97302          * Visits a VariableDeclaration in a `let` declaration list.
97303          *
97304          * @param node A VariableDeclaration node.
97305          */
97306         function visitVariableDeclarationInLetDeclarationList(node) {
97307             // For binding pattern names that lack initializers there is no point to emit
97308             // explicit initializer since downlevel codegen for destructuring will fail
97309             // in the absence of initializer so all binding elements will say uninitialized
97310             var name = node.name;
97311             if (ts.isBindingPattern(name)) {
97312                 return visitVariableDeclaration(node);
97313             }
97314             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
97315                 return factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createVoidZero());
97316             }
97317             return ts.visitEachChild(node, visitor, context);
97318         }
97319         /**
97320          * Visits a VariableDeclaration node with a binding pattern.
97321          *
97322          * @param node A VariableDeclaration node.
97323          */
97324         function visitVariableDeclaration(node) {
97325             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
97326             var updated;
97327             if (ts.isBindingPattern(node.name)) {
97328                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
97329                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
97330             }
97331             else {
97332                 updated = ts.visitEachChild(node, visitor, context);
97333             }
97334             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
97335             return updated;
97336         }
97337         function recordLabel(node) {
97338             convertedLoopState.labels.set(ts.idText(node.label), true);
97339         }
97340         function resetLabel(node) {
97341             convertedLoopState.labels.set(ts.idText(node.label), false);
97342         }
97343         function visitLabeledStatement(node) {
97344             if (convertedLoopState && !convertedLoopState.labels) {
97345                 convertedLoopState.labels = new ts.Map();
97346             }
97347             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
97348             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
97349                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
97350                 : factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node, convertedLoopState && resetLabel);
97351         }
97352         function visitIterationStatement(node, outermostLabeledStatement) {
97353             switch (node.kind) {
97354                 case 239 /* DoStatement */:
97355                 case 240 /* WhileStatement */:
97356                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
97357                 case 241 /* ForStatement */:
97358                     return visitForStatement(node, outermostLabeledStatement);
97359                 case 242 /* ForInStatement */:
97360                     return visitForInStatement(node, outermostLabeledStatement);
97361                 case 243 /* ForOfStatement */:
97362                     return visitForOfStatement(node, outermostLabeledStatement);
97363             }
97364         }
97365         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
97366             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
97367             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
97368             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
97369             return updated;
97370         }
97371         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
97372             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
97373         }
97374         function visitForStatement(node, outermostLabeledStatement) {
97375             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
97376         }
97377         function visitEachChildOfForStatement(node) {
97378             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));
97379         }
97380         function visitForInStatement(node, outermostLabeledStatement) {
97381             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
97382         }
97383         function visitForOfStatement(node, outermostLabeledStatement) {
97384             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
97385         }
97386         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
97387             var statements = [];
97388             var initializer = node.initializer;
97389             if (ts.isVariableDeclarationList(initializer)) {
97390                 if (node.initializer.flags & 3 /* BlockScoped */) {
97391                     enableSubstitutionsForBlockScopedBindings();
97392                 }
97393                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
97394                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
97395                     // This works whether the declaration is a var, let, or const.
97396                     // It will use rhsIterationValue _a[_i] as the initializer.
97397                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
97398                     var declarationList = ts.setTextRange(factory.createVariableDeclarationList(declarations), node.initializer);
97399                     ts.setOriginalNode(declarationList, node.initializer);
97400                     // Adjust the source map range for the first declaration to align with the old
97401                     // emitter.
97402                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
97403                     statements.push(factory.createVariableStatement(
97404                     /*modifiers*/ undefined, declarationList));
97405                 }
97406                 else {
97407                     // The following call does not include the initializer, so we have
97408                     // to emit it separately.
97409                     statements.push(ts.setTextRange(factory.createVariableStatement(
97410                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclarationList([
97411                         factory.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined), 
97412                         /*exclamationToken*/ undefined, 
97413                         /*type*/ undefined, boundValue)
97414                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
97415                 }
97416             }
97417             else {
97418                 // Initializer is an expression. Emit the expression in the body, so that it's
97419                 // evaluated on every iteration.
97420                 var assignment = factory.createAssignment(initializer, boundValue);
97421                 if (ts.isDestructuringAssignment(assignment)) {
97422                     statements.push(factory.createExpressionStatement(visitBinaryExpression(assignment, /*expressionResultIsUnused*/ true)));
97423                 }
97424                 else {
97425                     ts.setTextRangeEnd(assignment, initializer.end);
97426                     statements.push(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
97427                 }
97428             }
97429             if (convertedLoopBodyStatements) {
97430                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
97431             }
97432             else {
97433                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
97434                 if (ts.isBlock(statement)) {
97435                     return factory.updateBlock(statement, ts.setTextRange(factory.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
97436                 }
97437                 else {
97438                     statements.push(statement);
97439                     return createSyntheticBlockForConvertedStatements(statements);
97440                 }
97441             }
97442         }
97443         function createSyntheticBlockForConvertedStatements(statements) {
97444             return ts.setEmitFlags(factory.createBlock(factory.createNodeArray(statements), 
97445             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
97446         }
97447         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
97448             // The following ES6 code:
97449             //
97450             //    for (let v of expr) { }
97451             //
97452             // should be emitted as
97453             //
97454             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
97455             //        var v = _a[_i];
97456             //    }
97457             //
97458             // where _a and _i are temps emitted to capture the RHS and the counter,
97459             // respectively.
97460             // When the left hand side is an expression instead of a let declaration,
97461             // the "let v" is not emitted.
97462             // When the left hand side is a let/const, the v is renamed if there is
97463             // another v in scope.
97464             // Note that all assignments to the LHS are emitted in the body, including
97465             // all destructuring.
97466             // Note also that because an extra statement is needed to assign to the LHS,
97467             // for-of bodies are always emitted as blocks.
97468             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
97469             // In the case where the user wrote an identifier as the RHS, like this:
97470             //
97471             //     for (let v of arr) { }
97472             //
97473             // we don't want to emit a temporary variable for the RHS, just use it directly.
97474             var counter = factory.createLoopVariable();
97475             var rhsReference = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
97476             // The old emitter does not emit source maps for the expression
97477             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
97478             var forStatement = ts.setTextRange(factory.createForStatement(
97479             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
97480                 ts.setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), ts.moveRangePos(node.expression, -1)),
97481                 ts.setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression)
97482             ]), node.expression), 2097152 /* NoHoisting */), 
97483             /*condition*/ ts.setTextRange(factory.createLessThan(counter, factory.createPropertyAccessExpression(rhsReference, "length")), node.expression), 
97484             /*incrementor*/ ts.setTextRange(factory.createPostfixIncrement(counter), node.expression), 
97485             /*statement*/ convertForOfStatementHead(node, factory.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)), 
97486             /*location*/ node);
97487             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
97488             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
97489             ts.setTextRange(forStatement, node);
97490             return factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
97491         }
97492         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
97493             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
97494             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
97495             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
97496             var errorRecord = factory.createUniqueName("e");
97497             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
97498             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
97499             var values = ts.setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
97500             var next = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
97501             hoistVariableDeclaration(errorRecord);
97502             hoistVariableDeclaration(returnMethod);
97503             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
97504             var initializer = ancestorFacts & 1024 /* IterationContainer */
97505                 ? factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), values])
97506                 : values;
97507             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
97508             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
97509                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
97510                 factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next)
97511             ]), node.expression), 2097152 /* NoHoisting */), 
97512             /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")), 
97513             /*incrementor*/ factory.createAssignment(result, next), 
97514             /*statement*/ convertForOfStatementHead(node, factory.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)), 
97515             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
97516             return factory.createTryStatement(factory.createBlock([
97517                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
97518             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
97519                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
97520                     factory.createPropertyAssignment("error", catchVariable)
97521                 ])))
97522             ]), 1 /* SingleLine */)), factory.createBlock([
97523                 factory.createTryStatement(
97524                 /*tryBlock*/ factory.createBlock([
97525                     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 */),
97526                 ]), 
97527                 /*catchClause*/ undefined, 
97528                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
97529                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
97530                 ]), 1 /* SingleLine */))
97531             ]));
97532         }
97533         /**
97534          * Visits an ObjectLiteralExpression with computed property names.
97535          *
97536          * @param node An ObjectLiteralExpression node.
97537          */
97538         function visitObjectLiteralExpression(node) {
97539             var properties = node.properties;
97540             // Find the first computed property.
97541             // Everything until that point can be emitted as part of the initial object literal.
97542             var numInitialProperties = -1, hasComputed = false;
97543             for (var i = 0; i < properties.length; i++) {
97544                 var property = properties[i];
97545                 if ((property.transformFlags & 524288 /* ContainsYield */ &&
97546                     hierarchyFacts & 4 /* AsyncFunctionBody */)
97547                     || (hasComputed = ts.Debug.checkDefined(property.name).kind === 161 /* ComputedPropertyName */)) {
97548                     numInitialProperties = i;
97549                     break;
97550                 }
97551             }
97552             if (numInitialProperties < 0) {
97553                 return ts.visitEachChild(node, visitor, context);
97554             }
97555             // For computed properties, we need to create a unique handle to the object
97556             // literal so we can modify it without risking internal assignments tainting the object.
97557             var temp = factory.createTempVariable(hoistVariableDeclaration);
97558             // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
97559             var expressions = [];
97560             var assignment = factory.createAssignment(temp, ts.setEmitFlags(factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 65536 /* Indented */ : 0));
97561             if (node.multiLine) {
97562                 ts.startOnNewLine(assignment);
97563             }
97564             expressions.push(assignment);
97565             addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
97566             // We need to clone the temporary identifier so that we can write it on a
97567             // new line
97568             expressions.push(node.multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
97569             return factory.inlineExpressions(expressions);
97570         }
97571         function shouldConvertPartOfIterationStatement(node) {
97572             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
97573         }
97574         function shouldConvertInitializerOfForStatement(node) {
97575             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
97576         }
97577         function shouldConvertConditionOfForStatement(node) {
97578             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
97579         }
97580         function shouldConvertIncrementorOfForStatement(node) {
97581             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
97582         }
97583         function shouldConvertIterationStatement(node) {
97584             return shouldConvertBodyOfIterationStatement(node)
97585                 || shouldConvertInitializerOfForStatement(node);
97586         }
97587         function shouldConvertBodyOfIterationStatement(node) {
97588             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
97589         }
97590         /**
97591          * Records constituents of name for the given variable to be hoisted in the outer scope.
97592          */
97593         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
97594             if (!state.hoistedLocalVariables) {
97595                 state.hoistedLocalVariables = [];
97596             }
97597             visit(node.name);
97598             function visit(node) {
97599                 if (node.kind === 79 /* Identifier */) {
97600                     state.hoistedLocalVariables.push(node);
97601                 }
97602                 else {
97603                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
97604                         var element = _a[_i];
97605                         if (!ts.isOmittedExpression(element)) {
97606                             visit(element.name);
97607                         }
97608                     }
97609                 }
97610             }
97611         }
97612         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
97613             if (!shouldConvertIterationStatement(node)) {
97614                 var saveAllowedNonLabeledJumps = void 0;
97615                 if (convertedLoopState) {
97616                     // we get here if we are trying to emit normal loop loop inside converted loop
97617                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
97618                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
97619                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
97620                 }
97621                 var result = convert
97622                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
97623                     : factory.restoreEnclosingLabel(ts.isForStatement(node) ? visitEachChildOfForStatement(node) : ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
97624                 if (convertedLoopState) {
97625                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
97626                 }
97627                 return result;
97628             }
97629             var currentState = createConvertedLoopState(node);
97630             var statements = [];
97631             var outerConvertedLoopState = convertedLoopState;
97632             convertedLoopState = currentState;
97633             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
97634             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
97635             convertedLoopState = outerConvertedLoopState;
97636             if (initializerFunction)
97637                 statements.push(initializerFunction.functionDeclaration);
97638             if (bodyFunction)
97639                 statements.push(bodyFunction.functionDeclaration);
97640             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
97641             if (initializerFunction) {
97642                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
97643             }
97644             var loop;
97645             if (bodyFunction) {
97646                 if (convert) {
97647                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
97648                 }
97649                 else {
97650                     var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true));
97651                     loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
97652                 }
97653             }
97654             else {
97655                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
97656                 loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
97657             }
97658             statements.push(loop);
97659             return statements;
97660         }
97661         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
97662             switch (node.kind) {
97663                 case 241 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
97664                 case 242 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
97665                 case 243 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
97666                 case 239 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
97667                 case 240 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
97668                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
97669             }
97670         }
97671         function convertForStatement(node, initializerFunction, convertedLoopBody) {
97672             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
97673             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
97674             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);
97675         }
97676         function convertForOfStatement(node, convertedLoopBody) {
97677             return factory.updateForOfStatement(node, 
97678             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
97679         }
97680         function convertForInStatement(node, convertedLoopBody) {
97681             return factory.updateForInStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
97682         }
97683         function convertDoStatement(node, convertedLoopBody) {
97684             return factory.updateDoStatement(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
97685         }
97686         function convertWhileStatement(node, convertedLoopBody) {
97687             return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
97688         }
97689         function createConvertedLoopState(node) {
97690             var loopInitializer;
97691             switch (node.kind) {
97692                 case 241 /* ForStatement */:
97693                 case 242 /* ForInStatement */:
97694                 case 243 /* ForOfStatement */:
97695                     var initializer = node.initializer;
97696                     if (initializer && initializer.kind === 254 /* VariableDeclarationList */) {
97697                         loopInitializer = initializer;
97698                     }
97699                     break;
97700             }
97701             // variables that will be passed to the loop as parameters
97702             var loopParameters = [];
97703             // variables declared in the loop initializer that will be changed inside the loop
97704             var loopOutParameters = [];
97705             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
97706                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
97707                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
97708                     var decl = _a[_i];
97709                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
97710                 }
97711             }
97712             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
97713             if (convertedLoopState) {
97714                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
97715                 // if outer converted loop has already accumulated some state - pass it through
97716                 if (convertedLoopState.argumentsName) {
97717                     // outer loop has already used 'arguments' so we've already have some name to alias it
97718                     // use the same name in all nested loops
97719                     currentState.argumentsName = convertedLoopState.argumentsName;
97720                 }
97721                 if (convertedLoopState.thisName) {
97722                     // outer loop has already used 'this' so we've already have some name to alias it
97723                     // use the same name in all nested loops
97724                     currentState.thisName = convertedLoopState.thisName;
97725                 }
97726                 if (convertedLoopState.hoistedLocalVariables) {
97727                     // we've already collected some non-block scoped variable declarations in enclosing loop
97728                     // use the same storage in nested loop
97729                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
97730                 }
97731             }
97732             return currentState;
97733         }
97734         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
97735             var extraVariableDeclarations;
97736             // propagate state from the inner loop to the outer loop if necessary
97737             if (state.argumentsName) {
97738                 // if alias for arguments is set
97739                 if (outerState) {
97740                     // pass it to outer converted loop
97741                     outerState.argumentsName = state.argumentsName;
97742                 }
97743                 else {
97744                     // this is top level converted loop and we need to create an alias for 'arguments' object
97745                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.argumentsName, 
97746                     /*exclamationToken*/ undefined, 
97747                     /*type*/ undefined, factory.createIdentifier("arguments")));
97748                 }
97749             }
97750             if (state.thisName) {
97751                 // if alias for this is set
97752                 if (outerState) {
97753                     // pass it to outer converted loop
97754                     outerState.thisName = state.thisName;
97755                 }
97756                 else {
97757                     // this is top level converted loop so we need to create an alias for 'this' here
97758                     // NOTE:
97759                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
97760                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
97761                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.thisName, 
97762                     /*exclamationToken*/ undefined, 
97763                     /*type*/ undefined, factory.createIdentifier("this")));
97764                 }
97765             }
97766             if (state.hoistedLocalVariables) {
97767                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
97768                 if (outerState) {
97769                     // pass them to outer converted loop
97770                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
97771                 }
97772                 else {
97773                     if (!extraVariableDeclarations) {
97774                         extraVariableDeclarations = [];
97775                     }
97776                     // hoist collected variable declarations
97777                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
97778                         var identifier = _a[_i];
97779                         extraVariableDeclarations.push(factory.createVariableDeclaration(identifier));
97780                     }
97781                 }
97782             }
97783             // add extra variables to hold out parameters if necessary
97784             if (state.loopOutParameters.length) {
97785                 if (!extraVariableDeclarations) {
97786                     extraVariableDeclarations = [];
97787                 }
97788                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
97789                     var outParam = _c[_b];
97790                     extraVariableDeclarations.push(factory.createVariableDeclaration(outParam.outParamName));
97791                 }
97792             }
97793             if (state.conditionVariable) {
97794                 if (!extraVariableDeclarations) {
97795                     extraVariableDeclarations = [];
97796                 }
97797                 extraVariableDeclarations.push(factory.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createFalse()));
97798             }
97799             // create variable statement to hold all introduced variable declarations
97800             if (extraVariableDeclarations) {
97801                 statements.push(factory.createVariableStatement(
97802                 /*modifiers*/ undefined, factory.createVariableDeclarationList(extraVariableDeclarations)));
97803             }
97804         }
97805         function createOutVariable(p) {
97806             return factory.createVariableDeclaration(p.originalName, /*exclamationToken*/ undefined, /*type*/ undefined, p.outParamName);
97807         }
97808         /**
97809          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
97810          * that is captured in a closure inside of the initializer. The `_loop_init` function is
97811          * used to preserve the per-iteration environment semantics of
97812          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
97813          */
97814         function createFunctionForInitializerOfForStatement(node, currentState) {
97815             var functionName = factory.createUniqueName("_loop_init");
97816             var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0;
97817             var emitFlags = 0 /* None */;
97818             if (currentState.containsLexicalThis)
97819                 emitFlags |= 8 /* CapturesThis */;
97820             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
97821                 emitFlags |= 262144 /* AsyncFunctionBody */;
97822             var statements = [];
97823             statements.push(factory.createVariableStatement(/*modifiers*/ undefined, node.initializer));
97824             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
97825             // This transforms the following ES2015 syntax:
97826             //
97827             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
97828             //      // loop body
97829             //  }
97830             //
97831             // Into the following ES5 syntax:
97832             //
97833             //  var _loop_init_1 = function () {
97834             //      var i = (setImmediate(() => console.log(i)), 0);
97835             //      out_i_1 = i;
97836             //  };
97837             //  var out_i_1;
97838             //  _loop_init_1();
97839             //  for (var i = out_i_1; i < 2; i++) {
97840             //      // loop body
97841             //  }
97842             //
97843             // Which prevents mutations to `i` in the per-iteration environment of the body
97844             // from affecting the initial value for `i` outside of the per-iteration environment.
97845             var functionDeclaration = factory.createVariableStatement(
97846             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
97847                 factory.createVariableDeclaration(functionName, 
97848                 /*exclamationToken*/ undefined, 
97849                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
97850                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
97851                 /*name*/ undefined, 
97852                 /*typeParameters*/ undefined, 
97853                 /*parameters*/ undefined, 
97854                 /*type*/ undefined, ts.visitNode(factory.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
97855             ]), 2097152 /* NoHoisting */));
97856             var part = factory.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
97857             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
97858         }
97859         /**
97860          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
97861          * that is captured in a closure inside of the loop body. The `_loop` function is used to
97862          * preserve the per-iteration environment semantics of
97863          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
97864          */
97865         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
97866             var functionName = factory.createUniqueName("_loop");
97867             startLexicalEnvironment();
97868             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
97869             var lexicalEnvironment = endLexicalEnvironment();
97870             var statements = [];
97871             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
97872                 // If a block-scoped variable declared in the initializer of `node` is captured in
97873                 // the condition or incrementor, we must move the condition and incrementor into
97874                 // the body of the for loop.
97875                 //
97876                 // This transforms the following ES2015 syntax:
97877                 //
97878                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
97879                 //      // loop body
97880                 //  }
97881                 //
97882                 // Into the following ES5 syntax:
97883                 //
97884                 //  var _loop_1 = function (i) {
97885                 //      if (inc_1)
97886                 //          setImmediate(() => console.log(i)), i++;
97887                 //      else
97888                 //          inc_1 = true;
97889                 //      if (!(setImmediate(() => console.log(i)), i < 2))
97890                 //          return out_i_1 = i, "break";
97891                 //      // loop body
97892                 //      out_i_1 = i;
97893                 //  }
97894                 //  var out_i_1, inc_1 = false;
97895                 //  for (var i = 0;;) {
97896                 //      var state_1 = _loop_1(i);
97897                 //      i = out_i_1;
97898                 //      if (state_1 === "break")
97899                 //          break;
97900                 //  }
97901                 //
97902                 // Which prevents mutations to `i` in the per-iteration environment of the body
97903                 // from affecting the value of `i` in the previous per-iteration environment.
97904                 //
97905                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
97906                 // environment that is carried over to the next iteration of the loop. As a result,
97907                 // we must indicate whether this is the first evaluation of the loop body so that
97908                 // we only evaluate the incrementor on subsequent evaluations.
97909                 currentState.conditionVariable = factory.createUniqueName("inc");
97910                 if (node.incrementor) {
97911                     statements.push(factory.createIfStatement(currentState.conditionVariable, factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
97912                 }
97913                 else {
97914                     statements.push(factory.createIfStatement(factory.createLogicalNot(currentState.conditionVariable), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
97915                 }
97916                 if (shouldConvertConditionOfForStatement(node)) {
97917                     statements.push(factory.createIfStatement(factory.createPrefixUnaryExpression(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(factory.createBreakStatement(), visitor, ts.isStatement)));
97918                 }
97919             }
97920             if (ts.isBlock(statement)) {
97921                 ts.addRange(statements, statement.statements);
97922             }
97923             else {
97924                 statements.push(statement);
97925             }
97926             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
97927             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
97928             var loopBody = factory.createBlock(statements, /*multiLine*/ true);
97929             if (ts.isBlock(statement))
97930                 ts.setOriginalNode(loopBody, statement);
97931             var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0;
97932             var emitFlags = 524288 /* ReuseTempVariableScope */;
97933             if (currentState.containsLexicalThis)
97934                 emitFlags |= 8 /* CapturesThis */;
97935             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
97936                 emitFlags |= 262144 /* AsyncFunctionBody */;
97937             // This transforms the following ES2015 syntax (in addition to other variations):
97938             //
97939             //  for (let i = 0; i < 2; i++) {
97940             //      setImmediate(() => console.log(i));
97941             //  }
97942             //
97943             // Into the following ES5 syntax:
97944             //
97945             //  var _loop_1 = function (i) {
97946             //      setImmediate(() => console.log(i));
97947             //  };
97948             //  for (var i = 0; i < 2; i++) {
97949             //      _loop_1(i);
97950             //  }
97951             var functionDeclaration = factory.createVariableStatement(
97952             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
97953                 factory.createVariableDeclaration(functionName, 
97954                 /*exclamationToken*/ undefined, 
97955                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
97956                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
97957                 /*name*/ undefined, 
97958                 /*typeParameters*/ undefined, currentState.loopParameters, 
97959                 /*type*/ undefined, loopBody), emitFlags))
97960             ]), 2097152 /* NoHoisting */));
97961             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
97962             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
97963         }
97964         function copyOutParameter(outParam, copyDirection) {
97965             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
97966             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
97967             return factory.createBinaryExpression(target, 63 /* EqualsToken */, source);
97968         }
97969         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
97970             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
97971                 var outParam = outParams_1[_i];
97972                 if (outParam.flags & partFlags) {
97973                     statements.push(factory.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
97974                 }
97975             }
97976         }
97977         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
97978             var call = factory.createCallExpression(initFunctionExpressionName, /*typeArguments*/ undefined, []);
97979             var callResult = containsYield
97980                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
97981                 : call;
97982             return factory.createExpressionStatement(callResult);
97983         }
97984         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
97985             var statements = [];
97986             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
97987             // simple loops are emitted as just 'loop()';
97988             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
97989             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
97990                 !state.labeledNonLocalBreaks &&
97991                 !state.labeledNonLocalContinues;
97992             var call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
97993             var callResult = containsYield
97994                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
97995                 : call;
97996             if (isSimpleLoop) {
97997                 statements.push(factory.createExpressionStatement(callResult));
97998                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
97999             }
98000             else {
98001                 var loopResultName = factory.createUniqueName("state");
98002                 var stateVariable = factory.createVariableStatement(
98003                 /*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)]));
98004                 statements.push(stateVariable);
98005                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
98006                 if (state.nonLocalJumps & 8 /* Return */) {
98007                     var returnStatement = void 0;
98008                     if (outerState) {
98009                         outerState.nonLocalJumps |= 8 /* Return */;
98010                         returnStatement = factory.createReturnStatement(loopResultName);
98011                     }
98012                     else {
98013                         returnStatement = factory.createReturnStatement(factory.createPropertyAccessExpression(loopResultName, "value"));
98014                     }
98015                     statements.push(factory.createIfStatement(factory.createTypeCheck(loopResultName, "object"), returnStatement));
98016                 }
98017                 if (state.nonLocalJumps & 2 /* Break */) {
98018                     statements.push(factory.createIfStatement(factory.createStrictEquality(loopResultName, factory.createStringLiteral("break")), factory.createBreakStatement()));
98019                 }
98020                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
98021                     var caseClauses = [];
98022                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
98023                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
98024                     statements.push(factory.createSwitchStatement(loopResultName, factory.createCaseBlock(caseClauses)));
98025                 }
98026             }
98027             return statements;
98028         }
98029         function setLabeledJump(state, isBreak, labelText, labelMarker) {
98030             if (isBreak) {
98031                 if (!state.labeledNonLocalBreaks) {
98032                     state.labeledNonLocalBreaks = new ts.Map();
98033                 }
98034                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
98035             }
98036             else {
98037                 if (!state.labeledNonLocalContinues) {
98038                     state.labeledNonLocalContinues = new ts.Map();
98039                 }
98040                 state.labeledNonLocalContinues.set(labelText, labelMarker);
98041             }
98042         }
98043         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
98044             if (!table) {
98045                 return;
98046             }
98047             table.forEach(function (labelMarker, labelText) {
98048                 var statements = [];
98049                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
98050                 // then emit labeled break\continue
98051                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
98052                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
98053                     var label = factory.createIdentifier(labelText);
98054                     statements.push(isBreak ? factory.createBreakStatement(label) : factory.createContinueStatement(label));
98055                 }
98056                 else {
98057                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
98058                     statements.push(factory.createReturnStatement(loopResultName));
98059                 }
98060                 caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements));
98061             });
98062         }
98063         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
98064             var name = decl.name;
98065             if (ts.isBindingPattern(name)) {
98066                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
98067                     var element = _a[_i];
98068                     if (!ts.isOmittedExpression(element)) {
98069                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
98070                     }
98071                 }
98072             }
98073             else {
98074                 loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
98075                 var checkFlags = resolver.getNodeCheckFlags(decl);
98076                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
98077                     var outParamName = factory.createUniqueName("out_" + ts.idText(name));
98078                     var flags = 0;
98079                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
98080                         flags |= 1 /* Body */;
98081                     }
98082                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
98083                         flags |= 2 /* Initializer */;
98084                     }
98085                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
98086                 }
98087             }
98088         }
98089         /**
98090          * Adds the members of an object literal to an array of expressions.
98091          *
98092          * @param expressions An array of expressions.
98093          * @param node An ObjectLiteralExpression node.
98094          * @param receiver The receiver for members of the ObjectLiteralExpression.
98095          * @param numInitialNonComputedProperties The number of initial properties without
98096          *                                        computed property names.
98097          */
98098         function addObjectLiteralMembers(expressions, node, receiver, start) {
98099             var properties = node.properties;
98100             var numProperties = properties.length;
98101             for (var i = start; i < numProperties; i++) {
98102                 var property = properties[i];
98103                 switch (property.kind) {
98104                     case 171 /* GetAccessor */:
98105                     case 172 /* SetAccessor */:
98106                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
98107                         if (property === accessors.firstAccessor) {
98108                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
98109                         }
98110                         break;
98111                     case 168 /* MethodDeclaration */:
98112                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
98113                         break;
98114                     case 294 /* PropertyAssignment */:
98115                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
98116                         break;
98117                     case 295 /* ShorthandPropertyAssignment */:
98118                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
98119                         break;
98120                     default:
98121                         ts.Debug.failBadSyntaxKind(node);
98122                         break;
98123                 }
98124             }
98125         }
98126         /**
98127          * Transforms a PropertyAssignment node into an expression.
98128          *
98129          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
98130          * @param property The PropertyAssignment node.
98131          * @param receiver The receiver for the assignment.
98132          */
98133         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
98134             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
98135             ts.setTextRange(expression, property);
98136             if (startsOnNewLine) {
98137                 ts.startOnNewLine(expression);
98138             }
98139             return expression;
98140         }
98141         /**
98142          * Transforms a ShorthandPropertyAssignment node into an expression.
98143          *
98144          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
98145          * @param property The ShorthandPropertyAssignment node.
98146          * @param receiver The receiver for the assignment.
98147          */
98148         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
98149             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), factory.cloneNode(property.name));
98150             ts.setTextRange(expression, property);
98151             if (startsOnNewLine) {
98152                 ts.startOnNewLine(expression);
98153             }
98154             return expression;
98155         }
98156         /**
98157          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
98158          *
98159          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
98160          * @param method The MethodDeclaration node.
98161          * @param receiver The receiver for the assignment.
98162          */
98163         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
98164             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
98165             ts.setTextRange(expression, method);
98166             if (startsOnNewLine) {
98167                 ts.startOnNewLine(expression);
98168             }
98169             return expression;
98170         }
98171         function visitCatchClause(node) {
98172             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
98173             var updated;
98174             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
98175             if (ts.isBindingPattern(node.variableDeclaration.name)) {
98176                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
98177                 var newVariableDeclaration = factory.createVariableDeclaration(temp);
98178                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
98179                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
98180                 var list = factory.createVariableDeclarationList(vars);
98181                 ts.setTextRange(list, node.variableDeclaration);
98182                 var destructure = factory.createVariableStatement(/*modifiers*/ undefined, list);
98183                 updated = factory.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
98184             }
98185             else {
98186                 updated = ts.visitEachChild(node, visitor, context);
98187             }
98188             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
98189             return updated;
98190         }
98191         function addStatementToStartOfBlock(block, statement) {
98192             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
98193             return factory.updateBlock(block, __spreadArray([statement], transformedStatements, true));
98194         }
98195         /**
98196          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
98197          * PropertyAssignment.
98198          *
98199          * @param node A MethodDeclaration node.
98200          */
98201         function visitMethodDeclaration(node) {
98202             // We should only get here for methods on an object literal with regular identifier names.
98203             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
98204             // Methods with computed property names are handled in visitObjectLiteralExpression.
98205             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
98206             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
98207             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
98208             return ts.setTextRange(factory.createPropertyAssignment(node.name, functionExpression), 
98209             /*location*/ node);
98210         }
98211         /**
98212          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
98213          *
98214          * @param node An AccessorDeclaration node.
98215          */
98216         function visitAccessorDeclaration(node) {
98217             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
98218             var savedConvertedLoopState = convertedLoopState;
98219             convertedLoopState = undefined;
98220             var ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
98221             var updated;
98222             var parameters = ts.visitParameterList(node.parameters, visitor, context);
98223             var body = transformFunctionBody(node);
98224             if (node.kind === 171 /* GetAccessor */) {
98225                 updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
98226             }
98227             else {
98228                 updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body);
98229             }
98230             exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
98231             convertedLoopState = savedConvertedLoopState;
98232             return updated;
98233         }
98234         /**
98235          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
98236          *
98237          * @param node A ShorthandPropertyAssignment node.
98238          */
98239         function visitShorthandPropertyAssignment(node) {
98240             return ts.setTextRange(factory.createPropertyAssignment(node.name, visitIdentifier(factory.cloneNode(node.name))), 
98241             /*location*/ node);
98242         }
98243         function visitComputedPropertyName(node) {
98244             return ts.visitEachChild(node, visitor, context);
98245         }
98246         /**
98247          * Visits a YieldExpression node.
98248          *
98249          * @param node A YieldExpression node.
98250          */
98251         function visitYieldExpression(node) {
98252             // `yield` expressions are transformed using the generators transformer.
98253             return ts.visitEachChild(node, visitor, context);
98254         }
98255         /**
98256          * Visits an ArrayLiteralExpression that contains a spread element.
98257          *
98258          * @param node An ArrayLiteralExpression node.
98259          */
98260         function visitArrayLiteralExpression(node) {
98261             if (ts.some(node.elements, ts.isSpreadElement)) {
98262                 // We are here because we contain a SpreadElementExpression.
98263                 return transformAndSpreadElements(node.elements, /*isArgumentList*/ false, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
98264             }
98265             return ts.visitEachChild(node, visitor, context);
98266         }
98267         /**
98268          * Visits a CallExpression that contains either a spread element or `super`.
98269          *
98270          * @param node a CallExpression.
98271          */
98272         function visitCallExpression(node) {
98273             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
98274                 return visitTypeScriptClassWrapper(node);
98275             }
98276             var expression = ts.skipOuterExpressions(node.expression);
98277             if (expression.kind === 106 /* SuperKeyword */ ||
98278                 ts.isSuperProperty(expression) ||
98279                 ts.some(node.arguments, ts.isSpreadElement)) {
98280                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
98281             }
98282             return factory.updateCallExpression(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
98283             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
98284         }
98285         function visitTypeScriptClassWrapper(node) {
98286             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
98287             // The wrapper has a form similar to:
98288             //
98289             //  (function() {
98290             //      class C { // 1
98291             //      }
98292             //      C.x = 1; // 2
98293             //      return C;
98294             //  }())
98295             //
98296             // When we transform the class, we end up with something like this:
98297             //
98298             //  (function () {
98299             //      var C = (function () { // 3
98300             //          function C() {
98301             //          }
98302             //          return C; // 4
98303             //      }());
98304             //      C.x = 1;
98305             //      return C;
98306             //  }())
98307             //
98308             // We want to simplify the two nested IIFEs to end up with something like this:
98309             //
98310             //  (function () {
98311             //      function C() {
98312             //      }
98313             //      C.x = 1;
98314             //      return C;
98315             //  }())
98316             // We skip any outer expressions in a number of places to get to the innermost
98317             // expression, but we will restore them later to preserve comments and source maps.
98318             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
98319             // The class statements are the statements generated by visiting the first statement with initializer of the
98320             // body (1), while all other statements are added to remainingStatements (2)
98321             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
98322             // visit the class body statements outside of any converted loop body.
98323             var savedConvertedLoopState = convertedLoopState;
98324             convertedLoopState = undefined;
98325             var bodyStatements = ts.visitNodes(body.statements, classWrapperStatementVisitor, ts.isStatement);
98326             convertedLoopState = savedConvertedLoopState;
98327             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
98328             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
98329             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
98330             // We know there is only one variable declaration here as we verified this in an
98331             // earlier call to isTypeScriptClassWrapper
98332             var variable = varStatement.declarationList.declarations[0];
98333             var initializer = ts.skipOuterExpressions(variable.initializer);
98334             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
98335             // we see as an assignment, for example:
98336             //
98337             //  (function () {
98338             //      var C_1;
98339             //      var C = C_1 = (function () {
98340             //          function C() {
98341             //          }
98342             //          C.x = function () { return C_1; }
98343             //          return C;
98344             //      }());
98345             //      C = C_1 = __decorate([dec], C);
98346             //      return C;
98347             //  }())
98348             //
98349             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
98350             if (!aliasAssignment && ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 27 /* CommaToken */) {
98351                 aliasAssignment = ts.tryCast(initializer.left, ts.isAssignmentExpression);
98352             }
98353             // The underlying call (3) is another IIFE that may contain a '_super' argument.
98354             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
98355             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
98356             var funcStatements = func.body.statements;
98357             var classBodyStart = 0;
98358             var classBodyEnd = -1;
98359             var statements = [];
98360             if (aliasAssignment) {
98361                 // If we have a class alias assignment, we need to move it to the down-level constructor
98362                 // function we generated for the class.
98363                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
98364                 if (extendsCall) {
98365                     statements.push(extendsCall);
98366                     classBodyStart++;
98367                 }
98368                 // The next statement is the function declaration.
98369                 statements.push(funcStatements[classBodyStart]);
98370                 classBodyStart++;
98371                 // Add the class alias following the declaration.
98372                 statements.push(factory.createExpressionStatement(factory.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
98373             }
98374             // Find the trailing 'return' statement (4)
98375             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
98376                 classBodyEnd--;
98377             }
98378             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
98379             // as we already have one that has been introduced by the 'ts' transformer.
98380             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
98381             if (classBodyEnd < -1) {
98382                 // If there were any hoisted declarations following the return statement, we should
98383                 // append them.
98384                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
98385             }
98386             // Add the remaining statements of the outer wrapper.
98387             ts.addRange(statements, remainingStatements);
98388             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
98389             // after the remaining statements from the 'ts' transformer.
98390             ts.addRange(statements, classStatements, /*start*/ 1);
98391             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
98392             // and comment locations.
98393             return factory.restoreOuterExpressions(node.expression, factory.restoreOuterExpressions(variable.initializer, factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory.updateCallExpression(call, factory.restoreOuterExpressions(call.expression, factory.updateFunctionExpression(func, 
98394             /*modifiers*/ undefined, 
98395             /*asteriskToken*/ undefined, 
98396             /*name*/ undefined, 
98397             /*typeParameters*/ undefined, func.parameters, 
98398             /*type*/ undefined, factory.updateBlock(func.body, statements))), 
98399             /*typeArguments*/ undefined, call.arguments))));
98400         }
98401         function visitImmediateSuperCallInBody(node) {
98402             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
98403         }
98404         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
98405             // We are here either because SuperKeyword was used somewhere in the expression, or
98406             // because we contain a SpreadElementExpression.
98407             if (node.transformFlags & 16384 /* ContainsRestOrSpread */ ||
98408                 node.expression.kind === 106 /* SuperKeyword */ ||
98409                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
98410                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
98411                 if (node.expression.kind === 106 /* SuperKeyword */) {
98412                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
98413                 }
98414                 var resultingCall = void 0;
98415                 if (node.transformFlags & 16384 /* ContainsRestOrSpread */) {
98416                     // [source]
98417                     //      f(...a, b)
98418                     //      x.m(...a, b)
98419                     //      super(...a, b)
98420                     //      super.m(...a, b) // in static
98421                     //      super.m(...a, b) // in instance
98422                     //
98423                     // [output]
98424                     //      f.apply(void 0, a.concat([b]))
98425                     //      (_a = x).m.apply(_a, a.concat([b]))
98426                     //      _super.apply(this, a.concat([b]))
98427                     //      _super.m.apply(this, a.concat([b]))
98428                     //      _super.prototype.m.apply(this, a.concat([b]))
98429                     resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 106 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false));
98430                 }
98431                 else {
98432                     // [source]
98433                     //      super(a)
98434                     //      super.m(a) // in static
98435                     //      super.m(a) // in instance
98436                     //
98437                     // [output]
98438                     //      _super.call(this, a)
98439                     //      _super.m.call(this, a)
98440                     //      _super.prototype.m.call(this, a)
98441                     resultingCall = ts.setTextRange(factory.createFunctionCallCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 106 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression)), node);
98442                 }
98443                 if (node.expression.kind === 106 /* SuperKeyword */) {
98444                     var initializer = factory.createLogicalOr(resultingCall, createActualThis());
98445                     resultingCall = assignToCapturedThis
98446                         ? factory.createAssignment(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer)
98447                         : initializer;
98448                 }
98449                 return ts.setOriginalNode(resultingCall, node);
98450             }
98451             return ts.visitEachChild(node, visitor, context);
98452         }
98453         /**
98454          * Visits a NewExpression that contains a spread element.
98455          *
98456          * @param node A NewExpression node.
98457          */
98458         function visitNewExpression(node) {
98459             if (ts.some(node.arguments, ts.isSpreadElement)) {
98460                 // We are here because we contain a SpreadElementExpression.
98461                 // [source]
98462                 //      new C(...a)
98463                 //
98464                 // [output]
98465                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
98466                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
98467                 return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArray([factory.createVoidZero()], node.arguments, true)), /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
98468                 /*typeArguments*/ undefined, []);
98469             }
98470             return ts.visitEachChild(node, visitor, context);
98471         }
98472         /**
98473          * Transforms an array of Expression nodes that contains a SpreadExpression.
98474          *
98475          * @param elements The array of Expression nodes.
98476          * @param isArgumentList A value indicating whether to ensure that the result is a fresh array.
98477          * This should be `false` when spreading into an `ArrayLiteral`, and `true` when spreading into an
98478          * argument list.
98479          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
98480          */
98481         function transformAndSpreadElements(elements, isArgumentList, multiLine, hasTrailingComma) {
98482             // When there is no leading SpreadElement:
98483             //
98484             // [source]
98485             //      [a, ...b, c]
98486             //
98487             // [output (downlevelIteration)]
98488             //      __spreadArray(__spreadArray([a], __read(b)), [c])
98489             //
98490             // [output]
98491             //      __spreadArray(__spreadArray([a], b), [c])
98492             //
98493             // When there *is* a leading SpreadElement:
98494             //
98495             // [source]
98496             //      [...a, b]
98497             //
98498             // [output (downlevelIteration)]
98499             //      __spreadArray(__spreadArray([], __read(a)), [b])
98500             //
98501             // [output]
98502             //      __spreadArray(__spreadArray([], a), [b])
98503             //
98504             // NOTE: We use `isPackedArrayLiteral` below rather than just `isArrayLiteral`
98505             // because ES2015 spread will replace _missing_ array elements with `undefined`,
98506             // so we cannot just use an array as is. For example:
98507             //
98508             // `[1, ...[2, , 3]]` becomes `[1, 2, undefined, 3]`
98509             //
98510             // However, for packed array literals (i.e., an array literal with no OmittedExpression
98511             // elements), we can use the array as-is.
98512             // Map spans of spread expressions into their expressions and spans of other
98513             // expressions into an array literal.
98514             var numElements = elements.length;
98515             var segments = ts.flatten(
98516             // As we visit each element, we return one of two functions to use as the "key":
98517             // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]`
98518             // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]`
98519             ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
98520                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
98521             }));
98522             if (segments.length === 1) {
98523                 var firstSegment = segments[0];
98524                 // If we don't need a unique copy, then we are spreading into an argument list for
98525                 // a CallExpression or NewExpression. When using `--downlevelIteration`, we need
98526                 // to coerce this into an array for use with `apply`, so we will use the code path
98527                 // that follows instead.
98528                 if (isArgumentList && !compilerOptions.downlevelIteration
98529                     || ts.isPackedArrayLiteral(firstSegment.expression) // see NOTE (above)
98530                     || ts.isCallToHelper(firstSegment.expression, "___spreadArray")) {
98531                     return firstSegment.expression;
98532                 }
98533             }
98534             var helpers = emitHelpers();
98535             var startsWithSpread = segments[0].kind !== 0 /* None */;
98536             var expression = startsWithSpread ? factory.createArrayLiteralExpression() :
98537                 segments[0].expression;
98538             for (var i = startsWithSpread ? 0 : 1; i < segments.length; i++) {
98539                 var segment = segments[i];
98540                 // If this is for an argument list, it doesn't matter if the array is packed or sparse
98541                 expression = helpers.createSpreadArrayHelper(expression, segment.expression, segment.kind === 1 /* UnpackedSpread */ && !isArgumentList);
98542             }
98543             return expression;
98544         }
98545         function partitionSpread(node) {
98546             return ts.isSpreadElement(node)
98547                 ? visitSpanOfSpreads
98548                 : visitSpanOfNonSpreads;
98549         }
98550         function visitSpanOfSpreads(chunk) {
98551             return ts.map(chunk, visitExpressionOfSpread);
98552         }
98553         function visitExpressionOfSpread(node) {
98554             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
98555             // We don't need to pack already packed array literals, or existing calls to the `__read` helper.
98556             var isCallToReadHelper = ts.isCallToHelper(expression, "___read");
98557             var kind = isCallToReadHelper || ts.isPackedArrayLiteral(expression) ? 2 /* PackedSpread */ : 1 /* UnpackedSpread */;
98558             // We don't need the `__read` helper for array literals. Array packing will be performed by `__spreadArray`.
98559             if (compilerOptions.downlevelIteration && kind === 1 /* UnpackedSpread */ && !ts.isArrayLiteralExpression(expression) && !isCallToReadHelper) {
98560                 expression = emitHelpers().createReadHelper(expression, /*count*/ undefined);
98561                 // the `__read` helper returns a packed array, so we don't need to ensure a packed array
98562                 kind = 2 /* PackedSpread */;
98563             }
98564             return createSpreadSegment(kind, expression);
98565         }
98566         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
98567             var expression = factory.createArrayLiteralExpression(ts.visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
98568             // We do not pack non-spread segments, this is so that `[1, , ...[2, , 3], , 4]` is properly downleveled to
98569             // `[1, , 2, undefined, 3, , 4]`. See the NOTE in `transformAndSpreadElements`
98570             return createSpreadSegment(0 /* None */, expression);
98571         }
98572         function visitSpreadElement(node) {
98573             return ts.visitNode(node.expression, visitor, ts.isExpression);
98574         }
98575         /**
98576          * Visits a template literal.
98577          *
98578          * @param node A template literal.
98579          */
98580         function visitTemplateLiteral(node) {
98581             return ts.setTextRange(factory.createStringLiteral(node.text), node);
98582         }
98583         /**
98584          * Visits a string literal with an extended unicode escape.
98585          *
98586          * @param node A string literal.
98587          */
98588         function visitStringLiteral(node) {
98589             if (node.hasExtendedUnicodeEscape) {
98590                 return ts.setTextRange(factory.createStringLiteral(node.text), node);
98591             }
98592             return node;
98593         }
98594         /**
98595          * Visits a binary or octal (ES6) numeric literal.
98596          *
98597          * @param node A string literal.
98598          */
98599         function visitNumericLiteral(node) {
98600             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
98601                 return ts.setTextRange(factory.createNumericLiteral(node.text), node);
98602             }
98603             return node;
98604         }
98605         /**
98606          * Visits a TaggedTemplateExpression node.
98607          *
98608          * @param node A TaggedTemplateExpression node.
98609          */
98610         function visitTaggedTemplateExpression(node) {
98611             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
98612         }
98613         /**
98614          * Visits a TemplateExpression node.
98615          *
98616          * @param node A TemplateExpression node.
98617          */
98618         function visitTemplateExpression(node) {
98619             var expression = factory.createStringLiteral(node.head.text);
98620             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
98621                 var span = _a[_i];
98622                 var args = [ts.visitNode(span.expression, visitor, ts.isExpression)];
98623                 if (span.literal.text.length > 0) {
98624                     args.push(factory.createStringLiteral(span.literal.text));
98625                 }
98626                 expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), 
98627                 /*typeArguments*/ undefined, args);
98628             }
98629             return ts.setTextRange(expression, node);
98630         }
98631         /**
98632          * Visits the `super` keyword
98633          */
98634         function visitSuperKeyword(isExpressionOfCall) {
98635             return hierarchyFacts & 8 /* NonStaticClassElement */
98636                 && !isExpressionOfCall
98637                 ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype")
98638                 : factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
98639         }
98640         function visitMetaProperty(node) {
98641             if (node.keywordToken === 103 /* NewKeyword */ && node.name.escapedText === "target") {
98642                 hierarchyFacts |= 32768 /* NewTarget */;
98643                 return factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
98644             }
98645             return node;
98646         }
98647         /**
98648          * Called by the printer just before a node is printed.
98649          *
98650          * @param hint A hint as to the intended usage of the node.
98651          * @param node The node to be printed.
98652          * @param emitCallback The callback used to emit the node.
98653          */
98654         function onEmitNode(hint, node, emitCallback) {
98655             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
98656                 // If we are tracking a captured `this`, keep track of the enclosing function.
98657                 var ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
98658                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
98659                     : 65 /* FunctionIncludes */);
98660                 previousOnEmitNode(hint, node, emitCallback);
98661                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
98662                 return;
98663             }
98664             previousOnEmitNode(hint, node, emitCallback);
98665         }
98666         /**
98667          * Enables a more costly code path for substitutions when we determine a source file
98668          * contains block-scoped bindings (e.g. `let` or `const`).
98669          */
98670         function enableSubstitutionsForBlockScopedBindings() {
98671             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
98672                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
98673                 context.enableSubstitution(79 /* Identifier */);
98674             }
98675         }
98676         /**
98677          * Enables a more costly code path for substitutions when we determine a source file
98678          * contains a captured `this`.
98679          */
98680         function enableSubstitutionsForCapturedThis() {
98681             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
98682                 enabledSubstitutions |= 1 /* CapturedThis */;
98683                 context.enableSubstitution(108 /* ThisKeyword */);
98684                 context.enableEmitNotification(170 /* Constructor */);
98685                 context.enableEmitNotification(168 /* MethodDeclaration */);
98686                 context.enableEmitNotification(171 /* GetAccessor */);
98687                 context.enableEmitNotification(172 /* SetAccessor */);
98688                 context.enableEmitNotification(213 /* ArrowFunction */);
98689                 context.enableEmitNotification(212 /* FunctionExpression */);
98690                 context.enableEmitNotification(255 /* FunctionDeclaration */);
98691             }
98692         }
98693         /**
98694          * Hooks node substitutions.
98695          *
98696          * @param hint The context for the emitter.
98697          * @param node The node to substitute.
98698          */
98699         function onSubstituteNode(hint, node) {
98700             node = previousOnSubstituteNode(hint, node);
98701             if (hint === 1 /* Expression */) {
98702                 return substituteExpression(node);
98703             }
98704             if (ts.isIdentifier(node)) {
98705                 return substituteIdentifier(node);
98706             }
98707             return node;
98708         }
98709         /**
98710          * Hooks substitutions for non-expression identifiers.
98711          */
98712         function substituteIdentifier(node) {
98713             // Only substitute the identifier if we have enabled substitutions for block-scoped
98714             // bindings.
98715             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
98716                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
98717                 if (original && isNameOfDeclarationWithCollidingName(original)) {
98718                     return ts.setTextRange(factory.getGeneratedNameForNode(original), node);
98719                 }
98720             }
98721             return node;
98722         }
98723         /**
98724          * Determines whether a name is the name of a declaration with a colliding name.
98725          * NOTE: This function expects to be called with an original source tree node.
98726          *
98727          * @param node An original source tree node.
98728          */
98729         function isNameOfDeclarationWithCollidingName(node) {
98730             switch (node.parent.kind) {
98731                 case 202 /* BindingElement */:
98732                 case 256 /* ClassDeclaration */:
98733                 case 259 /* EnumDeclaration */:
98734                 case 253 /* VariableDeclaration */:
98735                     return node.parent.name === node
98736                         && resolver.isDeclarationWithCollidingName(node.parent);
98737             }
98738             return false;
98739         }
98740         /**
98741          * Substitutes an expression.
98742          *
98743          * @param node An Expression node.
98744          */
98745         function substituteExpression(node) {
98746             switch (node.kind) {
98747                 case 79 /* Identifier */:
98748                     return substituteExpressionIdentifier(node);
98749                 case 108 /* ThisKeyword */:
98750                     return substituteThisKeyword(node);
98751             }
98752             return node;
98753         }
98754         /**
98755          * Substitutes an expression identifier.
98756          *
98757          * @param node An Identifier node.
98758          */
98759         function substituteExpressionIdentifier(node) {
98760             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
98761                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
98762                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
98763                     return ts.setTextRange(factory.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
98764                 }
98765             }
98766             return node;
98767         }
98768         function isPartOfClassBody(declaration, node) {
98769             var currentNode = ts.getParseTreeNode(node);
98770             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
98771                 // if the node has no correlation to a parse tree node, its definitely not
98772                 // part of the body.
98773                 // if the node is outside of the document range of the declaration, its
98774                 // definitely not part of the body.
98775                 return false;
98776             }
98777             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
98778             while (currentNode) {
98779                 if (currentNode === blockScope || currentNode === declaration) {
98780                     // if we are in the enclosing block scope of the declaration, we are definitely
98781                     // not inside the class body.
98782                     return false;
98783                 }
98784                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
98785                     return true;
98786                 }
98787                 currentNode = currentNode.parent;
98788             }
98789             return false;
98790         }
98791         /**
98792          * Substitutes `this` when contained within an arrow function.
98793          *
98794          * @param node The ThisKeyword node.
98795          */
98796         function substituteThisKeyword(node) {
98797             if (enabledSubstitutions & 1 /* CapturedThis */
98798                 && hierarchyFacts & 16 /* CapturesThis */) {
98799                 return ts.setTextRange(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
98800             }
98801             return node;
98802         }
98803         function getClassMemberPrefix(node, member) {
98804             return ts.isStatic(member)
98805                 ? factory.getInternalName(node)
98806                 : factory.createPropertyAccessExpression(factory.getInternalName(node), "prototype");
98807         }
98808         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
98809             if (!constructor || !hasExtendsClause) {
98810                 return false;
98811             }
98812             if (ts.some(constructor.parameters)) {
98813                 return false;
98814             }
98815             var statement = ts.firstOrUndefined(constructor.body.statements);
98816             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 237 /* ExpressionStatement */) {
98817                 return false;
98818             }
98819             var statementExpression = statement.expression;
98820             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 207 /* CallExpression */) {
98821                 return false;
98822             }
98823             var callTarget = statementExpression.expression;
98824             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 106 /* SuperKeyword */) {
98825                 return false;
98826             }
98827             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
98828             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 224 /* SpreadElement */) {
98829                 return false;
98830             }
98831             var expression = callArgument.expression;
98832             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
98833         }
98834     }
98835     ts.transformES2015 = transformES2015;
98836 })(ts || (ts = {}));
98837 /*@internal*/
98838 var ts;
98839 (function (ts) {
98840     /**
98841      * Transforms ES5 syntax into ES3 syntax.
98842      *
98843      * @param context Context and state information for the transformation.
98844      */
98845     function transformES5(context) {
98846         var factory = context.factory;
98847         var compilerOptions = context.getCompilerOptions();
98848         // enable emit notification only if using --jsx preserve or react-native
98849         var previousOnEmitNode;
98850         var noSubstitution;
98851         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
98852             previousOnEmitNode = context.onEmitNode;
98853             context.onEmitNode = onEmitNode;
98854             context.enableEmitNotification(279 /* JsxOpeningElement */);
98855             context.enableEmitNotification(280 /* JsxClosingElement */);
98856             context.enableEmitNotification(278 /* JsxSelfClosingElement */);
98857             noSubstitution = [];
98858         }
98859         var previousOnSubstituteNode = context.onSubstituteNode;
98860         context.onSubstituteNode = onSubstituteNode;
98861         context.enableSubstitution(205 /* PropertyAccessExpression */);
98862         context.enableSubstitution(294 /* PropertyAssignment */);
98863         return ts.chainBundle(context, transformSourceFile);
98864         /**
98865          * Transforms an ES5 source file to ES3.
98866          *
98867          * @param node A SourceFile
98868          */
98869         function transformSourceFile(node) {
98870             return node;
98871         }
98872         /**
98873          * Called by the printer just before a node is printed.
98874          *
98875          * @param hint A hint as to the intended usage of the node.
98876          * @param node The node to emit.
98877          * @param emitCallback A callback used to emit the node.
98878          */
98879         function onEmitNode(hint, node, emitCallback) {
98880             switch (node.kind) {
98881                 case 279 /* JsxOpeningElement */:
98882                 case 280 /* JsxClosingElement */:
98883                 case 278 /* JsxSelfClosingElement */:
98884                     var tagName = node.tagName;
98885                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
98886                     break;
98887             }
98888             previousOnEmitNode(hint, node, emitCallback);
98889         }
98890         /**
98891          * Hooks node substitutions.
98892          *
98893          * @param hint A hint as to the intended usage of the node.
98894          * @param node The node to substitute.
98895          */
98896         function onSubstituteNode(hint, node) {
98897             if (node.id && noSubstitution && noSubstitution[node.id]) {
98898                 return previousOnSubstituteNode(hint, node);
98899             }
98900             node = previousOnSubstituteNode(hint, node);
98901             if (ts.isPropertyAccessExpression(node)) {
98902                 return substitutePropertyAccessExpression(node);
98903             }
98904             else if (ts.isPropertyAssignment(node)) {
98905                 return substitutePropertyAssignment(node);
98906             }
98907             return node;
98908         }
98909         /**
98910          * Substitutes a PropertyAccessExpression whose name is a reserved word.
98911          *
98912          * @param node A PropertyAccessExpression
98913          */
98914         function substitutePropertyAccessExpression(node) {
98915             if (ts.isPrivateIdentifier(node.name)) {
98916                 return node;
98917             }
98918             var literalName = trySubstituteReservedName(node.name);
98919             if (literalName) {
98920                 return ts.setTextRange(factory.createElementAccessExpression(node.expression, literalName), node);
98921             }
98922             return node;
98923         }
98924         /**
98925          * Substitutes a PropertyAssignment whose name is a reserved word.
98926          *
98927          * @param node A PropertyAssignment
98928          */
98929         function substitutePropertyAssignment(node) {
98930             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
98931             if (literalName) {
98932                 return factory.updatePropertyAssignment(node, literalName, node.initializer);
98933             }
98934             return node;
98935         }
98936         /**
98937          * If an identifier name is a reserved word, returns a string literal for the name.
98938          *
98939          * @param name An Identifier
98940          */
98941         function trySubstituteReservedName(name) {
98942             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
98943             if (token !== undefined && token >= 81 /* FirstReservedWord */ && token <= 116 /* LastReservedWord */) {
98944                 return ts.setTextRange(factory.createStringLiteralFromNode(name), name);
98945             }
98946             return undefined;
98947         }
98948     }
98949     ts.transformES5 = transformES5;
98950 })(ts || (ts = {}));
98951 // Transforms generator functions into a compatible ES5 representation with similar runtime
98952 // semantics. This is accomplished by first transforming the body of each generator
98953 // function into an intermediate representation that is the compiled into a JavaScript
98954 // switch statement.
98955 //
98956 // Many functions in this transformer will contain comments indicating the expected
98957 // intermediate representation. For illustrative purposes, the following intermediate
98958 // language is used to define this intermediate representation:
98959 //
98960 //  .nop                            - Performs no operation.
98961 //  .local NAME, ...                - Define local variable declarations.
98962 //  .mark LABEL                     - Mark the location of a label.
98963 //  .br LABEL                       - Jump to a label. If jumping out of a protected
98964 //                                    region, all .finally blocks are executed.
98965 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
98966 //                                    If jumping out of a protected region, all .finally
98967 //                                    blocks are executed.
98968 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
98969 //                                    If jumping out of a protected region, all .finally
98970 //                                    blocks are executed.
98971 //  .yield (x)                      - Yield the value of the optional expression `x`.
98972 //                                    Resume at the next label.
98973 //  .yieldstar (x)                  - Delegate yield to the value of the optional
98974 //                                    expression `x`. Resume at the next label.
98975 //                                    NOTE: `x` must be an Iterator, not an Iterable.
98976 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
98977 //                                    "break" abrupt completions jump to the CONTINUE or
98978 //                                    BREAK labels, respectively.
98979 //  .endloop                        - Marks the end of a loop.
98980 //  .with (x)                       - Marks the beginning of a WithStatement block, using
98981 //                                    the supplied expression.
98982 //  .endwith                        - Marks the end of a WithStatement.
98983 //  .switch                         - Marks the beginning of a SwitchStatement.
98984 //  .endswitch                      - Marks the end of a SwitchStatement.
98985 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
98986 //                                    supplied name.
98987 //  .endlabeled                     - Marks the end of a LabeledStatement.
98988 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
98989 //                                    labels for each block.
98990 //  .catch (x)                      - Marks the beginning of a catch block.
98991 //  .finally                        - Marks the beginning of a finally block.
98992 //  .endfinally                     - Marks the end of a finally block.
98993 //  .endtry                         - Marks the end of a protected region.
98994 //  .throw (x)                      - Throws the value of the expression `x`.
98995 //  .return (x)                     - Returns the value of the expression `x`.
98996 //
98997 // In addition, the illustrative intermediate representation introduces some special
98998 // variables:
98999 //
99000 //  %sent%                          - Either returns the next value sent to the generator,
99001 //                                    returns the result of a delegated yield, or throws
99002 //                                    the exception sent to the generator.
99003 //  %error%                         - Returns the value of the current exception in a
99004 //                                    catch block.
99005 //
99006 // This intermediate representation is then compiled into JavaScript syntax. The resulting
99007 // compilation output looks something like the following:
99008 //
99009 //  function f() {
99010 //      var /*locals*/;
99011 //      /*functions*/
99012 //      return __generator(function (state) {
99013 //          switch (state.label) {
99014 //              /*cases per label*/
99015 //          }
99016 //      });
99017 //  }
99018 //
99019 // Each of the above instructions corresponds to JavaScript emit similar to the following:
99020 //
99021 //  .local NAME                   | var NAME;
99022 // -------------------------------|----------------------------------------------
99023 //  .mark LABEL                   | case LABEL:
99024 // -------------------------------|----------------------------------------------
99025 //  .br LABEL                     |     return [3 /*break*/, LABEL];
99026 // -------------------------------|----------------------------------------------
99027 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
99028 // -------------------------------|----------------------------------------------
99029 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
99030 // -------------------------------|----------------------------------------------
99031 //  .yield (x)                    |     return [4 /*yield*/, x];
99032 //  .mark RESUME                  | case RESUME:
99033 //      a = %sent%;               |     a = state.sent();
99034 // -------------------------------|----------------------------------------------
99035 //  .yieldstar (x)                |     return [5 /*yield**/, x];
99036 //  .mark RESUME                  | case RESUME:
99037 //      a = %sent%;               |     a = state.sent();
99038 // -------------------------------|----------------------------------------------
99039 //  .with (_a)                    |     with (_a) {
99040 //      a();                      |         a();
99041 //                                |     }
99042 //                                |     state.label = LABEL;
99043 //  .mark LABEL                   | case LABEL:
99044 //                                |     with (_a) {
99045 //      b();                      |         b();
99046 //                                |     }
99047 //  .endwith                      |
99048 // -------------------------------|----------------------------------------------
99049 //                                | case 0:
99050 //                                |     state.trys = [];
99051 //                                | ...
99052 //  .try TRY, CATCH, FINALLY, END |
99053 //  .mark TRY                     | case TRY:
99054 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
99055 //  .nop                          |
99056 //      a();                      |     a();
99057 //  .br END                       |     return [3 /*break*/, END];
99058 //  .catch (e)                    |
99059 //  .mark CATCH                   | case CATCH:
99060 //                                |     e = state.sent();
99061 //      b();                      |     b();
99062 //  .br END                       |     return [3 /*break*/, END];
99063 //  .finally                      |
99064 //  .mark FINALLY                 | case FINALLY:
99065 //      c();                      |     c();
99066 //  .endfinally                   |     return [7 /*endfinally*/];
99067 //  .endtry                       |
99068 //  .mark END                     | case END:
99069 /*@internal*/
99070 var ts;
99071 (function (ts) {
99072     var OpCode;
99073     (function (OpCode) {
99074         OpCode[OpCode["Nop"] = 0] = "Nop";
99075         OpCode[OpCode["Statement"] = 1] = "Statement";
99076         OpCode[OpCode["Assign"] = 2] = "Assign";
99077         OpCode[OpCode["Break"] = 3] = "Break";
99078         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
99079         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
99080         OpCode[OpCode["Yield"] = 6] = "Yield";
99081         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
99082         OpCode[OpCode["Return"] = 8] = "Return";
99083         OpCode[OpCode["Throw"] = 9] = "Throw";
99084         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
99085     })(OpCode || (OpCode = {}));
99086     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
99087     var BlockAction;
99088     (function (BlockAction) {
99089         BlockAction[BlockAction["Open"] = 0] = "Open";
99090         BlockAction[BlockAction["Close"] = 1] = "Close";
99091     })(BlockAction || (BlockAction = {}));
99092     // the kind for a generated code block in a FunctionBuilder
99093     var CodeBlockKind;
99094     (function (CodeBlockKind) {
99095         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
99096         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
99097         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
99098         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
99099         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
99100     })(CodeBlockKind || (CodeBlockKind = {}));
99101     // the state for a generated code exception block
99102     var ExceptionBlockState;
99103     (function (ExceptionBlockState) {
99104         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
99105         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
99106         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
99107         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
99108     })(ExceptionBlockState || (ExceptionBlockState = {}));
99109     // NOTE: changes to this enum should be reflected in the __generator helper.
99110     var Instruction;
99111     (function (Instruction) {
99112         Instruction[Instruction["Next"] = 0] = "Next";
99113         Instruction[Instruction["Throw"] = 1] = "Throw";
99114         Instruction[Instruction["Return"] = 2] = "Return";
99115         Instruction[Instruction["Break"] = 3] = "Break";
99116         Instruction[Instruction["Yield"] = 4] = "Yield";
99117         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
99118         Instruction[Instruction["Catch"] = 6] = "Catch";
99119         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
99120     })(Instruction || (Instruction = {}));
99121     function getInstructionName(instruction) {
99122         switch (instruction) {
99123             case 2 /* Return */: return "return";
99124             case 3 /* Break */: return "break";
99125             case 4 /* Yield */: return "yield";
99126             case 5 /* YieldStar */: return "yield*";
99127             case 7 /* Endfinally */: return "endfinally";
99128             default: return undefined; // TODO: GH#18217
99129         }
99130     }
99131     function transformGenerators(context) {
99132         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
99133         var compilerOptions = context.getCompilerOptions();
99134         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
99135         var resolver = context.getEmitResolver();
99136         var previousOnSubstituteNode = context.onSubstituteNode;
99137         context.onSubstituteNode = onSubstituteNode;
99138         var renamedCatchVariables;
99139         var renamedCatchVariableDeclarations;
99140         var inGeneratorFunctionBody;
99141         var inStatementContainingYield;
99142         // The following three arrays store information about generated code blocks.
99143         // All three arrays are correlated by their index. This approach is used over allocating
99144         // objects to store the same information to avoid GC overhead.
99145         //
99146         var blocks; // Information about the code block
99147         var blockOffsets; // The operation offset at which a code block begins or ends
99148         var blockActions; // Whether the code block is opened or closed
99149         var blockStack; // A stack of currently open code blocks
99150         // Labels are used to mark locations in the code that can be the target of a Break (jump)
99151         // operation. These are translated into case clauses in a switch statement.
99152         // The following two arrays are correlated by their index. This approach is used over
99153         // allocating objects to store the same information to avoid GC overhead.
99154         //
99155         var labelOffsets; // The operation offset at which the label is defined.
99156         var labelExpressions; // The NumericLiteral nodes bound to each label.
99157         var nextLabelId = 1; // The next label id to use.
99158         // Operations store information about generated code for the function body. This
99159         // Includes things like statements, assignments, breaks (jumps), and yields.
99160         // The following three arrays are correlated by their index. This approach is used over
99161         // allocating objects to store the same information to avoid GC overhead.
99162         //
99163         var operations; // The operation to perform.
99164         var operationArguments; // The arguments to the operation.
99165         var operationLocations; // The source map location for the operation.
99166         var state; // The name of the state object used by the generator at runtime.
99167         // The following variables store information used by the `build` function:
99168         //
99169         var blockIndex = 0; // The index of the current block.
99170         var labelNumber = 0; // The current label number.
99171         var labelNumbers;
99172         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
99173         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
99174         var clauses; // The case clauses generated for labels.
99175         var statements; // The statements for the current label.
99176         var exceptionBlockStack; // A stack of containing exception blocks.
99177         var currentExceptionBlock; // The current exception block.
99178         var withBlockStack; // A stack containing `with` blocks.
99179         return ts.chainBundle(context, transformSourceFile);
99180         function transformSourceFile(node) {
99181             if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) {
99182                 return node;
99183             }
99184             var visited = ts.visitEachChild(node, visitor, context);
99185             ts.addEmitHelpers(visited, context.readEmitHelpers());
99186             return visited;
99187         }
99188         /**
99189          * Visits a node.
99190          *
99191          * @param node The node to visit.
99192          */
99193         function visitor(node) {
99194             var transformFlags = node.transformFlags;
99195             if (inStatementContainingYield) {
99196                 return visitJavaScriptInStatementContainingYield(node);
99197             }
99198             else if (inGeneratorFunctionBody) {
99199                 return visitJavaScriptInGeneratorFunctionBody(node);
99200             }
99201             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
99202                 return visitGenerator(node);
99203             }
99204             else if (transformFlags & 1024 /* ContainsGenerator */) {
99205                 return ts.visitEachChild(node, visitor, context);
99206             }
99207             else {
99208                 return node;
99209             }
99210         }
99211         /**
99212          * Visits a node that is contained within a statement that contains yield.
99213          *
99214          * @param node The node to visit.
99215          */
99216         function visitJavaScriptInStatementContainingYield(node) {
99217             switch (node.kind) {
99218                 case 239 /* DoStatement */:
99219                     return visitDoStatement(node);
99220                 case 240 /* WhileStatement */:
99221                     return visitWhileStatement(node);
99222                 case 248 /* SwitchStatement */:
99223                     return visitSwitchStatement(node);
99224                 case 249 /* LabeledStatement */:
99225                     return visitLabeledStatement(node);
99226                 default:
99227                     return visitJavaScriptInGeneratorFunctionBody(node);
99228             }
99229         }
99230         /**
99231          * Visits a node that is contained within a generator function.
99232          *
99233          * @param node The node to visit.
99234          */
99235         function visitJavaScriptInGeneratorFunctionBody(node) {
99236             switch (node.kind) {
99237                 case 255 /* FunctionDeclaration */:
99238                     return visitFunctionDeclaration(node);
99239                 case 212 /* FunctionExpression */:
99240                     return visitFunctionExpression(node);
99241                 case 171 /* GetAccessor */:
99242                 case 172 /* SetAccessor */:
99243                     return visitAccessorDeclaration(node);
99244                 case 236 /* VariableStatement */:
99245                     return visitVariableStatement(node);
99246                 case 241 /* ForStatement */:
99247                     return visitForStatement(node);
99248                 case 242 /* ForInStatement */:
99249                     return visitForInStatement(node);
99250                 case 245 /* BreakStatement */:
99251                     return visitBreakStatement(node);
99252                 case 244 /* ContinueStatement */:
99253                     return visitContinueStatement(node);
99254                 case 246 /* ReturnStatement */:
99255                     return visitReturnStatement(node);
99256                 default:
99257                     if (node.transformFlags & 524288 /* ContainsYield */) {
99258                         return visitJavaScriptContainingYield(node);
99259                     }
99260                     else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) {
99261                         return ts.visitEachChild(node, visitor, context);
99262                     }
99263                     else {
99264                         return node;
99265                     }
99266             }
99267         }
99268         /**
99269          * Visits a node that contains a YieldExpression.
99270          *
99271          * @param node The node to visit.
99272          */
99273         function visitJavaScriptContainingYield(node) {
99274             switch (node.kind) {
99275                 case 220 /* BinaryExpression */:
99276                     return visitBinaryExpression(node);
99277                 case 349 /* CommaListExpression */:
99278                     return visitCommaListExpression(node);
99279                 case 221 /* ConditionalExpression */:
99280                     return visitConditionalExpression(node);
99281                 case 223 /* YieldExpression */:
99282                     return visitYieldExpression(node);
99283                 case 203 /* ArrayLiteralExpression */:
99284                     return visitArrayLiteralExpression(node);
99285                 case 204 /* ObjectLiteralExpression */:
99286                     return visitObjectLiteralExpression(node);
99287                 case 206 /* ElementAccessExpression */:
99288                     return visitElementAccessExpression(node);
99289                 case 207 /* CallExpression */:
99290                     return visitCallExpression(node);
99291                 case 208 /* NewExpression */:
99292                     return visitNewExpression(node);
99293                 default:
99294                     return ts.visitEachChild(node, visitor, context);
99295             }
99296         }
99297         /**
99298          * Visits a generator function.
99299          *
99300          * @param node The node to visit.
99301          */
99302         function visitGenerator(node) {
99303             switch (node.kind) {
99304                 case 255 /* FunctionDeclaration */:
99305                     return visitFunctionDeclaration(node);
99306                 case 212 /* FunctionExpression */:
99307                     return visitFunctionExpression(node);
99308                 default:
99309                     return ts.Debug.failBadSyntaxKind(node);
99310             }
99311         }
99312         /**
99313          * Visits a function declaration.
99314          *
99315          * This will be called when one of the following conditions are met:
99316          * - The function declaration is a generator function.
99317          * - The function declaration is contained within the body of a generator function.
99318          *
99319          * @param node The node to visit.
99320          */
99321         function visitFunctionDeclaration(node) {
99322             // Currently, we only support generators that were originally async functions.
99323             if (node.asteriskToken) {
99324                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
99325                 /*decorators*/ undefined, node.modifiers, 
99326                 /*asteriskToken*/ undefined, node.name, 
99327                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
99328                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
99329                 /*location*/ node), node);
99330             }
99331             else {
99332                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
99333                 var savedInStatementContainingYield = inStatementContainingYield;
99334                 inGeneratorFunctionBody = false;
99335                 inStatementContainingYield = false;
99336                 node = ts.visitEachChild(node, visitor, context);
99337                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
99338                 inStatementContainingYield = savedInStatementContainingYield;
99339             }
99340             if (inGeneratorFunctionBody) {
99341                 // Function declarations in a generator function body are hoisted
99342                 // to the top of the lexical scope and elided from the current statement.
99343                 hoistFunctionDeclaration(node);
99344                 return undefined;
99345             }
99346             else {
99347                 return node;
99348             }
99349         }
99350         /**
99351          * Visits a function expression.
99352          *
99353          * This will be called when one of the following conditions are met:
99354          * - The function expression is a generator function.
99355          * - The function expression is contained within the body of a generator function.
99356          *
99357          * @param node The node to visit.
99358          */
99359         function visitFunctionExpression(node) {
99360             // Currently, we only support generators that were originally async functions.
99361             if (node.asteriskToken) {
99362                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
99363                 /*modifiers*/ undefined, 
99364                 /*asteriskToken*/ undefined, node.name, 
99365                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
99366                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
99367                 /*location*/ node), node);
99368             }
99369             else {
99370                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
99371                 var savedInStatementContainingYield = inStatementContainingYield;
99372                 inGeneratorFunctionBody = false;
99373                 inStatementContainingYield = false;
99374                 node = ts.visitEachChild(node, visitor, context);
99375                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
99376                 inStatementContainingYield = savedInStatementContainingYield;
99377             }
99378             return node;
99379         }
99380         /**
99381          * Visits a get or set accessor declaration.
99382          *
99383          * This will be called when one of the following conditions are met:
99384          * - The accessor is contained within the body of a generator function.
99385          *
99386          * @param node The node to visit.
99387          */
99388         function visitAccessorDeclaration(node) {
99389             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
99390             var savedInStatementContainingYield = inStatementContainingYield;
99391             inGeneratorFunctionBody = false;
99392             inStatementContainingYield = false;
99393             node = ts.visitEachChild(node, visitor, context);
99394             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
99395             inStatementContainingYield = savedInStatementContainingYield;
99396             return node;
99397         }
99398         /**
99399          * Transforms the body of a generator function declaration.
99400          *
99401          * @param node The function body to transform.
99402          */
99403         function transformGeneratorFunctionBody(body) {
99404             // Save existing generator state
99405             var statements = [];
99406             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
99407             var savedInStatementContainingYield = inStatementContainingYield;
99408             var savedBlocks = blocks;
99409             var savedBlockOffsets = blockOffsets;
99410             var savedBlockActions = blockActions;
99411             var savedBlockStack = blockStack;
99412             var savedLabelOffsets = labelOffsets;
99413             var savedLabelExpressions = labelExpressions;
99414             var savedNextLabelId = nextLabelId;
99415             var savedOperations = operations;
99416             var savedOperationArguments = operationArguments;
99417             var savedOperationLocations = operationLocations;
99418             var savedState = state;
99419             // Initialize generator state
99420             inGeneratorFunctionBody = true;
99421             inStatementContainingYield = false;
99422             blocks = undefined;
99423             blockOffsets = undefined;
99424             blockActions = undefined;
99425             blockStack = undefined;
99426             labelOffsets = undefined;
99427             labelExpressions = undefined;
99428             nextLabelId = 1;
99429             operations = undefined;
99430             operationArguments = undefined;
99431             operationLocations = undefined;
99432             state = factory.createTempVariable(/*recordTempVariable*/ undefined);
99433             // Build the generator
99434             resumeLexicalEnvironment();
99435             var statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
99436             transformAndEmitStatements(body.statements, statementOffset);
99437             var buildResult = build();
99438             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
99439             statements.push(factory.createReturnStatement(buildResult));
99440             // Restore previous generator state
99441             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
99442             inStatementContainingYield = savedInStatementContainingYield;
99443             blocks = savedBlocks;
99444             blockOffsets = savedBlockOffsets;
99445             blockActions = savedBlockActions;
99446             blockStack = savedBlockStack;
99447             labelOffsets = savedLabelOffsets;
99448             labelExpressions = savedLabelExpressions;
99449             nextLabelId = savedNextLabelId;
99450             operations = savedOperations;
99451             operationArguments = savedOperationArguments;
99452             operationLocations = savedOperationLocations;
99453             state = savedState;
99454             return ts.setTextRange(factory.createBlock(statements, body.multiLine), body);
99455         }
99456         /**
99457          * Visits a variable statement.
99458          *
99459          * This will be called when one of the following conditions are met:
99460          * - The variable statement is contained within the body of a generator function.
99461          *
99462          * @param node The node to visit.
99463          */
99464         function visitVariableStatement(node) {
99465             if (node.transformFlags & 524288 /* ContainsYield */) {
99466                 transformAndEmitVariableDeclarationList(node.declarationList);
99467                 return undefined;
99468             }
99469             else {
99470                 // Do not hoist custom prologues.
99471                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
99472                     return node;
99473                 }
99474                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
99475                     var variable = _a[_i];
99476                     hoistVariableDeclaration(variable.name);
99477                 }
99478                 var variables = ts.getInitializedVariables(node.declarationList);
99479                 if (variables.length === 0) {
99480                     return undefined;
99481                 }
99482                 return ts.setSourceMapRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
99483             }
99484         }
99485         /**
99486          * Visits a binary expression.
99487          *
99488          * This will be called when one of the following conditions are met:
99489          * - The node contains a YieldExpression.
99490          *
99491          * @param node The node to visit.
99492          */
99493         function visitBinaryExpression(node) {
99494             var assoc = ts.getExpressionAssociativity(node);
99495             switch (assoc) {
99496                 case 0 /* Left */:
99497                     return visitLeftAssociativeBinaryExpression(node);
99498                 case 1 /* Right */:
99499                     return visitRightAssociativeBinaryExpression(node);
99500                 default:
99501                     return ts.Debug.assertNever(assoc);
99502             }
99503         }
99504         /**
99505          * Visits a right-associative binary expression containing `yield`.
99506          *
99507          * @param node The node to visit.
99508          */
99509         function visitRightAssociativeBinaryExpression(node) {
99510             var left = node.left, right = node.right;
99511             if (containsYield(right)) {
99512                 var target = void 0;
99513                 switch (left.kind) {
99514                     case 205 /* PropertyAccessExpression */:
99515                         // [source]
99516                         //      a.b = yield;
99517                         //
99518                         // [intermediate]
99519                         //  .local _a
99520                         //      _a = a;
99521                         //  .yield resumeLabel
99522                         //  .mark resumeLabel
99523                         //      _a.b = %sent%;
99524                         target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
99525                         break;
99526                     case 206 /* ElementAccessExpression */:
99527                         // [source]
99528                         //      a[b] = yield;
99529                         //
99530                         // [intermediate]
99531                         //  .local _a, _b
99532                         //      _a = a;
99533                         //      _b = b;
99534                         //  .yield resumeLabel
99535                         //  .mark resumeLabel
99536                         //      _a[_b] = %sent%;
99537                         target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
99538                         break;
99539                     default:
99540                         target = ts.visitNode(left, visitor, ts.isExpression);
99541                         break;
99542                 }
99543                 var operator = node.operatorToken.kind;
99544                 if (ts.isCompoundAssignment(operator)) {
99545                     return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createBinaryExpression(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
99546                 }
99547                 else {
99548                     return factory.updateBinaryExpression(node, target, node.operatorToken, ts.visitNode(right, visitor, ts.isExpression));
99549                 }
99550             }
99551             return ts.visitEachChild(node, visitor, context);
99552         }
99553         function visitLeftAssociativeBinaryExpression(node) {
99554             if (containsYield(node.right)) {
99555                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
99556                     return visitLogicalBinaryExpression(node);
99557                 }
99558                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
99559                     return visitCommaExpression(node);
99560                 }
99561                 // [source]
99562                 //      a() + (yield) + c()
99563                 //
99564                 // [intermediate]
99565                 //  .local _a
99566                 //      _a = a();
99567                 //  .yield resumeLabel
99568                 //      _a + %sent% + c()
99569                 return factory.updateBinaryExpression(node, cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
99570             }
99571             return ts.visitEachChild(node, visitor, context);
99572         }
99573         /**
99574          * Visits a comma expression containing `yield`.
99575          *
99576          * @param node The node to visit.
99577          */
99578         function visitCommaExpression(node) {
99579             // [source]
99580             //      x = a(), yield, b();
99581             //
99582             // [intermediate]
99583             //      a();
99584             //  .yield resumeLabel
99585             //  .mark resumeLabel
99586             //      x = %sent%, b();
99587             var pendingExpressions = [];
99588             visit(node.left);
99589             visit(node.right);
99590             return factory.inlineExpressions(pendingExpressions);
99591             function visit(node) {
99592                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
99593                     visit(node.left);
99594                     visit(node.right);
99595                 }
99596                 else {
99597                     if (containsYield(node) && pendingExpressions.length > 0) {
99598                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
99599                         pendingExpressions = [];
99600                     }
99601                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
99602                 }
99603             }
99604         }
99605         /**
99606          * Visits a comma-list expression.
99607          *
99608          * @param node The node to visit.
99609          */
99610         function visitCommaListExpression(node) {
99611             // flattened version of `visitCommaExpression`
99612             var pendingExpressions = [];
99613             for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
99614                 var elem = _a[_i];
99615                 if (ts.isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */) {
99616                     pendingExpressions.push(visitCommaExpression(elem));
99617                 }
99618                 else {
99619                     if (containsYield(elem) && pendingExpressions.length > 0) {
99620                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
99621                         pendingExpressions = [];
99622                     }
99623                     pendingExpressions.push(ts.visitNode(elem, visitor, ts.isExpression));
99624                 }
99625             }
99626             return factory.inlineExpressions(pendingExpressions);
99627         }
99628         /**
99629          * Visits a logical binary expression containing `yield`.
99630          *
99631          * @param node A node to visit.
99632          */
99633         function visitLogicalBinaryExpression(node) {
99634             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
99635             // to be transformed as such:
99636             //
99637             // [source]
99638             //      x = a() && yield;
99639             //
99640             // [intermediate]
99641             //  .local _a
99642             //      _a = a();
99643             //  .brfalse resultLabel, (_a)
99644             //  .yield resumeLabel
99645             //  .mark resumeLabel
99646             //      _a = %sent%;
99647             //  .mark resultLabel
99648             //      x = _a;
99649             //
99650             // [source]
99651             //      x = a() || yield;
99652             //
99653             // [intermediate]
99654             //  .local _a
99655             //      _a = a();
99656             //  .brtrue resultLabel, (_a)
99657             //  .yield resumeLabel
99658             //  .mark resumeLabel
99659             //      _a = %sent%;
99660             //  .mark resultLabel
99661             //      x = _a;
99662             var resultLabel = defineLabel();
99663             var resultLocal = declareLocal();
99664             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
99665             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
99666                 // Logical `&&` shortcuts when the left-hand operand is falsey.
99667                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
99668             }
99669             else {
99670                 // Logical `||` shortcuts when the left-hand operand is truthy.
99671                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
99672             }
99673             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
99674             markLabel(resultLabel);
99675             return resultLocal;
99676         }
99677         /**
99678          * Visits a conditional expression containing `yield`.
99679          *
99680          * @param node The node to visit.
99681          */
99682         function visitConditionalExpression(node) {
99683             // [source]
99684             //      x = a() ? yield : b();
99685             //
99686             // [intermediate]
99687             //  .local _a
99688             //  .brfalse whenFalseLabel, (a())
99689             //  .yield resumeLabel
99690             //  .mark resumeLabel
99691             //      _a = %sent%;
99692             //  .br resultLabel
99693             //  .mark whenFalseLabel
99694             //      _a = b();
99695             //  .mark resultLabel
99696             //      x = _a;
99697             // We only need to perform a specific transformation if a `yield` expression exists
99698             // in either the `whenTrue` or `whenFalse` branches.
99699             // A `yield` in the condition will be handled by the normal visitor.
99700             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
99701                 var whenFalseLabel = defineLabel();
99702                 var resultLabel = defineLabel();
99703                 var resultLocal = declareLocal();
99704                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
99705                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
99706                 emitBreak(resultLabel);
99707                 markLabel(whenFalseLabel);
99708                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
99709                 markLabel(resultLabel);
99710                 return resultLocal;
99711             }
99712             return ts.visitEachChild(node, visitor, context);
99713         }
99714         /**
99715          * Visits a `yield` expression.
99716          *
99717          * @param node The node to visit.
99718          */
99719         function visitYieldExpression(node) {
99720             // [source]
99721             //      x = yield a();
99722             //
99723             // [intermediate]
99724             //  .yield resumeLabel, (a())
99725             //  .mark resumeLabel
99726             //      x = %sent%;
99727             var resumeLabel = defineLabel();
99728             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
99729             if (node.asteriskToken) {
99730                 // NOTE: `expression` must be defined for `yield*`.
99731                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
99732                     ? ts.setTextRange(emitHelpers().createValuesHelper(expression), node)
99733                     : expression;
99734                 emitYieldStar(iterator, /*location*/ node);
99735             }
99736             else {
99737                 emitYield(expression, /*location*/ node);
99738             }
99739             markLabel(resumeLabel);
99740             return createGeneratorResume(/*location*/ node);
99741         }
99742         /**
99743          * Visits an ArrayLiteralExpression that contains a YieldExpression.
99744          *
99745          * @param node The node to visit.
99746          */
99747         function visitArrayLiteralExpression(node) {
99748             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
99749         }
99750         /**
99751          * Visits an array of expressions containing one or more YieldExpression nodes
99752          * and returns an expression for the resulting value.
99753          *
99754          * @param elements The elements to visit.
99755          * @param multiLine Whether array literals created should be emitted on multiple lines.
99756          */
99757         function visitElements(elements, leadingElement, location, multiLine) {
99758             // [source]
99759             //      ar = [1, yield, 2];
99760             //
99761             // [intermediate]
99762             //  .local _a
99763             //      _a = [1];
99764             //  .yield resumeLabel
99765             //  .mark resumeLabel
99766             //      ar = _a.concat([%sent%, 2]);
99767             var numInitialElements = countInitialNodesWithoutYield(elements);
99768             var temp;
99769             if (numInitialElements > 0) {
99770                 temp = declareLocal();
99771                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
99772                 emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
99773                     ? __spreadArray([leadingElement], initialElements, true) : initialElements));
99774                 leadingElement = undefined;
99775             }
99776             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
99777             return temp
99778                 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
99779                 : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions, true) : expressions, multiLine), location);
99780             function reduceElement(expressions, element) {
99781                 if (containsYield(element) && expressions.length > 0) {
99782                     var hasAssignedTemp = temp !== undefined;
99783                     if (!temp) {
99784                         temp = declareLocal();
99785                     }
99786                     emitAssignment(temp, hasAssignedTemp
99787                         ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
99788                         : factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions, true) : expressions, multiLine));
99789                     leadingElement = undefined;
99790                     expressions = [];
99791                 }
99792                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
99793                 return expressions;
99794             }
99795         }
99796         function visitObjectLiteralExpression(node) {
99797             // [source]
99798             //      o = {
99799             //          a: 1,
99800             //          b: yield,
99801             //          c: 2
99802             //      };
99803             //
99804             // [intermediate]
99805             //  .local _a
99806             //      _a = {
99807             //          a: 1
99808             //      };
99809             //  .yield resumeLabel
99810             //  .mark resumeLabel
99811             //      o = (_a.b = %sent%,
99812             //          _a.c = 2,
99813             //          _a);
99814             var properties = node.properties;
99815             var multiLine = node.multiLine;
99816             var numInitialProperties = countInitialNodesWithoutYield(properties);
99817             var temp = declareLocal();
99818             emitAssignment(temp, factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
99819             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
99820             // TODO(rbuckton): Does this need to be parented?
99821             expressions.push(multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
99822             return factory.inlineExpressions(expressions);
99823             function reduceProperty(expressions, property) {
99824                 if (containsYield(property) && expressions.length > 0) {
99825                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions)));
99826                     expressions = [];
99827                 }
99828                 var expression = ts.createExpressionForObjectLiteralElementLike(factory, node, property, temp);
99829                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
99830                 if (visited) {
99831                     if (multiLine) {
99832                         ts.startOnNewLine(visited);
99833                     }
99834                     expressions.push(visited);
99835                 }
99836                 return expressions;
99837             }
99838         }
99839         /**
99840          * Visits an ElementAccessExpression that contains a YieldExpression.
99841          *
99842          * @param node The node to visit.
99843          */
99844         function visitElementAccessExpression(node) {
99845             if (containsYield(node.argumentExpression)) {
99846                 // [source]
99847                 //      a = x[yield];
99848                 //
99849                 // [intermediate]
99850                 //  .local _a
99851                 //      _a = x;
99852                 //  .yield resumeLabel
99853                 //  .mark resumeLabel
99854                 //      a = _a[%sent%]
99855                 return factory.updateElementAccessExpression(node, cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
99856             }
99857             return ts.visitEachChild(node, visitor, context);
99858         }
99859         function visitCallExpression(node) {
99860             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
99861                 // [source]
99862                 //      a.b(1, yield, 2);
99863                 //
99864                 // [intermediate]
99865                 //  .local _a, _b, _c
99866                 //      _b = (_a = a).b;
99867                 //      _c = [1];
99868                 //  .yield resumeLabel
99869                 //  .mark resumeLabel
99870                 //      _b.apply(_a, _c.concat([%sent%, 2]));
99871                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
99872                 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments)), node), node);
99873             }
99874             return ts.visitEachChild(node, visitor, context);
99875         }
99876         function visitNewExpression(node) {
99877             if (ts.forEach(node.arguments, containsYield)) {
99878                 // [source]
99879                 //      new a.b(1, yield, 2);
99880                 //
99881                 // [intermediate]
99882                 //  .local _a, _b, _c
99883                 //      _b = (_a = a.b).bind;
99884                 //      _c = [1];
99885                 //  .yield resumeLabel
99886                 //  .mark resumeLabel
99887                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
99888                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
99889                 return ts.setOriginalNode(ts.setTextRange(factory.createNewExpression(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
99890                 /*leadingElement*/ factory.createVoidZero())), 
99891                 /*typeArguments*/ undefined, []), node), node);
99892             }
99893             return ts.visitEachChild(node, visitor, context);
99894         }
99895         function transformAndEmitStatements(statements, start) {
99896             if (start === void 0) { start = 0; }
99897             var numStatements = statements.length;
99898             for (var i = start; i < numStatements; i++) {
99899                 transformAndEmitStatement(statements[i]);
99900             }
99901         }
99902         function transformAndEmitEmbeddedStatement(node) {
99903             if (ts.isBlock(node)) {
99904                 transformAndEmitStatements(node.statements);
99905             }
99906             else {
99907                 transformAndEmitStatement(node);
99908             }
99909         }
99910         function transformAndEmitStatement(node) {
99911             var savedInStatementContainingYield = inStatementContainingYield;
99912             if (!inStatementContainingYield) {
99913                 inStatementContainingYield = containsYield(node);
99914             }
99915             transformAndEmitStatementWorker(node);
99916             inStatementContainingYield = savedInStatementContainingYield;
99917         }
99918         function transformAndEmitStatementWorker(node) {
99919             switch (node.kind) {
99920                 case 234 /* Block */:
99921                     return transformAndEmitBlock(node);
99922                 case 237 /* ExpressionStatement */:
99923                     return transformAndEmitExpressionStatement(node);
99924                 case 238 /* IfStatement */:
99925                     return transformAndEmitIfStatement(node);
99926                 case 239 /* DoStatement */:
99927                     return transformAndEmitDoStatement(node);
99928                 case 240 /* WhileStatement */:
99929                     return transformAndEmitWhileStatement(node);
99930                 case 241 /* ForStatement */:
99931                     return transformAndEmitForStatement(node);
99932                 case 242 /* ForInStatement */:
99933                     return transformAndEmitForInStatement(node);
99934                 case 244 /* ContinueStatement */:
99935                     return transformAndEmitContinueStatement(node);
99936                 case 245 /* BreakStatement */:
99937                     return transformAndEmitBreakStatement(node);
99938                 case 246 /* ReturnStatement */:
99939                     return transformAndEmitReturnStatement(node);
99940                 case 247 /* WithStatement */:
99941                     return transformAndEmitWithStatement(node);
99942                 case 248 /* SwitchStatement */:
99943                     return transformAndEmitSwitchStatement(node);
99944                 case 249 /* LabeledStatement */:
99945                     return transformAndEmitLabeledStatement(node);
99946                 case 250 /* ThrowStatement */:
99947                     return transformAndEmitThrowStatement(node);
99948                 case 251 /* TryStatement */:
99949                     return transformAndEmitTryStatement(node);
99950                 default:
99951                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
99952             }
99953         }
99954         function transformAndEmitBlock(node) {
99955             if (containsYield(node)) {
99956                 transformAndEmitStatements(node.statements);
99957             }
99958             else {
99959                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
99960             }
99961         }
99962         function transformAndEmitExpressionStatement(node) {
99963             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
99964         }
99965         function transformAndEmitVariableDeclarationList(node) {
99966             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
99967                 var variable = _a[_i];
99968                 var name = factory.cloneNode(variable.name);
99969                 ts.setCommentRange(name, variable.name);
99970                 hoistVariableDeclaration(name);
99971             }
99972             var variables = ts.getInitializedVariables(node);
99973             var numVariables = variables.length;
99974             var variablesWritten = 0;
99975             var pendingExpressions = [];
99976             while (variablesWritten < numVariables) {
99977                 for (var i = variablesWritten; i < numVariables; i++) {
99978                     var variable = variables[i];
99979                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
99980                         break;
99981                     }
99982                     pendingExpressions.push(transformInitializedVariable(variable));
99983                 }
99984                 if (pendingExpressions.length) {
99985                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
99986                     variablesWritten += pendingExpressions.length;
99987                     pendingExpressions = [];
99988                 }
99989             }
99990             return undefined;
99991         }
99992         function transformInitializedVariable(node) {
99993             return ts.setSourceMapRange(factory.createAssignment(ts.setSourceMapRange(factory.cloneNode(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
99994         }
99995         function transformAndEmitIfStatement(node) {
99996             if (containsYield(node)) {
99997                 // [source]
99998                 //      if (x)
99999                 //          /*thenStatement*/
100000                 //      else
100001                 //          /*elseStatement*/
100002                 //
100003                 // [intermediate]
100004                 //  .brfalse elseLabel, (x)
100005                 //      /*thenStatement*/
100006                 //  .br endLabel
100007                 //  .mark elseLabel
100008                 //      /*elseStatement*/
100009                 //  .mark endLabel
100010                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
100011                     var endLabel = defineLabel();
100012                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
100013                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
100014                     transformAndEmitEmbeddedStatement(node.thenStatement);
100015                     if (node.elseStatement) {
100016                         emitBreak(endLabel);
100017                         markLabel(elseLabel);
100018                         transformAndEmitEmbeddedStatement(node.elseStatement);
100019                     }
100020                     markLabel(endLabel);
100021                 }
100022                 else {
100023                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100024                 }
100025             }
100026             else {
100027                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100028             }
100029         }
100030         function transformAndEmitDoStatement(node) {
100031             if (containsYield(node)) {
100032                 // [source]
100033                 //      do {
100034                 //          /*body*/
100035                 //      }
100036                 //      while (i < 10);
100037                 //
100038                 // [intermediate]
100039                 //  .loop conditionLabel, endLabel
100040                 //  .mark loopLabel
100041                 //      /*body*/
100042                 //  .mark conditionLabel
100043                 //  .brtrue loopLabel, (i < 10)
100044                 //  .endloop
100045                 //  .mark endLabel
100046                 var conditionLabel = defineLabel();
100047                 var loopLabel = defineLabel();
100048                 beginLoopBlock(/*continueLabel*/ conditionLabel);
100049                 markLabel(loopLabel);
100050                 transformAndEmitEmbeddedStatement(node.statement);
100051                 markLabel(conditionLabel);
100052                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
100053                 endLoopBlock();
100054             }
100055             else {
100056                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100057             }
100058         }
100059         function visitDoStatement(node) {
100060             if (inStatementContainingYield) {
100061                 beginScriptLoopBlock();
100062                 node = ts.visitEachChild(node, visitor, context);
100063                 endLoopBlock();
100064                 return node;
100065             }
100066             else {
100067                 return ts.visitEachChild(node, visitor, context);
100068             }
100069         }
100070         function transformAndEmitWhileStatement(node) {
100071             if (containsYield(node)) {
100072                 // [source]
100073                 //      while (i < 10) {
100074                 //          /*body*/
100075                 //      }
100076                 //
100077                 // [intermediate]
100078                 //  .loop loopLabel, endLabel
100079                 //  .mark loopLabel
100080                 //  .brfalse endLabel, (i < 10)
100081                 //      /*body*/
100082                 //  .br loopLabel
100083                 //  .endloop
100084                 //  .mark endLabel
100085                 var loopLabel = defineLabel();
100086                 var endLabel = beginLoopBlock(loopLabel);
100087                 markLabel(loopLabel);
100088                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
100089                 transformAndEmitEmbeddedStatement(node.statement);
100090                 emitBreak(loopLabel);
100091                 endLoopBlock();
100092             }
100093             else {
100094                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100095             }
100096         }
100097         function visitWhileStatement(node) {
100098             if (inStatementContainingYield) {
100099                 beginScriptLoopBlock();
100100                 node = ts.visitEachChild(node, visitor, context);
100101                 endLoopBlock();
100102                 return node;
100103             }
100104             else {
100105                 return ts.visitEachChild(node, visitor, context);
100106             }
100107         }
100108         function transformAndEmitForStatement(node) {
100109             if (containsYield(node)) {
100110                 // [source]
100111                 //      for (var i = 0; i < 10; i++) {
100112                 //          /*body*/
100113                 //      }
100114                 //
100115                 // [intermediate]
100116                 //  .local i
100117                 //      i = 0;
100118                 //  .loop incrementLabel, endLoopLabel
100119                 //  .mark conditionLabel
100120                 //  .brfalse endLoopLabel, (i < 10)
100121                 //      /*body*/
100122                 //  .mark incrementLabel
100123                 //      i++;
100124                 //  .br conditionLabel
100125                 //  .endloop
100126                 //  .mark endLoopLabel
100127                 var conditionLabel = defineLabel();
100128                 var incrementLabel = defineLabel();
100129                 var endLabel = beginLoopBlock(incrementLabel);
100130                 if (node.initializer) {
100131                     var initializer = node.initializer;
100132                     if (ts.isVariableDeclarationList(initializer)) {
100133                         transformAndEmitVariableDeclarationList(initializer);
100134                     }
100135                     else {
100136                         emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
100137                     }
100138                 }
100139                 markLabel(conditionLabel);
100140                 if (node.condition) {
100141                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
100142                 }
100143                 transformAndEmitEmbeddedStatement(node.statement);
100144                 markLabel(incrementLabel);
100145                 if (node.incrementor) {
100146                     emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
100147                 }
100148                 emitBreak(conditionLabel);
100149                 endLoopBlock();
100150             }
100151             else {
100152                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100153             }
100154         }
100155         function visitForStatement(node) {
100156             if (inStatementContainingYield) {
100157                 beginScriptLoopBlock();
100158             }
100159             var initializer = node.initializer;
100160             if (initializer && ts.isVariableDeclarationList(initializer)) {
100161                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
100162                     var variable = _a[_i];
100163                     hoistVariableDeclaration(variable.name);
100164                 }
100165                 var variables = ts.getInitializedVariables(initializer);
100166                 node = factory.updateForStatement(node, variables.length > 0
100167                     ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable))
100168                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context));
100169             }
100170             else {
100171                 node = ts.visitEachChild(node, visitor, context);
100172             }
100173             if (inStatementContainingYield) {
100174                 endLoopBlock();
100175             }
100176             return node;
100177         }
100178         function transformAndEmitForInStatement(node) {
100179             // TODO(rbuckton): Source map locations
100180             if (containsYield(node)) {
100181                 // [source]
100182                 //      for (var p in o) {
100183                 //          /*body*/
100184                 //      }
100185                 //
100186                 // [intermediate]
100187                 //  .local _a, _b, _i
100188                 //      _a = [];
100189                 //      for (_b in o) _a.push(_b);
100190                 //      _i = 0;
100191                 //  .loop incrementLabel, endLoopLabel
100192                 //  .mark conditionLabel
100193                 //  .brfalse endLoopLabel, (_i < _a.length)
100194                 //      p = _a[_i];
100195                 //      /*body*/
100196                 //  .mark incrementLabel
100197                 //      _b++;
100198                 //  .br conditionLabel
100199                 //  .endloop
100200                 //  .mark endLoopLabel
100201                 var keysArray = declareLocal(); // _a
100202                 var key = declareLocal(); // _b
100203                 var keysIndex = factory.createLoopVariable(); // _i
100204                 var initializer = node.initializer;
100205                 hoistVariableDeclaration(keysIndex);
100206                 emitAssignment(keysArray, factory.createArrayLiteralExpression());
100207                 emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), 
100208                 /*typeArguments*/ undefined, [key]))));
100209                 emitAssignment(keysIndex, factory.createNumericLiteral(0));
100210                 var conditionLabel = defineLabel();
100211                 var incrementLabel = defineLabel();
100212                 var endLabel = beginLoopBlock(incrementLabel);
100213                 markLabel(conditionLabel);
100214                 emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length")));
100215                 var variable = void 0;
100216                 if (ts.isVariableDeclarationList(initializer)) {
100217                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
100218                         var variable_1 = _a[_i];
100219                         hoistVariableDeclaration(variable_1.name);
100220                     }
100221                     variable = factory.cloneNode(initializer.declarations[0].name);
100222                 }
100223                 else {
100224                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
100225                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
100226                 }
100227                 emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex));
100228                 transformAndEmitEmbeddedStatement(node.statement);
100229                 markLabel(incrementLabel);
100230                 emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex)));
100231                 emitBreak(conditionLabel);
100232                 endLoopBlock();
100233             }
100234             else {
100235                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100236             }
100237         }
100238         function visitForInStatement(node) {
100239             // [source]
100240             //      for (var x in a) {
100241             //          /*body*/
100242             //      }
100243             //
100244             // [intermediate]
100245             //  .local x
100246             //  .loop
100247             //      for (x in a) {
100248             //          /*body*/
100249             //      }
100250             //  .endloop
100251             if (inStatementContainingYield) {
100252                 beginScriptLoopBlock();
100253             }
100254             var initializer = node.initializer;
100255             if (ts.isVariableDeclarationList(initializer)) {
100256                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
100257                     var variable = _a[_i];
100258                     hoistVariableDeclaration(variable.name);
100259                 }
100260                 node = factory.updateForInStatement(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
100261             }
100262             else {
100263                 node = ts.visitEachChild(node, visitor, context);
100264             }
100265             if (inStatementContainingYield) {
100266                 endLoopBlock();
100267             }
100268             return node;
100269         }
100270         function transformAndEmitContinueStatement(node) {
100271             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
100272             if (label > 0) {
100273                 emitBreak(label, /*location*/ node);
100274             }
100275             else {
100276                 // invalid continue without a containing loop. Leave the node as is, per #17875.
100277                 emitStatement(node);
100278             }
100279         }
100280         function visitContinueStatement(node) {
100281             if (inStatementContainingYield) {
100282                 var label = findContinueTarget(node.label && ts.idText(node.label));
100283                 if (label > 0) {
100284                     return createInlineBreak(label, /*location*/ node);
100285                 }
100286             }
100287             return ts.visitEachChild(node, visitor, context);
100288         }
100289         function transformAndEmitBreakStatement(node) {
100290             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
100291             if (label > 0) {
100292                 emitBreak(label, /*location*/ node);
100293             }
100294             else {
100295                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
100296                 emitStatement(node);
100297             }
100298         }
100299         function visitBreakStatement(node) {
100300             if (inStatementContainingYield) {
100301                 var label = findBreakTarget(node.label && ts.idText(node.label));
100302                 if (label > 0) {
100303                     return createInlineBreak(label, /*location*/ node);
100304                 }
100305             }
100306             return ts.visitEachChild(node, visitor, context);
100307         }
100308         function transformAndEmitReturnStatement(node) {
100309             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
100310             /*location*/ node);
100311         }
100312         function visitReturnStatement(node) {
100313             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
100314             /*location*/ node);
100315         }
100316         function transformAndEmitWithStatement(node) {
100317             if (containsYield(node)) {
100318                 // [source]
100319                 //      with (x) {
100320                 //          /*body*/
100321                 //      }
100322                 //
100323                 // [intermediate]
100324                 //  .with (x)
100325                 //      /*body*/
100326                 //  .endwith
100327                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
100328                 transformAndEmitEmbeddedStatement(node.statement);
100329                 endWithBlock();
100330             }
100331             else {
100332                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100333             }
100334         }
100335         function transformAndEmitSwitchStatement(node) {
100336             if (containsYield(node.caseBlock)) {
100337                 // [source]
100338                 //      switch (x) {
100339                 //          case a:
100340                 //              /*caseStatements*/
100341                 //          case b:
100342                 //              /*caseStatements*/
100343                 //          default:
100344                 //              /*defaultStatements*/
100345                 //      }
100346                 //
100347                 // [intermediate]
100348                 //  .local _a
100349                 //  .switch endLabel
100350                 //      _a = x;
100351                 //      switch (_a) {
100352                 //          case a:
100353                 //  .br clauseLabels[0]
100354                 //      }
100355                 //      switch (_a) {
100356                 //          case b:
100357                 //  .br clauseLabels[1]
100358                 //      }
100359                 //  .br clauseLabels[2]
100360                 //  .mark clauseLabels[0]
100361                 //      /*caseStatements*/
100362                 //  .mark clauseLabels[1]
100363                 //      /*caseStatements*/
100364                 //  .mark clauseLabels[2]
100365                 //      /*caseStatements*/
100366                 //  .endswitch
100367                 //  .mark endLabel
100368                 var caseBlock = node.caseBlock;
100369                 var numClauses = caseBlock.clauses.length;
100370                 var endLabel = beginSwitchBlock();
100371                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
100372                 // Create labels for each clause and find the index of the first default clause.
100373                 var clauseLabels = [];
100374                 var defaultClauseIndex = -1;
100375                 for (var i = 0; i < numClauses; i++) {
100376                     var clause = caseBlock.clauses[i];
100377                     clauseLabels.push(defineLabel());
100378                     if (clause.kind === 289 /* DefaultClause */ && defaultClauseIndex === -1) {
100379                         defaultClauseIndex = i;
100380                     }
100381                 }
100382                 // Emit switch statements for each run of case clauses either from the first case
100383                 // clause or the next case clause with a `yield` in its expression, up to the next
100384                 // case clause with a `yield` in its expression.
100385                 var clausesWritten = 0;
100386                 var pendingClauses = [];
100387                 while (clausesWritten < numClauses) {
100388                     var defaultClausesSkipped = 0;
100389                     for (var i = clausesWritten; i < numClauses; i++) {
100390                         var clause = caseBlock.clauses[i];
100391                         if (clause.kind === 288 /* CaseClause */) {
100392                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
100393                                 break;
100394                             }
100395                             pendingClauses.push(factory.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
100396                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
100397                             ]));
100398                         }
100399                         else {
100400                             defaultClausesSkipped++;
100401                         }
100402                     }
100403                     if (pendingClauses.length) {
100404                         emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses)));
100405                         clausesWritten += pendingClauses.length;
100406                         pendingClauses = [];
100407                     }
100408                     if (defaultClausesSkipped > 0) {
100409                         clausesWritten += defaultClausesSkipped;
100410                         defaultClausesSkipped = 0;
100411                     }
100412                 }
100413                 if (defaultClauseIndex >= 0) {
100414                     emitBreak(clauseLabels[defaultClauseIndex]);
100415                 }
100416                 else {
100417                     emitBreak(endLabel);
100418                 }
100419                 for (var i = 0; i < numClauses; i++) {
100420                     markLabel(clauseLabels[i]);
100421                     transformAndEmitStatements(caseBlock.clauses[i].statements);
100422                 }
100423                 endSwitchBlock();
100424             }
100425             else {
100426                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100427             }
100428         }
100429         function visitSwitchStatement(node) {
100430             if (inStatementContainingYield) {
100431                 beginScriptSwitchBlock();
100432             }
100433             node = ts.visitEachChild(node, visitor, context);
100434             if (inStatementContainingYield) {
100435                 endSwitchBlock();
100436             }
100437             return node;
100438         }
100439         function transformAndEmitLabeledStatement(node) {
100440             if (containsYield(node)) {
100441                 // [source]
100442                 //      x: {
100443                 //          /*body*/
100444                 //      }
100445                 //
100446                 // [intermediate]
100447                 //  .labeled "x", endLabel
100448                 //      /*body*/
100449                 //  .endlabeled
100450                 //  .mark endLabel
100451                 beginLabeledBlock(ts.idText(node.label));
100452                 transformAndEmitEmbeddedStatement(node.statement);
100453                 endLabeledBlock();
100454             }
100455             else {
100456                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
100457             }
100458         }
100459         function visitLabeledStatement(node) {
100460             if (inStatementContainingYield) {
100461                 beginScriptLabeledBlock(ts.idText(node.label));
100462             }
100463             node = ts.visitEachChild(node, visitor, context);
100464             if (inStatementContainingYield) {
100465                 endLabeledBlock();
100466             }
100467             return node;
100468         }
100469         function transformAndEmitThrowStatement(node) {
100470             var _a;
100471             // TODO(rbuckton): `expression` should be required on `throw`.
100472             emitThrow(ts.visitNode((_a = node.expression) !== null && _a !== void 0 ? _a : factory.createVoidZero(), visitor, ts.isExpression), 
100473             /*location*/ node);
100474         }
100475         function transformAndEmitTryStatement(node) {
100476             if (containsYield(node)) {
100477                 // [source]
100478                 //      try {
100479                 //          /*tryBlock*/
100480                 //      }
100481                 //      catch (e) {
100482                 //          /*catchBlock*/
100483                 //      }
100484                 //      finally {
100485                 //          /*finallyBlock*/
100486                 //      }
100487                 //
100488                 // [intermediate]
100489                 //  .local _a
100490                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
100491                 //  .mark tryLabel
100492                 //  .nop
100493                 //      /*tryBlock*/
100494                 //  .br endLabel
100495                 //  .catch
100496                 //  .mark catchLabel
100497                 //      _a = %error%;
100498                 //      /*catchBlock*/
100499                 //  .br endLabel
100500                 //  .finally
100501                 //  .mark finallyLabel
100502                 //      /*finallyBlock*/
100503                 //  .endfinally
100504                 //  .endtry
100505                 //  .mark endLabel
100506                 beginExceptionBlock();
100507                 transformAndEmitEmbeddedStatement(node.tryBlock);
100508                 if (node.catchClause) {
100509                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
100510                     transformAndEmitEmbeddedStatement(node.catchClause.block);
100511                 }
100512                 if (node.finallyBlock) {
100513                     beginFinallyBlock();
100514                     transformAndEmitEmbeddedStatement(node.finallyBlock);
100515                 }
100516                 endExceptionBlock();
100517             }
100518             else {
100519                 emitStatement(ts.visitEachChild(node, visitor, context));
100520             }
100521         }
100522         function containsYield(node) {
100523             return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0;
100524         }
100525         function countInitialNodesWithoutYield(nodes) {
100526             var numNodes = nodes.length;
100527             for (var i = 0; i < numNodes; i++) {
100528                 if (containsYield(nodes[i])) {
100529                     return i;
100530                 }
100531             }
100532             return -1;
100533         }
100534         function onSubstituteNode(hint, node) {
100535             node = previousOnSubstituteNode(hint, node);
100536             if (hint === 1 /* Expression */) {
100537                 return substituteExpression(node);
100538             }
100539             return node;
100540         }
100541         function substituteExpression(node) {
100542             if (ts.isIdentifier(node)) {
100543                 return substituteExpressionIdentifier(node);
100544             }
100545             return node;
100546         }
100547         function substituteExpressionIdentifier(node) {
100548             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
100549                 var original = ts.getOriginalNode(node);
100550                 if (ts.isIdentifier(original) && original.parent) {
100551                     var declaration = resolver.getReferencedValueDeclaration(original);
100552                     if (declaration) {
100553                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
100554                         if (name) {
100555                             // TODO(rbuckton): Does this need to be parented?
100556                             var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
100557                             ts.setSourceMapRange(clone_6, node);
100558                             ts.setCommentRange(clone_6, node);
100559                             return clone_6;
100560                         }
100561                     }
100562                 }
100563             }
100564             return node;
100565         }
100566         function cacheExpression(node) {
100567             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
100568                 return node;
100569             }
100570             var temp = factory.createTempVariable(hoistVariableDeclaration);
100571             emitAssignment(temp, node, /*location*/ node);
100572             return temp;
100573         }
100574         function declareLocal(name) {
100575             var temp = name
100576                 ? factory.createUniqueName(name)
100577                 : factory.createTempVariable(/*recordTempVariable*/ undefined);
100578             hoistVariableDeclaration(temp);
100579             return temp;
100580         }
100581         /**
100582          * Defines a label, uses as the target of a Break operation.
100583          */
100584         function defineLabel() {
100585             if (!labelOffsets) {
100586                 labelOffsets = [];
100587             }
100588             var label = nextLabelId;
100589             nextLabelId++;
100590             labelOffsets[label] = -1;
100591             return label;
100592         }
100593         /**
100594          * Marks the current operation with the specified label.
100595          */
100596         function markLabel(label) {
100597             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
100598             labelOffsets[label] = operations ? operations.length : 0;
100599         }
100600         /**
100601          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
100602          *
100603          * @param block Information about the block.
100604          */
100605         function beginBlock(block) {
100606             if (!blocks) {
100607                 blocks = [];
100608                 blockActions = [];
100609                 blockOffsets = [];
100610                 blockStack = [];
100611             }
100612             var index = blockActions.length;
100613             blockActions[index] = 0 /* Open */;
100614             blockOffsets[index] = operations ? operations.length : 0;
100615             blocks[index] = block;
100616             blockStack.push(block);
100617             return index;
100618         }
100619         /**
100620          * Ends the current block operation.
100621          */
100622         function endBlock() {
100623             var block = peekBlock();
100624             if (block === undefined)
100625                 return ts.Debug.fail("beginBlock was never called.");
100626             var index = blockActions.length;
100627             blockActions[index] = 1 /* Close */;
100628             blockOffsets[index] = operations ? operations.length : 0;
100629             blocks[index] = block;
100630             blockStack.pop();
100631             return block;
100632         }
100633         /**
100634          * Gets the current open block.
100635          */
100636         function peekBlock() {
100637             return ts.lastOrUndefined(blockStack);
100638         }
100639         /**
100640          * Gets the kind of the current open block.
100641          */
100642         function peekBlockKind() {
100643             var block = peekBlock();
100644             return block && block.kind;
100645         }
100646         /**
100647          * Begins a code block for a generated `with` statement.
100648          *
100649          * @param expression An identifier representing expression for the `with` block.
100650          */
100651         function beginWithBlock(expression) {
100652             var startLabel = defineLabel();
100653             var endLabel = defineLabel();
100654             markLabel(startLabel);
100655             beginBlock({
100656                 kind: 1 /* With */,
100657                 expression: expression,
100658                 startLabel: startLabel,
100659                 endLabel: endLabel
100660             });
100661         }
100662         /**
100663          * Ends a code block for a generated `with` statement.
100664          */
100665         function endWithBlock() {
100666             ts.Debug.assert(peekBlockKind() === 1 /* With */);
100667             var block = endBlock();
100668             markLabel(block.endLabel);
100669         }
100670         /**
100671          * Begins a code block for a generated `try` statement.
100672          */
100673         function beginExceptionBlock() {
100674             var startLabel = defineLabel();
100675             var endLabel = defineLabel();
100676             markLabel(startLabel);
100677             beginBlock({
100678                 kind: 0 /* Exception */,
100679                 state: 0 /* Try */,
100680                 startLabel: startLabel,
100681                 endLabel: endLabel
100682             });
100683             emitNop();
100684             return endLabel;
100685         }
100686         /**
100687          * Enters the `catch` clause of a generated `try` statement.
100688          *
100689          * @param variable The catch variable.
100690          */
100691         function beginCatchBlock(variable) {
100692             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
100693             // generated identifiers should already be unique within a file
100694             var name;
100695             if (ts.isGeneratedIdentifier(variable.name)) {
100696                 name = variable.name;
100697                 hoistVariableDeclaration(variable.name);
100698             }
100699             else {
100700                 var text = ts.idText(variable.name);
100701                 name = declareLocal(text);
100702                 if (!renamedCatchVariables) {
100703                     renamedCatchVariables = new ts.Map();
100704                     renamedCatchVariableDeclarations = [];
100705                     context.enableSubstitution(79 /* Identifier */);
100706                 }
100707                 renamedCatchVariables.set(text, true);
100708                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
100709             }
100710             var exception = peekBlock();
100711             ts.Debug.assert(exception.state < 1 /* Catch */);
100712             var endLabel = exception.endLabel;
100713             emitBreak(endLabel);
100714             var catchLabel = defineLabel();
100715             markLabel(catchLabel);
100716             exception.state = 1 /* Catch */;
100717             exception.catchVariable = name;
100718             exception.catchLabel = catchLabel;
100719             emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, []));
100720             emitNop();
100721         }
100722         /**
100723          * Enters the `finally` block of a generated `try` statement.
100724          */
100725         function beginFinallyBlock() {
100726             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
100727             var exception = peekBlock();
100728             ts.Debug.assert(exception.state < 2 /* Finally */);
100729             var endLabel = exception.endLabel;
100730             emitBreak(endLabel);
100731             var finallyLabel = defineLabel();
100732             markLabel(finallyLabel);
100733             exception.state = 2 /* Finally */;
100734             exception.finallyLabel = finallyLabel;
100735         }
100736         /**
100737          * Ends the code block for a generated `try` statement.
100738          */
100739         function endExceptionBlock() {
100740             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
100741             var exception = endBlock();
100742             var state = exception.state;
100743             if (state < 2 /* Finally */) {
100744                 emitBreak(exception.endLabel);
100745             }
100746             else {
100747                 emitEndfinally();
100748             }
100749             markLabel(exception.endLabel);
100750             emitNop();
100751             exception.state = 3 /* Done */;
100752         }
100753         /**
100754          * Begins a code block that supports `break` or `continue` statements that are defined in
100755          * the source tree and not from generated code.
100756          *
100757          * @param labelText Names from containing labeled statements.
100758          */
100759         function beginScriptLoopBlock() {
100760             beginBlock({
100761                 kind: 3 /* Loop */,
100762                 isScript: true,
100763                 breakLabel: -1,
100764                 continueLabel: -1
100765             });
100766         }
100767         /**
100768          * Begins a code block that supports `break` or `continue` statements that are defined in
100769          * generated code. Returns a label used to mark the operation to which to jump when a
100770          * `break` statement targets this block.
100771          *
100772          * @param continueLabel A Label used to mark the operation to which to jump when a
100773          *                      `continue` statement targets this block.
100774          */
100775         function beginLoopBlock(continueLabel) {
100776             var breakLabel = defineLabel();
100777             beginBlock({
100778                 kind: 3 /* Loop */,
100779                 isScript: false,
100780                 breakLabel: breakLabel,
100781                 continueLabel: continueLabel,
100782             });
100783             return breakLabel;
100784         }
100785         /**
100786          * Ends a code block that supports `break` or `continue` statements that are defined in
100787          * generated code or in the source tree.
100788          */
100789         function endLoopBlock() {
100790             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
100791             var block = endBlock();
100792             var breakLabel = block.breakLabel;
100793             if (!block.isScript) {
100794                 markLabel(breakLabel);
100795             }
100796         }
100797         /**
100798          * Begins a code block that supports `break` statements that are defined in the source
100799          * tree and not from generated code.
100800          *
100801          */
100802         function beginScriptSwitchBlock() {
100803             beginBlock({
100804                 kind: 2 /* Switch */,
100805                 isScript: true,
100806                 breakLabel: -1
100807             });
100808         }
100809         /**
100810          * Begins a code block that supports `break` statements that are defined in generated code.
100811          * Returns a label used to mark the operation to which to jump when a `break` statement
100812          * targets this block.
100813          */
100814         function beginSwitchBlock() {
100815             var breakLabel = defineLabel();
100816             beginBlock({
100817                 kind: 2 /* Switch */,
100818                 isScript: false,
100819                 breakLabel: breakLabel,
100820             });
100821             return breakLabel;
100822         }
100823         /**
100824          * Ends a code block that supports `break` statements that are defined in generated code.
100825          */
100826         function endSwitchBlock() {
100827             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
100828             var block = endBlock();
100829             var breakLabel = block.breakLabel;
100830             if (!block.isScript) {
100831                 markLabel(breakLabel);
100832             }
100833         }
100834         function beginScriptLabeledBlock(labelText) {
100835             beginBlock({
100836                 kind: 4 /* Labeled */,
100837                 isScript: true,
100838                 labelText: labelText,
100839                 breakLabel: -1
100840             });
100841         }
100842         function beginLabeledBlock(labelText) {
100843             var breakLabel = defineLabel();
100844             beginBlock({
100845                 kind: 4 /* Labeled */,
100846                 isScript: false,
100847                 labelText: labelText,
100848                 breakLabel: breakLabel
100849             });
100850         }
100851         function endLabeledBlock() {
100852             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
100853             var block = endBlock();
100854             if (!block.isScript) {
100855                 markLabel(block.breakLabel);
100856             }
100857         }
100858         /**
100859          * Indicates whether the provided block supports `break` statements.
100860          *
100861          * @param block A code block.
100862          */
100863         function supportsUnlabeledBreak(block) {
100864             return block.kind === 2 /* Switch */
100865                 || block.kind === 3 /* Loop */;
100866         }
100867         /**
100868          * Indicates whether the provided block supports `break` statements with labels.
100869          *
100870          * @param block A code block.
100871          */
100872         function supportsLabeledBreakOrContinue(block) {
100873             return block.kind === 4 /* Labeled */;
100874         }
100875         /**
100876          * Indicates whether the provided block supports `continue` statements.
100877          *
100878          * @param block A code block.
100879          */
100880         function supportsUnlabeledContinue(block) {
100881             return block.kind === 3 /* Loop */;
100882         }
100883         function hasImmediateContainingLabeledBlock(labelText, start) {
100884             for (var j = start; j >= 0; j--) {
100885                 var containingBlock = blockStack[j];
100886                 if (supportsLabeledBreakOrContinue(containingBlock)) {
100887                     if (containingBlock.labelText === labelText) {
100888                         return true;
100889                     }
100890                 }
100891                 else {
100892                     break;
100893                 }
100894             }
100895             return false;
100896         }
100897         /**
100898          * Finds the label that is the target for a `break` statement.
100899          *
100900          * @param labelText An optional name of a containing labeled statement.
100901          */
100902         function findBreakTarget(labelText) {
100903             if (blockStack) {
100904                 if (labelText) {
100905                     for (var i = blockStack.length - 1; i >= 0; i--) {
100906                         var block = blockStack[i];
100907                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
100908                             return block.breakLabel;
100909                         }
100910                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
100911                             return block.breakLabel;
100912                         }
100913                     }
100914                 }
100915                 else {
100916                     for (var i = blockStack.length - 1; i >= 0; i--) {
100917                         var block = blockStack[i];
100918                         if (supportsUnlabeledBreak(block)) {
100919                             return block.breakLabel;
100920                         }
100921                     }
100922                 }
100923             }
100924             return 0;
100925         }
100926         /**
100927          * Finds the label that is the target for a `continue` statement.
100928          *
100929          * @param labelText An optional name of a containing labeled statement.
100930          */
100931         function findContinueTarget(labelText) {
100932             if (blockStack) {
100933                 if (labelText) {
100934                     for (var i = blockStack.length - 1; i >= 0; i--) {
100935                         var block = blockStack[i];
100936                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
100937                             return block.continueLabel;
100938                         }
100939                     }
100940                 }
100941                 else {
100942                     for (var i = blockStack.length - 1; i >= 0; i--) {
100943                         var block = blockStack[i];
100944                         if (supportsUnlabeledContinue(block)) {
100945                             return block.continueLabel;
100946                         }
100947                     }
100948                 }
100949             }
100950             return 0;
100951         }
100952         /**
100953          * Creates an expression that can be used to indicate the value for a label.
100954          *
100955          * @param label A label.
100956          */
100957         function createLabel(label) {
100958             if (label !== undefined && label > 0) {
100959                 if (labelExpressions === undefined) {
100960                     labelExpressions = [];
100961                 }
100962                 var expression = factory.createNumericLiteral(-1);
100963                 if (labelExpressions[label] === undefined) {
100964                     labelExpressions[label] = [expression];
100965                 }
100966                 else {
100967                     labelExpressions[label].push(expression);
100968                 }
100969                 return expression;
100970             }
100971             return factory.createOmittedExpression();
100972         }
100973         /**
100974          * Creates a numeric literal for the provided instruction.
100975          */
100976         function createInstruction(instruction) {
100977             var literal = factory.createNumericLiteral(instruction);
100978             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
100979             return literal;
100980         }
100981         /**
100982          * Creates a statement that can be used indicate a Break operation to the provided label.
100983          *
100984          * @param label A label.
100985          * @param location An optional source map location for the statement.
100986          */
100987         function createInlineBreak(label, location) {
100988             ts.Debug.assertLessThan(0, label, "Invalid label");
100989             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
100990                 createInstruction(3 /* Break */),
100991                 createLabel(label)
100992             ])), location);
100993         }
100994         /**
100995          * Creates a statement that can be used indicate a Return operation.
100996          *
100997          * @param expression The expression for the return statement.
100998          * @param location An optional source map location for the statement.
100999          */
101000         function createInlineReturn(expression, location) {
101001             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
101002                 ? [createInstruction(2 /* Return */), expression]
101003                 : [createInstruction(2 /* Return */)])), location);
101004         }
101005         /**
101006          * Creates an expression that can be used to resume from a Yield operation.
101007          */
101008         function createGeneratorResume(location) {
101009             return ts.setTextRange(factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), 
101010             /*typeArguments*/ undefined, []), location);
101011         }
101012         /**
101013          * Emits an empty instruction.
101014          */
101015         function emitNop() {
101016             emitWorker(0 /* Nop */);
101017         }
101018         /**
101019          * Emits a Statement.
101020          *
101021          * @param node A statement.
101022          */
101023         function emitStatement(node) {
101024             if (node) {
101025                 emitWorker(1 /* Statement */, [node]);
101026             }
101027             else {
101028                 emitNop();
101029             }
101030         }
101031         /**
101032          * Emits an Assignment operation.
101033          *
101034          * @param left The left-hand side of the assignment.
101035          * @param right The right-hand side of the assignment.
101036          * @param location An optional source map location for the assignment.
101037          */
101038         function emitAssignment(left, right, location) {
101039             emitWorker(2 /* Assign */, [left, right], location);
101040         }
101041         /**
101042          * Emits a Break operation to the specified label.
101043          *
101044          * @param label A label.
101045          * @param location An optional source map location for the assignment.
101046          */
101047         function emitBreak(label, location) {
101048             emitWorker(3 /* Break */, [label], location);
101049         }
101050         /**
101051          * Emits a Break operation to the specified label when a condition evaluates to a truthy
101052          * value at runtime.
101053          *
101054          * @param label A label.
101055          * @param condition The condition.
101056          * @param location An optional source map location for the assignment.
101057          */
101058         function emitBreakWhenTrue(label, condition, location) {
101059             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
101060         }
101061         /**
101062          * Emits a Break to the specified label when a condition evaluates to a falsey value at
101063          * runtime.
101064          *
101065          * @param label A label.
101066          * @param condition The condition.
101067          * @param location An optional source map location for the assignment.
101068          */
101069         function emitBreakWhenFalse(label, condition, location) {
101070             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
101071         }
101072         /**
101073          * Emits a YieldStar operation for the provided expression.
101074          *
101075          * @param expression An optional value for the yield operation.
101076          * @param location An optional source map location for the assignment.
101077          */
101078         function emitYieldStar(expression, location) {
101079             emitWorker(7 /* YieldStar */, [expression], location);
101080         }
101081         /**
101082          * Emits a Yield operation for the provided expression.
101083          *
101084          * @param expression An optional value for the yield operation.
101085          * @param location An optional source map location for the assignment.
101086          */
101087         function emitYield(expression, location) {
101088             emitWorker(6 /* Yield */, [expression], location);
101089         }
101090         /**
101091          * Emits a Return operation for the provided expression.
101092          *
101093          * @param expression An optional value for the operation.
101094          * @param location An optional source map location for the assignment.
101095          */
101096         function emitReturn(expression, location) {
101097             emitWorker(8 /* Return */, [expression], location);
101098         }
101099         /**
101100          * Emits a Throw operation for the provided expression.
101101          *
101102          * @param expression A value for the operation.
101103          * @param location An optional source map location for the assignment.
101104          */
101105         function emitThrow(expression, location) {
101106             emitWorker(9 /* Throw */, [expression], location);
101107         }
101108         /**
101109          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
101110          */
101111         function emitEndfinally() {
101112             emitWorker(10 /* Endfinally */);
101113         }
101114         /**
101115          * Emits an operation.
101116          *
101117          * @param code The OpCode for the operation.
101118          * @param args The optional arguments for the operation.
101119          */
101120         function emitWorker(code, args, location) {
101121             if (operations === undefined) {
101122                 operations = [];
101123                 operationArguments = [];
101124                 operationLocations = [];
101125             }
101126             if (labelOffsets === undefined) {
101127                 // mark entry point
101128                 markLabel(defineLabel());
101129             }
101130             var operationIndex = operations.length;
101131             operations[operationIndex] = code;
101132             operationArguments[operationIndex] = args;
101133             operationLocations[operationIndex] = location;
101134         }
101135         /**
101136          * Builds the generator function body.
101137          */
101138         function build() {
101139             blockIndex = 0;
101140             labelNumber = 0;
101141             labelNumbers = undefined;
101142             lastOperationWasAbrupt = false;
101143             lastOperationWasCompletion = false;
101144             clauses = undefined;
101145             statements = undefined;
101146             exceptionBlockStack = undefined;
101147             currentExceptionBlock = undefined;
101148             withBlockStack = undefined;
101149             var buildResult = buildStatements();
101150             return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(
101151             /*modifiers*/ undefined, 
101152             /*asteriskToken*/ undefined, 
101153             /*name*/ undefined, 
101154             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
101155             /*type*/ undefined, factory.createBlock(buildResult, 
101156             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
101157         }
101158         /**
101159          * Builds the statements for the generator function body.
101160          */
101161         function buildStatements() {
101162             if (operations) {
101163                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
101164                     writeOperation(operationIndex);
101165                 }
101166                 flushFinalLabel(operations.length);
101167             }
101168             else {
101169                 flushFinalLabel(0);
101170             }
101171             if (clauses) {
101172                 var labelExpression = factory.createPropertyAccessExpression(state, "label");
101173                 var switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
101174                 return [ts.startOnNewLine(switchStatement)];
101175             }
101176             if (statements) {
101177                 return statements;
101178             }
101179             return [];
101180         }
101181         /**
101182          * Flush the current label and advance to a new label.
101183          */
101184         function flushLabel() {
101185             if (!statements) {
101186                 return;
101187             }
101188             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
101189             lastOperationWasAbrupt = false;
101190             lastOperationWasCompletion = false;
101191             labelNumber++;
101192         }
101193         /**
101194          * Flush the final label of the generator function body.
101195          */
101196         function flushFinalLabel(operationIndex) {
101197             if (isFinalLabelReachable(operationIndex)) {
101198                 tryEnterLabel(operationIndex);
101199                 withBlockStack = undefined;
101200                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
101201             }
101202             if (statements && clauses) {
101203                 appendLabel(/*markLabelEnd*/ false);
101204             }
101205             updateLabelExpressions();
101206         }
101207         /**
101208          * Tests whether the final label of the generator function body
101209          * is reachable by user code.
101210          */
101211         function isFinalLabelReachable(operationIndex) {
101212             // if the last operation was *not* a completion (return/throw) then
101213             // the final label is reachable.
101214             if (!lastOperationWasCompletion) {
101215                 return true;
101216             }
101217             // if there are no labels defined or referenced, then the final label is
101218             // not reachable.
101219             if (!labelOffsets || !labelExpressions) {
101220                 return false;
101221             }
101222             // if the label for this offset is referenced, then the final label
101223             // is reachable.
101224             for (var label = 0; label < labelOffsets.length; label++) {
101225                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
101226                     return true;
101227                 }
101228             }
101229             return false;
101230         }
101231         /**
101232          * Appends a case clause for the last label and sets the new label.
101233          *
101234          * @param markLabelEnd Indicates that the transition between labels was a fall-through
101235          *                     from a previous case clause and the change in labels should be
101236          *                     reflected on the `state` object.
101237          */
101238         function appendLabel(markLabelEnd) {
101239             if (!clauses) {
101240                 clauses = [];
101241             }
101242             if (statements) {
101243                 if (withBlockStack) {
101244                     // The previous label was nested inside one or more `with` blocks, so we
101245                     // surround the statements in generated `with` blocks to create the same environment.
101246                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
101247                         var withBlock = withBlockStack[i];
101248                         statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))];
101249                     }
101250                 }
101251                 if (currentExceptionBlock) {
101252                     // The previous label was nested inside of an exception block, so we must
101253                     // indicate entry into a protected region by pushing the label numbers
101254                     // for each block in the protected region.
101255                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
101256                     statements.unshift(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"), 
101257                     /*typeArguments*/ undefined, [
101258                         factory.createArrayLiteralExpression([
101259                             createLabel(startLabel),
101260                             createLabel(catchLabel),
101261                             createLabel(finallyLabel),
101262                             createLabel(endLabel)
101263                         ])
101264                     ])));
101265                     currentExceptionBlock = undefined;
101266                 }
101267                 if (markLabelEnd) {
101268                     // The case clause for the last label falls through to this label, so we
101269                     // add an assignment statement to reflect the change in labels.
101270                     statements.push(factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(state, "label"), factory.createNumericLiteral(labelNumber + 1))));
101271                 }
101272             }
101273             clauses.push(factory.createCaseClause(factory.createNumericLiteral(labelNumber), statements || []));
101274             statements = undefined;
101275         }
101276         /**
101277          * Tries to enter into a new label at the current operation index.
101278          */
101279         function tryEnterLabel(operationIndex) {
101280             if (!labelOffsets) {
101281                 return;
101282             }
101283             for (var label = 0; label < labelOffsets.length; label++) {
101284                 if (labelOffsets[label] === operationIndex) {
101285                     flushLabel();
101286                     if (labelNumbers === undefined) {
101287                         labelNumbers = [];
101288                     }
101289                     if (labelNumbers[labelNumber] === undefined) {
101290                         labelNumbers[labelNumber] = [label];
101291                     }
101292                     else {
101293                         labelNumbers[labelNumber].push(label);
101294                     }
101295                 }
101296             }
101297         }
101298         /**
101299          * Updates literal expressions for labels with actual label numbers.
101300          */
101301         function updateLabelExpressions() {
101302             if (labelExpressions !== undefined && labelNumbers !== undefined) {
101303                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
101304                     var labels = labelNumbers[labelNumber_1];
101305                     if (labels !== undefined) {
101306                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
101307                             var label = labels_1[_i];
101308                             var expressions = labelExpressions[label];
101309                             if (expressions !== undefined) {
101310                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
101311                                     var expression = expressions_1[_a];
101312                                     expression.text = String(labelNumber_1);
101313                                 }
101314                             }
101315                         }
101316                     }
101317                 }
101318             }
101319         }
101320         /**
101321          * Tries to enter or leave a code block.
101322          */
101323         function tryEnterOrLeaveBlock(operationIndex) {
101324             if (blocks) {
101325                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
101326                     var block = blocks[blockIndex];
101327                     var blockAction = blockActions[blockIndex];
101328                     switch (block.kind) {
101329                         case 0 /* Exception */:
101330                             if (blockAction === 0 /* Open */) {
101331                                 if (!exceptionBlockStack) {
101332                                     exceptionBlockStack = [];
101333                                 }
101334                                 if (!statements) {
101335                                     statements = [];
101336                                 }
101337                                 exceptionBlockStack.push(currentExceptionBlock);
101338                                 currentExceptionBlock = block;
101339                             }
101340                             else if (blockAction === 1 /* Close */) {
101341                                 currentExceptionBlock = exceptionBlockStack.pop();
101342                             }
101343                             break;
101344                         case 1 /* With */:
101345                             if (blockAction === 0 /* Open */) {
101346                                 if (!withBlockStack) {
101347                                     withBlockStack = [];
101348                                 }
101349                                 withBlockStack.push(block);
101350                             }
101351                             else if (blockAction === 1 /* Close */) {
101352                                 withBlockStack.pop();
101353                             }
101354                             break;
101355                         // default: do nothing
101356                     }
101357                 }
101358             }
101359         }
101360         /**
101361          * Writes an operation as a statement to the current label's statement list.
101362          *
101363          * @param operation The OpCode of the operation
101364          */
101365         function writeOperation(operationIndex) {
101366             tryEnterLabel(operationIndex);
101367             tryEnterOrLeaveBlock(operationIndex);
101368             // early termination, nothing else to process in this label
101369             if (lastOperationWasAbrupt) {
101370                 return;
101371             }
101372             lastOperationWasAbrupt = false;
101373             lastOperationWasCompletion = false;
101374             var opcode = operations[operationIndex];
101375             if (opcode === 0 /* Nop */) {
101376                 return;
101377             }
101378             else if (opcode === 10 /* Endfinally */) {
101379                 return writeEndfinally();
101380             }
101381             var args = operationArguments[operationIndex];
101382             if (opcode === 1 /* Statement */) {
101383                 return writeStatement(args[0]);
101384             }
101385             var location = operationLocations[operationIndex];
101386             switch (opcode) {
101387                 case 2 /* Assign */:
101388                     return writeAssign(args[0], args[1], location);
101389                 case 3 /* Break */:
101390                     return writeBreak(args[0], location);
101391                 case 4 /* BreakWhenTrue */:
101392                     return writeBreakWhenTrue(args[0], args[1], location);
101393                 case 5 /* BreakWhenFalse */:
101394                     return writeBreakWhenFalse(args[0], args[1], location);
101395                 case 6 /* Yield */:
101396                     return writeYield(args[0], location);
101397                 case 7 /* YieldStar */:
101398                     return writeYieldStar(args[0], location);
101399                 case 8 /* Return */:
101400                     return writeReturn(args[0], location);
101401                 case 9 /* Throw */:
101402                     return writeThrow(args[0], location);
101403             }
101404         }
101405         /**
101406          * Writes a statement to the current label's statement list.
101407          *
101408          * @param statement A statement to write.
101409          */
101410         function writeStatement(statement) {
101411             if (statement) {
101412                 if (!statements) {
101413                     statements = [statement];
101414                 }
101415                 else {
101416                     statements.push(statement);
101417                 }
101418             }
101419         }
101420         /**
101421          * Writes an Assign operation to the current label's statement list.
101422          *
101423          * @param left The left-hand side of the assignment.
101424          * @param right The right-hand side of the assignment.
101425          * @param operationLocation The source map location for the operation.
101426          */
101427         function writeAssign(left, right, operationLocation) {
101428             writeStatement(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation));
101429         }
101430         /**
101431          * Writes a Throw operation to the current label's statement list.
101432          *
101433          * @param expression The value to throw.
101434          * @param operationLocation The source map location for the operation.
101435          */
101436         function writeThrow(expression, operationLocation) {
101437             lastOperationWasAbrupt = true;
101438             lastOperationWasCompletion = true;
101439             writeStatement(ts.setTextRange(factory.createThrowStatement(expression), operationLocation));
101440         }
101441         /**
101442          * Writes a Return operation to the current label's statement list.
101443          *
101444          * @param expression The value to return.
101445          * @param operationLocation The source map location for the operation.
101446          */
101447         function writeReturn(expression, operationLocation) {
101448             lastOperationWasAbrupt = true;
101449             lastOperationWasCompletion = true;
101450             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
101451                 ? [createInstruction(2 /* Return */), expression]
101452                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
101453         }
101454         /**
101455          * Writes a Break operation to the current label's statement list.
101456          *
101457          * @param label The label for the Break.
101458          * @param operationLocation The source map location for the operation.
101459          */
101460         function writeBreak(label, operationLocation) {
101461             lastOperationWasAbrupt = true;
101462             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
101463                 createInstruction(3 /* Break */),
101464                 createLabel(label)
101465             ])), operationLocation), 384 /* NoTokenSourceMaps */));
101466         }
101467         /**
101468          * Writes a BreakWhenTrue operation to the current label's statement list.
101469          *
101470          * @param label The label for the Break.
101471          * @param condition The condition for the Break.
101472          * @param operationLocation The source map location for the operation.
101473          */
101474         function writeBreakWhenTrue(label, condition, operationLocation) {
101475             writeStatement(ts.setEmitFlags(factory.createIfStatement(condition, ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
101476                 createInstruction(3 /* Break */),
101477                 createLabel(label)
101478             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
101479         }
101480         /**
101481          * Writes a BreakWhenFalse operation to the current label's statement list.
101482          *
101483          * @param label The label for the Break.
101484          * @param condition The condition for the Break.
101485          * @param operationLocation The source map location for the operation.
101486          */
101487         function writeBreakWhenFalse(label, condition, operationLocation) {
101488             writeStatement(ts.setEmitFlags(factory.createIfStatement(factory.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
101489                 createInstruction(3 /* Break */),
101490                 createLabel(label)
101491             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
101492         }
101493         /**
101494          * Writes a Yield operation to the current label's statement list.
101495          *
101496          * @param expression The expression to yield.
101497          * @param operationLocation The source map location for the operation.
101498          */
101499         function writeYield(expression, operationLocation) {
101500             lastOperationWasAbrupt = true;
101501             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
101502                 ? [createInstruction(4 /* Yield */), expression]
101503                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
101504         }
101505         /**
101506          * Writes a YieldStar instruction to the current label's statement list.
101507          *
101508          * @param expression The expression to yield.
101509          * @param operationLocation The source map location for the operation.
101510          */
101511         function writeYieldStar(expression, operationLocation) {
101512             lastOperationWasAbrupt = true;
101513             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
101514                 createInstruction(5 /* YieldStar */),
101515                 expression
101516             ])), operationLocation), 384 /* NoTokenSourceMaps */));
101517         }
101518         /**
101519          * Writes an Endfinally instruction to the current label's statement list.
101520          */
101521         function writeEndfinally() {
101522             lastOperationWasAbrupt = true;
101523             writeStatement(factory.createReturnStatement(factory.createArrayLiteralExpression([
101524                 createInstruction(7 /* Endfinally */)
101525             ])));
101526         }
101527     }
101528     ts.transformGenerators = transformGenerators;
101529 })(ts || (ts = {}));
101530 /*@internal*/
101531 var ts;
101532 (function (ts) {
101533     function transformModule(context) {
101534         function getTransformModuleDelegate(moduleKind) {
101535             switch (moduleKind) {
101536                 case ts.ModuleKind.AMD: return transformAMDModule;
101537                 case ts.ModuleKind.UMD: return transformUMDModule;
101538                 default: return transformCommonJSModule;
101539             }
101540         }
101541         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
101542         var compilerOptions = context.getCompilerOptions();
101543         var resolver = context.getEmitResolver();
101544         var host = context.getEmitHost();
101545         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
101546         var moduleKind = ts.getEmitModuleKind(compilerOptions);
101547         var previousOnSubstituteNode = context.onSubstituteNode;
101548         var previousOnEmitNode = context.onEmitNode;
101549         context.onSubstituteNode = onSubstituteNode;
101550         context.onEmitNode = onEmitNode;
101551         context.enableSubstitution(207 /* CallExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
101552         context.enableSubstitution(209 /* TaggedTemplateExpression */); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
101553         context.enableSubstitution(79 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
101554         context.enableSubstitution(220 /* BinaryExpression */); // Substitutes assignments to exported symbols.
101555         context.enableSubstitution(295 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
101556         context.enableEmitNotification(303 /* SourceFile */); // Restore state when substituting nodes in a file.
101557         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
101558         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
101559         var currentSourceFile; // The current file.
101560         var currentModuleInfo; // The ExternalModuleInfo for the current file.
101561         var noSubstitution = []; // Set of nodes for which substitution rules should be ignored.
101562         var needUMDDynamicImportHelper;
101563         return ts.chainBundle(context, transformSourceFile);
101564         /**
101565          * Transforms the module aspects of a SourceFile.
101566          *
101567          * @param node The SourceFile node.
101568          */
101569         function transformSourceFile(node) {
101570             if (node.isDeclarationFile ||
101571                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
101572                     node.transformFlags & 4194304 /* ContainsDynamicImport */ ||
101573                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) {
101574                 return node;
101575             }
101576             currentSourceFile = node;
101577             currentModuleInfo = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
101578             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
101579             // Perform the transformation.
101580             var transformModule = getTransformModuleDelegate(moduleKind);
101581             var updated = transformModule(node);
101582             currentSourceFile = undefined;
101583             currentModuleInfo = undefined;
101584             needUMDDynamicImportHelper = false;
101585             return updated;
101586         }
101587         function shouldEmitUnderscoreUnderscoreESModule() {
101588             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
101589                 return true;
101590             }
101591             return false;
101592         }
101593         /**
101594          * Transforms a SourceFile into a CommonJS module.
101595          *
101596          * @param node The SourceFile node.
101597          */
101598         function transformCommonJSModule(node) {
101599             startLexicalEnvironment();
101600             var statements = [];
101601             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
101602             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !ts.isJsonSourceFile(node), topLevelVisitor);
101603             if (shouldEmitUnderscoreUnderscoreESModule()) {
101604                 ts.append(statements, createUnderscoreUnderscoreESModule());
101605             }
101606             if (ts.length(currentModuleInfo.exportedNames)) {
101607                 var chunkSize = 50;
101608                 for (var i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) {
101609                     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())));
101610                 }
101611             }
101612             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, ts.isStatement));
101613             ts.addRange(statements, ts.visitNodes(node.statements, topLevelVisitor, ts.isStatement, statementOffset));
101614             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
101615             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
101616             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
101617             ts.addEmitHelpers(updated, context.readEmitHelpers());
101618             return updated;
101619         }
101620         /**
101621          * Transforms a SourceFile into an AMD module.
101622          *
101623          * @param node The SourceFile node.
101624          */
101625         function transformAMDModule(node) {
101626             var define = factory.createIdentifier("define");
101627             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
101628             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
101629             // An AMD define function has the following shape:
101630             //
101631             //     define(id?, dependencies?, factory);
101632             //
101633             // This has the shape of the following:
101634             //
101635             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
101636             //
101637             // The location of the alias in the parameter list in the factory function needs to
101638             // match the position of the module name in the dependency list.
101639             //
101640             // To ensure this is true in cases of modules with no aliases, e.g.:
101641             //
101642             //     import "module"
101643             //
101644             // or
101645             //
101646             //     /// <amd-dependency path= "a.css" />
101647             //
101648             // we need to add modules without alias names to the end of the dependencies list
101649             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
101650             // Create an updated SourceFile:
101651             //
101652             //     define(mofactory.updateSourceFile", "module2"], function ...
101653             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
101654                 factory.createExpressionStatement(factory.createCallExpression(define, 
101655                 /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : []), true), [
101656                     // Add the dependency array argument:
101657                     //
101658                     //     ["require", "exports", module1", "module2", ...]
101659                     factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArray(__spreadArray([
101660                         factory.createStringLiteral("require"),
101661                         factory.createStringLiteral("exports")
101662                     ], aliasedModuleNames, true), unaliasedModuleNames, true)),
101663                     // Add the module body function argument:
101664                     //
101665                     //     function (require, exports, module1, module2) ...
101666                     jsonSourceFile ?
101667                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
101668                         factory.createFunctionExpression(
101669                         /*modifiers*/ undefined, 
101670                         /*asteriskToken*/ undefined, 
101671                         /*name*/ undefined, 
101672                         /*typeParameters*/ undefined, __spreadArray([
101673                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
101674                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
101675                         ], importAliasNames, true), 
101676                         /*type*/ undefined, transformAsynchronousModuleBody(node))
101677                 ], false)))
101678             ]), 
101679             /*location*/ node.statements));
101680             ts.addEmitHelpers(updated, context.readEmitHelpers());
101681             return updated;
101682         }
101683         /**
101684          * Transforms a SourceFile into a UMD module.
101685          *
101686          * @param node The SourceFile node.
101687          */
101688         function transformUMDModule(node) {
101689             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
101690             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
101691             var umdHeader = factory.createFunctionExpression(
101692             /*modifiers*/ undefined, 
101693             /*asteriskToken*/ undefined, 
101694             /*name*/ undefined, 
101695             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
101696             /*type*/ undefined, ts.setTextRange(factory.createBlock([
101697                 factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([
101698                     factory.createVariableStatement(
101699                     /*modifiers*/ undefined, [
101700                         factory.createVariableDeclaration("v", 
101701                         /*exclamationToken*/ undefined, 
101702                         /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("factory"), 
101703                         /*typeArguments*/ undefined, [
101704                             factory.createIdentifier("require"),
101705                             factory.createIdentifier("exports")
101706                         ]))
101707                     ]),
101708                     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 */)
101709                 ]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
101710                     factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"), 
101711                     /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : []), true), [
101712                         factory.createArrayLiteralExpression(__spreadArray(__spreadArray([
101713                             factory.createStringLiteral("require"),
101714                             factory.createStringLiteral("exports")
101715                         ], aliasedModuleNames, true), unaliasedModuleNames, true)),
101716                         factory.createIdentifier("factory")
101717                     ], false)))
101718                 ])))
101719             ], 
101720             /*multiLine*/ true), 
101721             /*location*/ undefined));
101722             // Create an updated SourceFile:
101723             //
101724             //  (function (factory) {
101725             //      if (typeof module === "object" && typeof module.exports === "object") {
101726             //          var v = factory(require, exports);
101727             //          if (v !== undefined) module.exports = v;
101728             //      }
101729             //      else if (typeof define === 'function' && define.amd) {
101730             //          define(["require", "exports"], factory);
101731             //      }
101732             //  })(function ...)
101733             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
101734                 factory.createExpressionStatement(factory.createCallExpression(umdHeader, 
101735                 /*typeArguments*/ undefined, [
101736                     // Add the module body function argument:
101737                     //
101738                     //     function (require, exports) ...
101739                     factory.createFunctionExpression(
101740                     /*modifiers*/ undefined, 
101741                     /*asteriskToken*/ undefined, 
101742                     /*name*/ undefined, 
101743                     /*typeParameters*/ undefined, __spreadArray([
101744                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
101745                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
101746                     ], importAliasNames, true), 
101747                     /*type*/ undefined, transformAsynchronousModuleBody(node))
101748                 ]))
101749             ]), 
101750             /*location*/ node.statements));
101751             ts.addEmitHelpers(updated, context.readEmitHelpers());
101752             return updated;
101753         }
101754         /**
101755          * Collect the additional asynchronous dependencies for the module.
101756          *
101757          * @param node The source file.
101758          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
101759          */
101760         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
101761             // names of modules with corresponding parameter in the factory function
101762             var aliasedModuleNames = [];
101763             // names of modules with no corresponding parameters in factory function
101764             var unaliasedModuleNames = [];
101765             // names of the parameters in the factory function; these
101766             // parameters need to match the indexes of the corresponding
101767             // module names in aliasedModuleNames.
101768             var importAliasNames = [];
101769             // Fill in amd-dependency tags
101770             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
101771                 var amdDependency = _a[_i];
101772                 if (amdDependency.name) {
101773                     aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
101774                     importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
101775                 }
101776                 else {
101777                     unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
101778                 }
101779             }
101780             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
101781                 var importNode = _c[_b];
101782                 // Find the name of the external module
101783                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
101784                 // Find the name of the module alias, if there is one
101785                 var importAliasName = ts.getLocalNameForExternalImport(factory, importNode, currentSourceFile);
101786                 // It is possible that externalModuleName is undefined if it is not string literal.
101787                 // This can happen in the invalid import syntax.
101788                 // E.g : "import * from alias from 'someLib';"
101789                 if (externalModuleName) {
101790                     if (includeNonAmdDependencies && importAliasName) {
101791                         // Set emitFlags on the name of the classDeclaration
101792                         // This is so that when printer will not substitute the identifier
101793                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
101794                         aliasedModuleNames.push(externalModuleName);
101795                         importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
101796                     }
101797                     else {
101798                         unaliasedModuleNames.push(externalModuleName);
101799                     }
101800                 }
101801             }
101802             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
101803         }
101804         function getAMDImportExpressionForImport(node) {
101805             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
101806                 return undefined;
101807             }
101808             var name = ts.getLocalNameForExternalImport(factory, node, currentSourceFile); // TODO: GH#18217
101809             var expr = getHelperExpressionForImport(node, name);
101810             if (expr === name) {
101811                 return undefined;
101812             }
101813             return factory.createExpressionStatement(factory.createAssignment(name, expr));
101814         }
101815         /**
101816          * Transforms a SourceFile into an AMD or UMD module body.
101817          *
101818          * @param node The SourceFile node.
101819          */
101820         function transformAsynchronousModuleBody(node) {
101821             startLexicalEnvironment();
101822             var statements = [];
101823             var statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, topLevelVisitor);
101824             if (shouldEmitUnderscoreUnderscoreESModule()) {
101825                 ts.append(statements, createUnderscoreUnderscoreESModule());
101826             }
101827             if (ts.length(currentModuleInfo.exportedNames)) {
101828                 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())));
101829             }
101830             // Visit each statement of the module body.
101831             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, ts.isStatement));
101832             if (moduleKind === ts.ModuleKind.AMD) {
101833                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
101834             }
101835             ts.addRange(statements, ts.visitNodes(node.statements, topLevelVisitor, ts.isStatement, statementOffset));
101836             // Append the 'export =' statement if provided.
101837             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
101838             // End the lexical environment for the module body
101839             // and merge any new lexical declarations.
101840             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
101841             var body = factory.createBlock(statements, /*multiLine*/ true);
101842             if (needUMDDynamicImportHelper) {
101843                 ts.addEmitHelper(body, dynamicImportUMDHelper);
101844             }
101845             return body;
101846         }
101847         /**
101848          * Adds the down-level representation of `export=` to the statement list if one exists
101849          * in the source file.
101850          *
101851          * @param statements The Statement list to modify.
101852          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
101853          * return statement.
101854          */
101855         function addExportEqualsIfNeeded(statements, emitAsReturn) {
101856             if (currentModuleInfo.exportEquals) {
101857                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, visitor);
101858                 if (expressionResult) {
101859                     if (emitAsReturn) {
101860                         var statement = factory.createReturnStatement(expressionResult);
101861                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
101862                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
101863                         statements.push(statement);
101864                     }
101865                     else {
101866                         var statement = factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), expressionResult));
101867                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
101868                         ts.setEmitFlags(statement, 1536 /* NoComments */);
101869                         statements.push(statement);
101870                     }
101871                 }
101872             }
101873         }
101874         //
101875         // Top-Level Source Element Visitors
101876         //
101877         /**
101878          * Visits a node at the top level of the source file.
101879          *
101880          * @param node The node to visit.
101881          */
101882         function topLevelVisitor(node) {
101883             switch (node.kind) {
101884                 case 265 /* ImportDeclaration */:
101885                     return visitImportDeclaration(node);
101886                 case 264 /* ImportEqualsDeclaration */:
101887                     return visitImportEqualsDeclaration(node);
101888                 case 271 /* ExportDeclaration */:
101889                     return visitExportDeclaration(node);
101890                 case 270 /* ExportAssignment */:
101891                     return visitExportAssignment(node);
101892                 case 236 /* VariableStatement */:
101893                     return visitVariableStatement(node);
101894                 case 255 /* FunctionDeclaration */:
101895                     return visitFunctionDeclaration(node);
101896                 case 256 /* ClassDeclaration */:
101897                     return visitClassDeclaration(node);
101898                 case 350 /* MergeDeclarationMarker */:
101899                     return visitMergeDeclarationMarker(node);
101900                 case 351 /* EndOfDeclarationMarker */:
101901                     return visitEndOfDeclarationMarker(node);
101902                 default:
101903                     return visitor(node);
101904             }
101905         }
101906         function visitorWorker(node, valueIsDiscarded) {
101907             // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression
101908             // as export/import statements are only transformed at the top level of a file.
101909             if (!(node.transformFlags & (4194304 /* ContainsDynamicImport */ | 2048 /* ContainsDestructuringAssignment */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) {
101910                 return node;
101911             }
101912             switch (node.kind) {
101913                 case 241 /* ForStatement */:
101914                     return visitForStatement(node);
101915                 case 237 /* ExpressionStatement */:
101916                     return visitExpressionStatement(node);
101917                 case 211 /* ParenthesizedExpression */:
101918                     return visitParenthesizedExpression(node, valueIsDiscarded);
101919                 case 348 /* PartiallyEmittedExpression */:
101920                     return visitPartiallyEmittedExpression(node, valueIsDiscarded);
101921                 case 207 /* CallExpression */:
101922                     if (ts.isImportCall(node) && currentSourceFile.impliedNodeFormat === undefined) {
101923                         return visitImportCallExpression(node);
101924                     }
101925                     break;
101926                 case 220 /* BinaryExpression */:
101927                     if (ts.isDestructuringAssignment(node)) {
101928                         return visitDestructuringAssignment(node, valueIsDiscarded);
101929                     }
101930                     break;
101931                 case 218 /* PrefixUnaryExpression */:
101932                 case 219 /* PostfixUnaryExpression */:
101933                     return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded);
101934             }
101935             return ts.visitEachChild(node, visitor, context);
101936         }
101937         function visitor(node) {
101938             return visitorWorker(node, /*valueIsDiscarded*/ false);
101939         }
101940         function discardedValueVisitor(node) {
101941             return visitorWorker(node, /*valueIsDiscarded*/ true);
101942         }
101943         function destructuringNeedsFlattening(node) {
101944             if (ts.isObjectLiteralExpression(node)) {
101945                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
101946                     var elem = _a[_i];
101947                     switch (elem.kind) {
101948                         case 294 /* PropertyAssignment */:
101949                             if (destructuringNeedsFlattening(elem.initializer)) {
101950                                 return true;
101951                             }
101952                             break;
101953                         case 295 /* ShorthandPropertyAssignment */:
101954                             if (destructuringNeedsFlattening(elem.name)) {
101955                                 return true;
101956                             }
101957                             break;
101958                         case 296 /* SpreadAssignment */:
101959                             if (destructuringNeedsFlattening(elem.expression)) {
101960                                 return true;
101961                             }
101962                             break;
101963                         case 168 /* MethodDeclaration */:
101964                         case 171 /* GetAccessor */:
101965                         case 172 /* SetAccessor */:
101966                             return false;
101967                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
101968                     }
101969                 }
101970             }
101971             else if (ts.isArrayLiteralExpression(node)) {
101972                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
101973                     var elem = _c[_b];
101974                     if (ts.isSpreadElement(elem)) {
101975                         if (destructuringNeedsFlattening(elem.expression)) {
101976                             return true;
101977                         }
101978                     }
101979                     else if (destructuringNeedsFlattening(elem)) {
101980                         return true;
101981                     }
101982                 }
101983             }
101984             else if (ts.isIdentifier(node)) {
101985                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
101986             }
101987             return false;
101988         }
101989         function visitDestructuringAssignment(node, valueIsDiscarded) {
101990             if (destructuringNeedsFlattening(node.left)) {
101991                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !valueIsDiscarded, createAllExportExpressions);
101992             }
101993             return ts.visitEachChild(node, visitor, context);
101994         }
101995         function visitForStatement(node) {
101996             return factory.updateForStatement(node, ts.visitNode(node.initializer, discardedValueVisitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, discardedValueVisitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context));
101997         }
101998         function visitExpressionStatement(node) {
101999             return factory.updateExpressionStatement(node, ts.visitNode(node.expression, discardedValueVisitor, ts.isExpression));
102000         }
102001         function visitParenthesizedExpression(node, valueIsDiscarded) {
102002             return factory.updateParenthesizedExpression(node, ts.visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, ts.isExpression));
102003         }
102004         function visitPartiallyEmittedExpression(node, valueIsDiscarded) {
102005             return factory.updatePartiallyEmittedExpression(node, ts.visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, ts.isExpression));
102006         }
102007         function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) {
102008             // When we see a prefix or postfix increment expression whose operand is an exported
102009             // symbol, we should ensure all exports of that symbol are updated with the correct
102010             // value.
102011             //
102012             // - We do not transform generated identifiers for any reason.
102013             // - We do not transform identifiers tagged with the LocalName flag.
102014             // - We do not transform identifiers that were originally the name of an enum or
102015             //   namespace due to how they are transformed in TypeScript.
102016             // - We only transform identifiers that are exported at the top level.
102017             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
102018                 && ts.isIdentifier(node.operand)
102019                 && !ts.isGeneratedIdentifier(node.operand)
102020                 && !ts.isLocalName(node.operand)
102021                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
102022                 var exportedNames = getExports(node.operand);
102023                 if (exportedNames) {
102024                     var temp = void 0;
102025                     var expression = ts.visitNode(node.operand, visitor, ts.isExpression);
102026                     if (ts.isPrefixUnaryExpression(node)) {
102027                         expression = factory.updatePrefixUnaryExpression(node, expression);
102028                     }
102029                     else {
102030                         expression = factory.updatePostfixUnaryExpression(node, expression);
102031                         if (!valueIsDiscarded) {
102032                             temp = factory.createTempVariable(hoistVariableDeclaration);
102033                             expression = factory.createAssignment(temp, expression);
102034                             ts.setTextRange(expression, node);
102035                         }
102036                         expression = factory.createComma(expression, factory.cloneNode(node.operand));
102037                         ts.setTextRange(expression, node);
102038                     }
102039                     for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
102040                         var exportName = exportedNames_1[_i];
102041                         noSubstitution[ts.getNodeId(expression)] = true;
102042                         expression = createExportExpression(exportName, expression);
102043                         ts.setTextRange(expression, node);
102044                     }
102045                     if (temp) {
102046                         noSubstitution[ts.getNodeId(expression)] = true;
102047                         expression = factory.createComma(expression, temp);
102048                         ts.setTextRange(expression, node);
102049                     }
102050                     return expression;
102051                 }
102052             }
102053             return ts.visitEachChild(node, visitor, context);
102054         }
102055         function visitImportCallExpression(node) {
102056             var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
102057             var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor);
102058             // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
102059             var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
102060             var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
102061             switch (compilerOptions.module) {
102062                 case ts.ModuleKind.AMD:
102063                     return createImportCallExpressionAMD(argument, containsLexicalThis);
102064                 case ts.ModuleKind.UMD:
102065                     return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis);
102066                 case ts.ModuleKind.CommonJS:
102067                 default:
102068                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
102069             }
102070         }
102071         function createImportCallExpressionUMD(arg, containsLexicalThis) {
102072             // (function (factory) {
102073             //      ... (regular UMD)
102074             // }
102075             // })(function (require, exports, useSyncRequire) {
102076             //      "use strict";
102077             //      Object.defineProperty(exports, "__esModule", { value: true });
102078             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
102079             //      var __resolved = new Promise(function (resolve) { resolve(); });
102080             //      .....
102081             //      __syncRequire
102082             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
102083             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
102084             // });
102085             needUMDDynamicImportHelper = true;
102086             if (ts.isSimpleCopiableExpression(arg)) {
102087                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536 /* NoComments */);
102088                 return factory.createConditionalExpression(
102089                 /*condition*/ factory.createIdentifier("__syncRequire"), 
102090                 /*questionToken*/ undefined, 
102091                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
102092                 /*colonToken*/ undefined, 
102093                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
102094             }
102095             else {
102096                 var temp = factory.createTempVariable(hoistVariableDeclaration);
102097                 return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
102098                 /*condition*/ factory.createIdentifier("__syncRequire"), 
102099                 /*questionToken*/ undefined, 
102100                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
102101                 /*colonToken*/ undefined, 
102102                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
102103             }
102104         }
102105         function createImportCallExpressionAMD(arg, containsLexicalThis) {
102106             // improt("./blah")
102107             // emit as
102108             // define(["require", "exports", "blah"], function (require, exports) {
102109             //     ...
102110             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
102111             // });
102112             var resolve = factory.createUniqueName("resolve");
102113             var reject = factory.createUniqueName("reject");
102114             var parameters = [
102115                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
102116                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
102117             ];
102118             var body = factory.createBlock([
102119                 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), 
102120                 /*typeArguments*/ undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]))
102121             ]);
102122             var func;
102123             if (languageVersion >= 2 /* ES2015 */) {
102124                 func = factory.createArrowFunction(
102125                 /*modifiers*/ undefined, 
102126                 /*typeParameters*/ undefined, parameters, 
102127                 /*type*/ undefined, 
102128                 /*equalsGreaterThanToken*/ undefined, body);
102129             }
102130             else {
102131                 func = factory.createFunctionExpression(
102132                 /*modifiers*/ undefined, 
102133                 /*asteriskToken*/ undefined, 
102134                 /*name*/ undefined, 
102135                 /*typeParameters*/ undefined, parameters, 
102136                 /*type*/ undefined, body);
102137                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
102138                 // that this new function expression indicates it captures 'this' so that the
102139                 // es2015 transformer will properly substitute 'this' with '_this'.
102140                 if (containsLexicalThis) {
102141                     ts.setEmitFlags(func, 8 /* CapturesThis */);
102142                 }
102143             }
102144             var promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
102145             if (ts.getESModuleInterop(compilerOptions)) {
102146                 return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
102147             }
102148             return promise;
102149         }
102150         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
102151             // import("./blah")
102152             // emit as
102153             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
102154             // We have to wrap require in then callback so that require is done in asynchronously
102155             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
102156             var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
102157             var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
102158             if (ts.getESModuleInterop(compilerOptions)) {
102159                 requireCall = emitHelpers().createImportStarHelper(requireCall);
102160             }
102161             var func;
102162             if (languageVersion >= 2 /* ES2015 */) {
102163                 func = factory.createArrowFunction(
102164                 /*modifiers*/ undefined, 
102165                 /*typeParameters*/ undefined, 
102166                 /*parameters*/ [], 
102167                 /*type*/ undefined, 
102168                 /*equalsGreaterThanToken*/ undefined, requireCall);
102169             }
102170             else {
102171                 func = factory.createFunctionExpression(
102172                 /*modifiers*/ undefined, 
102173                 /*asteriskToken*/ undefined, 
102174                 /*name*/ undefined, 
102175                 /*typeParameters*/ undefined, 
102176                 /*parameters*/ [], 
102177                 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]));
102178                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
102179                 // that this new function expression indicates it captures 'this' so that the
102180                 // es2015 transformer will properly substitute 'this' with '_this'.
102181                 if (containsLexicalThis) {
102182                     ts.setEmitFlags(func, 8 /* CapturesThis */);
102183                 }
102184             }
102185             return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
102186         }
102187         function getHelperExpressionForExport(node, innerExpr) {
102188             if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
102189                 return innerExpr;
102190             }
102191             if (ts.getExportNeedsImportStarHelper(node)) {
102192                 return emitHelpers().createImportStarHelper(innerExpr);
102193             }
102194             return innerExpr;
102195         }
102196         function getHelperExpressionForImport(node, innerExpr) {
102197             if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
102198                 return innerExpr;
102199             }
102200             if (ts.getImportNeedsImportStarHelper(node)) {
102201                 return emitHelpers().createImportStarHelper(innerExpr);
102202             }
102203             if (ts.getImportNeedsImportDefaultHelper(node)) {
102204                 return emitHelpers().createImportDefaultHelper(innerExpr);
102205             }
102206             return innerExpr;
102207         }
102208         /**
102209          * Visits an ImportDeclaration node.
102210          *
102211          * @param node The node to visit.
102212          */
102213         function visitImportDeclaration(node) {
102214             var statements;
102215             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
102216             if (moduleKind !== ts.ModuleKind.AMD) {
102217                 if (!node.importClause) {
102218                     // import "mod";
102219                     return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
102220                 }
102221                 else {
102222                     var variables = [];
102223                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
102224                         // import * as n from "mod";
102225                         variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
102226                         /*exclamationToken*/ undefined, 
102227                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
102228                     }
102229                     else {
102230                         // import d from "mod";
102231                         // import { x, y } from "mod";
102232                         // import d, { x, y } from "mod";
102233                         // import d, * as n from "mod";
102234                         variables.push(factory.createVariableDeclaration(factory.getGeneratedNameForNode(node), 
102235                         /*exclamationToken*/ undefined, 
102236                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
102237                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
102238                             variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
102239                             /*exclamationToken*/ undefined, 
102240                             /*type*/ undefined, factory.getGeneratedNameForNode(node)));
102241                         }
102242                     }
102243                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
102244                     /*modifiers*/ undefined, factory.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
102245                     /*location*/ node), 
102246                     /*original*/ node));
102247                 }
102248             }
102249             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
102250                 // import d, * as n from "mod";
102251                 statements = ts.append(statements, factory.createVariableStatement(
102252                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
102253                     ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
102254                     /*exclamationToken*/ undefined, 
102255                     /*type*/ undefined, factory.getGeneratedNameForNode(node)), 
102256                     /*location*/ node), 
102257                     /*original*/ node)
102258                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
102259             }
102260             if (hasAssociatedEndOfDeclarationMarker(node)) {
102261                 // Defer exports until we encounter an EndOfDeclarationMarker node
102262                 var id = ts.getOriginalNodeId(node);
102263                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
102264             }
102265             else {
102266                 statements = appendExportsOfImportDeclaration(statements, node);
102267             }
102268             return ts.singleOrMany(statements);
102269         }
102270         /**
102271          * Creates a `require()` call to import an external module.
102272          *
102273          * @param importNode The declararation to import.
102274          */
102275         function createRequireCall(importNode) {
102276             var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
102277             var args = [];
102278             if (moduleName) {
102279                 args.push(moduleName);
102280             }
102281             return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, args);
102282         }
102283         /**
102284          * Visits an ImportEqualsDeclaration node.
102285          *
102286          * @param node The node to visit.
102287          */
102288         function visitImportEqualsDeclaration(node) {
102289             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
102290             var statements;
102291             if (moduleKind !== ts.ModuleKind.AMD) {
102292                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
102293                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
102294                 }
102295                 else {
102296                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
102297                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
102298                         factory.createVariableDeclaration(factory.cloneNode(node.name), 
102299                         /*exclamationToken*/ undefined, 
102300                         /*type*/ undefined, createRequireCall(node))
102301                     ], 
102302                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
102303                 }
102304             }
102305             else {
102306                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
102307                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(node), factory.getLocalName(node))), node), node));
102308                 }
102309             }
102310             if (hasAssociatedEndOfDeclarationMarker(node)) {
102311                 // Defer exports until we encounter an EndOfDeclarationMarker node
102312                 var id = ts.getOriginalNodeId(node);
102313                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
102314             }
102315             else {
102316                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
102317             }
102318             return ts.singleOrMany(statements);
102319         }
102320         /**
102321          * Visits an ExportDeclaration node.
102322          *
102323          * @param The node to visit.
102324          */
102325         function visitExportDeclaration(node) {
102326             if (!node.moduleSpecifier) {
102327                 // Elide export declarations with no module specifier as they are handled
102328                 // elsewhere.
102329                 return undefined;
102330             }
102331             var generatedName = factory.getGeneratedNameForNode(node);
102332             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
102333                 var statements = [];
102334                 // export { x, y } from "mod";
102335                 if (moduleKind !== ts.ModuleKind.AMD) {
102336                     statements.push(ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
102337                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
102338                         factory.createVariableDeclaration(generatedName, 
102339                         /*exclamationToken*/ undefined, 
102340                         /*type*/ undefined, createRequireCall(node))
102341                     ])), 
102342                     /*location*/ node), 
102343                     /* original */ node));
102344                 }
102345                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
102346                     var specifier = _a[_i];
102347                     if (languageVersion === 0 /* ES3 */) {
102348                         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));
102349                     }
102350                     else {
102351                         var exportNeedsImportDefault = !!ts.getESModuleInterop(compilerOptions) &&
102352                             !(ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) &&
102353                             ts.idText(specifier.propertyName || specifier.name) === "default";
102354                         var exportedValue = factory.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name);
102355                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
102356                     }
102357                 }
102358                 return ts.singleOrMany(statements);
102359             }
102360             else if (node.exportClause) {
102361                 var statements = [];
102362                 // export * as ns from "mod";
102363                 // export * as default from "mod";
102364                 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== ts.ModuleKind.AMD ?
102365                     createRequireCall(node) :
102366                     ts.isExportNamespaceAsDefaultDeclaration(node) ? generatedName :
102367                         factory.createIdentifier(ts.idText(node.exportClause.name))))), node), node));
102368                 return ts.singleOrMany(statements);
102369             }
102370             else {
102371                 // export * from "mod";
102372                 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
102373             }
102374         }
102375         /**
102376          * Visits an ExportAssignment node.
102377          *
102378          * @param node The node to visit.
102379          */
102380         function visitExportAssignment(node) {
102381             if (node.isExportEquals) {
102382                 return undefined;
102383             }
102384             var statements;
102385             var original = node.original;
102386             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
102387                 // Defer exports until we encounter an EndOfDeclarationMarker node
102388                 var id = ts.getOriginalNodeId(node);
102389                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), ts.visitNode(node.expression, visitor), /*location*/ node, /*allowComments*/ true);
102390             }
102391             else {
102392                 statements = appendExportStatement(statements, factory.createIdentifier("default"), ts.visitNode(node.expression, visitor), /*location*/ node, /*allowComments*/ true);
102393             }
102394             return ts.singleOrMany(statements);
102395         }
102396         /**
102397          * Visits a FunctionDeclaration node.
102398          *
102399          * @param node The node to visit.
102400          */
102401         function visitFunctionDeclaration(node) {
102402             var statements;
102403             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
102404                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
102405                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
102406                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), 
102407                 /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), 
102408                 /*location*/ node), 
102409                 /*original*/ node));
102410             }
102411             else {
102412                 statements = ts.append(statements, ts.visitEachChild(node, visitor, context));
102413             }
102414             if (hasAssociatedEndOfDeclarationMarker(node)) {
102415                 // Defer exports until we encounter an EndOfDeclarationMarker node
102416                 var id = ts.getOriginalNodeId(node);
102417                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
102418             }
102419             else {
102420                 statements = appendExportsOfHoistedDeclaration(statements, node);
102421             }
102422             return ts.singleOrMany(statements);
102423         }
102424         /**
102425          * Visits a ClassDeclaration node.
102426          *
102427          * @param node The node to visit.
102428          */
102429         function visitClassDeclaration(node) {
102430             var statements;
102431             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
102432                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(
102433                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
102434                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node));
102435             }
102436             else {
102437                 statements = ts.append(statements, ts.visitEachChild(node, visitor, context));
102438             }
102439             if (hasAssociatedEndOfDeclarationMarker(node)) {
102440                 // Defer exports until we encounter an EndOfDeclarationMarker node
102441                 var id = ts.getOriginalNodeId(node);
102442                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
102443             }
102444             else {
102445                 statements = appendExportsOfHoistedDeclaration(statements, node);
102446             }
102447             return ts.singleOrMany(statements);
102448         }
102449         /**
102450          * Visits a VariableStatement node.
102451          *
102452          * @param node The node to visit.
102453          */
102454         function visitVariableStatement(node) {
102455             var statements;
102456             var variables;
102457             var expressions;
102458             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
102459                 var modifiers = void 0;
102460                 var removeCommentsOnExpressions = false;
102461                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
102462                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
102463                     var variable = _a[_i];
102464                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
102465                         if (!modifiers) {
102466                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
102467                         }
102468                         variables = ts.append(variables, variable);
102469                     }
102470                     else if (variable.initializer) {
102471                         if (!ts.isBindingPattern(variable.name) && (ts.isArrowFunction(variable.initializer) || ts.isFunctionExpression(variable.initializer) || ts.isClassExpression(variable.initializer))) {
102472                             var expression = factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), variable.name), 
102473                             /*location*/ variable.name), factory.createIdentifier(ts.getTextOfIdentifierOrLiteral(variable.name)));
102474                             var updatedVariable = factory.createVariableDeclaration(variable.name, variable.exclamationToken, variable.type, ts.visitNode(variable.initializer, visitor));
102475                             variables = ts.append(variables, updatedVariable);
102476                             expressions = ts.append(expressions, expression);
102477                             removeCommentsOnExpressions = true;
102478                         }
102479                         else {
102480                             expressions = ts.append(expressions, transformInitializedVariable(variable));
102481                         }
102482                     }
102483                 }
102484                 if (variables) {
102485                     statements = ts.append(statements, factory.updateVariableStatement(node, modifiers, factory.updateVariableDeclarationList(node.declarationList, variables)));
102486                 }
102487                 if (expressions) {
102488                     var statement = ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node);
102489                     if (removeCommentsOnExpressions) {
102490                         ts.removeAllComments(statement);
102491                     }
102492                     statements = ts.append(statements, statement);
102493                 }
102494             }
102495             else {
102496                 statements = ts.append(statements, ts.visitEachChild(node, visitor, context));
102497             }
102498             if (hasAssociatedEndOfDeclarationMarker(node)) {
102499                 // Defer exports until we encounter an EndOfDeclarationMarker node
102500                 var id = ts.getOriginalNodeId(node);
102501                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
102502             }
102503             else {
102504                 statements = appendExportsOfVariableStatement(statements, node);
102505             }
102506             return ts.singleOrMany(statements);
102507         }
102508         function createAllExportExpressions(name, value, location) {
102509             var exportedNames = getExports(name);
102510             if (exportedNames) {
102511                 // For each additional export of the declaration, apply an export assignment.
102512                 var expression = ts.isExportName(name) ? value : factory.createAssignment(name, value);
102513                 for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
102514                     var exportName = exportedNames_2[_i];
102515                     // Mark the node to prevent triggering substitution.
102516                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
102517                     expression = createExportExpression(exportName, expression, /*location*/ location);
102518                 }
102519                 return expression;
102520             }
102521             return factory.createAssignment(name, value);
102522         }
102523         /**
102524          * Transforms an exported variable with an initializer into an expression.
102525          *
102526          * @param node The node to transform.
102527          */
102528         function transformInitializedVariable(node) {
102529             if (ts.isBindingPattern(node.name)) {
102530                 return ts.flattenDestructuringAssignment(ts.visitNode(node, visitor), 
102531                 /*visitor*/ undefined, context, 0 /* All */, 
102532                 /*needsValue*/ false, createAllExportExpressions);
102533             }
102534             else {
102535                 return factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), node.name), 
102536                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, visitor) : factory.createVoidZero());
102537             }
102538         }
102539         /**
102540          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
102541          * and transformed declaration.
102542          *
102543          * @param node The node to visit.
102544          */
102545         function visitMergeDeclarationMarker(node) {
102546             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
102547             // declaration we do not emit a leading variable declaration. To preserve the
102548             // begin/end semantics of the declararation and to properly handle exports
102549             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
102550             //
102551             // To balance the declaration, add the exports of the elided variable
102552             // statement.
102553             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 236 /* VariableStatement */) {
102554                 var id = ts.getOriginalNodeId(node);
102555                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
102556             }
102557             return node;
102558         }
102559         /**
102560          * Determines whether a node has an associated EndOfDeclarationMarker.
102561          *
102562          * @param node The node to test.
102563          */
102564         function hasAssociatedEndOfDeclarationMarker(node) {
102565             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
102566         }
102567         /**
102568          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
102569          * declaration.
102570          *
102571          * @param node The node to visit.
102572          */
102573         function visitEndOfDeclarationMarker(node) {
102574             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
102575             // end of the transformed declaration. We use this marker to emit any deferred exports
102576             // of the declaration.
102577             var id = ts.getOriginalNodeId(node);
102578             var statements = deferredExports[id];
102579             if (statements) {
102580                 delete deferredExports[id];
102581                 return ts.append(statements, node);
102582             }
102583             return node;
102584         }
102585         /**
102586          * Appends the exports of an ImportDeclaration to a statement list, returning the
102587          * statement list.
102588          *
102589          * @param statements A statement list to which the down-level export statements are to be
102590          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102591          * appended.
102592          * @param decl The declaration whose exports are to be recorded.
102593          */
102594         function appendExportsOfImportDeclaration(statements, decl) {
102595             if (currentModuleInfo.exportEquals) {
102596                 return statements;
102597             }
102598             var importClause = decl.importClause;
102599             if (!importClause) {
102600                 return statements;
102601             }
102602             if (importClause.name) {
102603                 statements = appendExportsOfDeclaration(statements, importClause);
102604             }
102605             var namedBindings = importClause.namedBindings;
102606             if (namedBindings) {
102607                 switch (namedBindings.kind) {
102608                     case 267 /* NamespaceImport */:
102609                         statements = appendExportsOfDeclaration(statements, namedBindings);
102610                         break;
102611                     case 268 /* NamedImports */:
102612                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
102613                             var importBinding = _a[_i];
102614                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
102615                         }
102616                         break;
102617                 }
102618             }
102619             return statements;
102620         }
102621         /**
102622          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
102623          * statement list.
102624          *
102625          * @param statements A statement list to which the down-level export statements are to be
102626          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102627          * appended.
102628          * @param decl The declaration whose exports are to be recorded.
102629          */
102630         function appendExportsOfImportEqualsDeclaration(statements, decl) {
102631             if (currentModuleInfo.exportEquals) {
102632                 return statements;
102633             }
102634             return appendExportsOfDeclaration(statements, decl);
102635         }
102636         /**
102637          * Appends the exports of a VariableStatement to a statement list, returning the statement
102638          * list.
102639          *
102640          * @param statements A statement list to which the down-level export statements are to be
102641          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102642          * appended.
102643          * @param node The VariableStatement whose exports are to be recorded.
102644          */
102645         function appendExportsOfVariableStatement(statements, node) {
102646             if (currentModuleInfo.exportEquals) {
102647                 return statements;
102648             }
102649             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
102650                 var decl = _a[_i];
102651                 statements = appendExportsOfBindingElement(statements, decl);
102652             }
102653             return statements;
102654         }
102655         /**
102656          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
102657          * returning the statement list.
102658          *
102659          * @param statements A statement list to which the down-level export statements are to be
102660          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102661          * appended.
102662          * @param decl The declaration whose exports are to be recorded.
102663          */
102664         function appendExportsOfBindingElement(statements, decl) {
102665             if (currentModuleInfo.exportEquals) {
102666                 return statements;
102667             }
102668             if (ts.isBindingPattern(decl.name)) {
102669                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
102670                     var element = _a[_i];
102671                     if (!ts.isOmittedExpression(element)) {
102672                         statements = appendExportsOfBindingElement(statements, element);
102673                     }
102674                 }
102675             }
102676             else if (!ts.isGeneratedIdentifier(decl.name)) {
102677                 statements = appendExportsOfDeclaration(statements, decl);
102678             }
102679             return statements;
102680         }
102681         /**
102682          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
102683          * returning the statement list.
102684          *
102685          * @param statements A statement list to which the down-level export statements are to be
102686          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102687          * appended.
102688          * @param decl The declaration whose exports are to be recorded.
102689          */
102690         function appendExportsOfHoistedDeclaration(statements, decl) {
102691             if (currentModuleInfo.exportEquals) {
102692                 return statements;
102693             }
102694             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
102695                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl);
102696                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl);
102697             }
102698             if (decl.name) {
102699                 statements = appendExportsOfDeclaration(statements, decl);
102700             }
102701             return statements;
102702         }
102703         /**
102704          * Appends the exports of a declaration to a statement list, returning the statement list.
102705          *
102706          * @param statements A statement list to which the down-level export statements are to be
102707          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102708          * appended.
102709          * @param decl The declaration to export.
102710          */
102711         function appendExportsOfDeclaration(statements, decl, liveBinding) {
102712             var name = factory.getDeclarationName(decl);
102713             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
102714             if (exportSpecifiers) {
102715                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
102716                     var exportSpecifier = exportSpecifiers_1[_i];
102717                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
102718                 }
102719             }
102720             return statements;
102721         }
102722         /**
102723          * Appends the down-level representation of an export to a statement list, returning the
102724          * statement list.
102725          *
102726          * @param statements A statement list to which the down-level export statements are to be
102727          * appended. If `statements` is `undefined`, a new array is allocated if statements are
102728          * appended.
102729          * @param exportName The name of the export.
102730          * @param expression The expression to export.
102731          * @param location The location to use for source maps and comments for the export.
102732          * @param allowComments Whether to allow comments on the export.
102733          */
102734         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
102735             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
102736             return statements;
102737         }
102738         function createUnderscoreUnderscoreESModule() {
102739             var statement;
102740             if (languageVersion === 0 /* ES3 */) {
102741                 statement = factory.createExpressionStatement(createExportExpression(factory.createIdentifier("__esModule"), factory.createTrue()));
102742             }
102743             else {
102744                 statement = factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
102745                 /*typeArguments*/ undefined, [
102746                     factory.createIdentifier("exports"),
102747                     factory.createStringLiteral("__esModule"),
102748                     factory.createObjectLiteralExpression([
102749                         factory.createPropertyAssignment("value", factory.createTrue())
102750                     ])
102751                 ]));
102752             }
102753             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
102754             return statement;
102755         }
102756         /**
102757          * Creates a call to the current file's export function to export a value.
102758          *
102759          * @param name The bound name of the export.
102760          * @param value The exported value.
102761          * @param location The location to use for source maps and comments for the export.
102762          * @param allowComments An optional value indicating whether to emit comments for the statement.
102763          */
102764         function createExportStatement(name, value, location, allowComments, liveBinding) {
102765             var statement = ts.setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
102766             ts.startOnNewLine(statement);
102767             if (!allowComments) {
102768                 ts.setEmitFlags(statement, 1536 /* NoComments */);
102769             }
102770             return statement;
102771         }
102772         /**
102773          * Creates a call to the current file's export function to export a value.
102774          *
102775          * @param name The bound name of the export.
102776          * @param value The exported value.
102777          * @param location The location to use for source maps and comments for the export.
102778          */
102779         function createExportExpression(name, value, location, liveBinding) {
102780             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
102781             /*typeArguments*/ undefined, [
102782                 factory.createIdentifier("exports"),
102783                 factory.createStringLiteralFromNode(name),
102784                 factory.createObjectLiteralExpression([
102785                     factory.createPropertyAssignment("enumerable", factory.createTrue()),
102786                     factory.createPropertyAssignment("get", factory.createFunctionExpression(
102787                     /*modifiers*/ undefined, 
102788                     /*asteriskToken*/ undefined, 
102789                     /*name*/ undefined, 
102790                     /*typeParameters*/ undefined, 
102791                     /*parameters*/ [], 
102792                     /*type*/ undefined, factory.createBlock([factory.createReturnStatement(value)])))
102793                 ])
102794             ]) : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(name)), value), location);
102795         }
102796         //
102797         // Modifier Visitors
102798         //
102799         /**
102800          * Visit nodes to elide module-specific modifiers.
102801          *
102802          * @param node The node to visit.
102803          */
102804         function modifierVisitor(node) {
102805             // Elide module-specific modifiers.
102806             switch (node.kind) {
102807                 case 93 /* ExportKeyword */:
102808                 case 88 /* DefaultKeyword */:
102809                     return undefined;
102810             }
102811             return node;
102812         }
102813         //
102814         // Emit Notification
102815         //
102816         /**
102817          * Hook for node emit notifications.
102818          *
102819          * @param hint A hint as to the intended usage of the node.
102820          * @param node The node to emit.
102821          * @param emit A callback used to emit the node in the printer.
102822          */
102823         function onEmitNode(hint, node, emitCallback) {
102824             if (node.kind === 303 /* SourceFile */) {
102825                 currentSourceFile = node;
102826                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
102827                 previousOnEmitNode(hint, node, emitCallback);
102828                 currentSourceFile = undefined;
102829                 currentModuleInfo = undefined;
102830             }
102831             else {
102832                 previousOnEmitNode(hint, node, emitCallback);
102833             }
102834         }
102835         //
102836         // Substitutions
102837         //
102838         /**
102839          * Hooks node substitutions.
102840          *
102841          * @param hint A hint as to the intended usage of the node.
102842          * @param node The node to substitute.
102843          */
102844         function onSubstituteNode(hint, node) {
102845             node = previousOnSubstituteNode(hint, node);
102846             if (node.id && noSubstitution[node.id]) {
102847                 return node;
102848             }
102849             if (hint === 1 /* Expression */) {
102850                 return substituteExpression(node);
102851             }
102852             else if (ts.isShorthandPropertyAssignment(node)) {
102853                 return substituteShorthandPropertyAssignment(node);
102854             }
102855             return node;
102856         }
102857         /**
102858          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
102859          * or exported symbol.
102860          *
102861          * @param node The node to substitute.
102862          */
102863         function substituteShorthandPropertyAssignment(node) {
102864             var name = node.name;
102865             var exportedOrImportedName = substituteExpressionIdentifier(name);
102866             if (exportedOrImportedName !== name) {
102867                 // A shorthand property with an assignment initializer is probably part of a
102868                 // destructuring assignment
102869                 if (node.objectAssignmentInitializer) {
102870                     var initializer = factory.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
102871                     return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
102872                 }
102873                 return ts.setTextRange(factory.createPropertyAssignment(name, exportedOrImportedName), node);
102874             }
102875             return node;
102876         }
102877         /**
102878          * Substitution for an Expression that may contain an imported or exported symbol.
102879          *
102880          * @param node The node to substitute.
102881          */
102882         function substituteExpression(node) {
102883             switch (node.kind) {
102884                 case 79 /* Identifier */:
102885                     return substituteExpressionIdentifier(node);
102886                 case 207 /* CallExpression */:
102887                     return substituteCallExpression(node);
102888                 case 209 /* TaggedTemplateExpression */:
102889                     return substituteTaggedTemplateExpression(node);
102890                 case 220 /* BinaryExpression */:
102891                     return substituteBinaryExpression(node);
102892             }
102893             return node;
102894         }
102895         function substituteCallExpression(node) {
102896             if (ts.isIdentifier(node.expression)) {
102897                 var expression = substituteExpressionIdentifier(node.expression);
102898                 noSubstitution[ts.getNodeId(expression)] = true;
102899                 if (!ts.isIdentifier(expression)) {
102900                     return ts.addEmitFlags(factory.updateCallExpression(node, expression, 
102901                     /*typeArguments*/ undefined, node.arguments), 536870912 /* IndirectCall */);
102902                 }
102903             }
102904             return node;
102905         }
102906         function substituteTaggedTemplateExpression(node) {
102907             if (ts.isIdentifier(node.tag)) {
102908                 var tag = substituteExpressionIdentifier(node.tag);
102909                 noSubstitution[ts.getNodeId(tag)] = true;
102910                 if (!ts.isIdentifier(tag)) {
102911                     return ts.addEmitFlags(factory.updateTaggedTemplateExpression(node, tag, 
102912                     /*typeArguments*/ undefined, node.template), 536870912 /* IndirectCall */);
102913                 }
102914             }
102915             return node;
102916         }
102917         /**
102918          * Substitution for an Identifier expression that may contain an imported or exported
102919          * symbol.
102920          *
102921          * @param node The node to substitute.
102922          */
102923         function substituteExpressionIdentifier(node) {
102924             var _a, _b;
102925             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
102926                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
102927                 if (externalHelpersModuleName) {
102928                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
102929                 }
102930                 return node;
102931             }
102932             else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) {
102933                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
102934                 if (exportContainer && exportContainer.kind === 303 /* SourceFile */) {
102935                     return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), 
102936                     /*location*/ node);
102937                 }
102938                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
102939                 if (importDeclaration) {
102940                     if (ts.isImportClause(importDeclaration)) {
102941                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
102942                         /*location*/ node);
102943                     }
102944                     else if (ts.isImportSpecifier(importDeclaration)) {
102945                         var name = importDeclaration.propertyName || importDeclaration.name;
102946                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(name)), 
102947                         /*location*/ node);
102948                     }
102949                 }
102950             }
102951             return node;
102952         }
102953         /**
102954          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
102955          *
102956          * @param node The node to substitute.
102957          */
102958         function substituteBinaryExpression(node) {
102959             // When we see an assignment expression whose left-hand side is an exported symbol,
102960             // we should ensure all exports of that symbol are updated with the correct value.
102961             //
102962             // - We do not substitute generated identifiers for any reason.
102963             // - We do not substitute identifiers tagged with the LocalName flag.
102964             // - We do not substitute identifiers that were originally the name of an enum or
102965             //   namespace due to how they are transformed in TypeScript.
102966             // - We only substitute identifiers that are exported at the top level.
102967             if (ts.isAssignmentOperator(node.operatorToken.kind)
102968                 && ts.isIdentifier(node.left)
102969                 && !ts.isGeneratedIdentifier(node.left)
102970                 && !ts.isLocalName(node.left)
102971                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
102972                 var exportedNames = getExports(node.left);
102973                 if (exportedNames) {
102974                     // For each additional export of the declaration, apply an export assignment.
102975                     var expression = node;
102976                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
102977                         var exportName = exportedNames_3[_i];
102978                         // Mark the node to prevent triggering this rule again.
102979                         noSubstitution[ts.getNodeId(expression)] = true;
102980                         expression = createExportExpression(exportName, expression, /*location*/ node);
102981                     }
102982                     return expression;
102983                 }
102984             }
102985             return node;
102986         }
102987         /**
102988          * Gets the additional exports of a name.
102989          *
102990          * @param name The name.
102991          */
102992         function getExports(name) {
102993             if (!ts.isGeneratedIdentifier(name)) {
102994                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
102995                     || resolver.getReferencedValueDeclaration(name);
102996                 if (valueDeclaration) {
102997                     return currentModuleInfo
102998                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
102999                 }
103000             }
103001         }
103002     }
103003     ts.transformModule = transformModule;
103004     // emit helper for dynamic import
103005     var dynamicImportUMDHelper = {
103006         name: "typescript:dynamicimport-sync-require",
103007         scoped: true,
103008         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
103009     };
103010 })(ts || (ts = {}));
103011 /*@internal*/
103012 var ts;
103013 (function (ts) {
103014     function transformSystemModule(context) {
103015         var factory = context.factory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
103016         var compilerOptions = context.getCompilerOptions();
103017         var resolver = context.getEmitResolver();
103018         var host = context.getEmitHost();
103019         var previousOnSubstituteNode = context.onSubstituteNode;
103020         var previousOnEmitNode = context.onEmitNode;
103021         context.onSubstituteNode = onSubstituteNode;
103022         context.onEmitNode = onEmitNode;
103023         context.enableSubstitution(79 /* Identifier */); // Substitutes expression identifiers for imported symbols.
103024         context.enableSubstitution(295 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
103025         context.enableSubstitution(220 /* BinaryExpression */); // Substitutes assignments to exported symbols.
103026         context.enableSubstitution(230 /* MetaProperty */); // Substitutes 'import.meta'
103027         context.enableEmitNotification(303 /* SourceFile */); // Restore state when substituting nodes in a file.
103028         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
103029         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
103030         var exportFunctionsMap = []; // The export function associated with a source file.
103031         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
103032         var contextObjectMap = []; // The context object associated with a source file.
103033         var currentSourceFile; // The current file.
103034         var moduleInfo; // ExternalModuleInfo for the current file.
103035         var exportFunction; // The export function for the current file.
103036         var contextObject; // The context object for the current file.
103037         var hoistedStatements;
103038         var enclosingBlockScopedContainer;
103039         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
103040         return ts.chainBundle(context, transformSourceFile);
103041         /**
103042          * Transforms the module aspects of a SourceFile.
103043          *
103044          * @param node The SourceFile node.
103045          */
103046         function transformSourceFile(node) {
103047             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) {
103048                 return node;
103049             }
103050             var id = ts.getOriginalNodeId(node);
103051             currentSourceFile = node;
103052             enclosingBlockScopedContainer = node;
103053             // System modules have the following shape:
103054             //
103055             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
103056             //
103057             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
103058             // is used to publish exported values. 'exports' returns its 'value' argument so in
103059             // most cases expressions that mutate exported values can be rewritten as:
103060             //
103061             //     expr -> exports('name', expr)
103062             //
103063             // The only exception in this rule is postfix unary operators,
103064             // see comment to 'substitutePostfixUnaryExpression' for more details
103065             // Collect information about the external module and dependency groups.
103066             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
103067             // Make sure that the name of the 'exports' function does not conflict with
103068             // existing identifiers.
103069             exportFunction = factory.createUniqueName("exports");
103070             exportFunctionsMap[id] = exportFunction;
103071             contextObject = contextObjectMap[id] = factory.createUniqueName("context");
103072             // Add the body of the module.
103073             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
103074             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
103075             var moduleBodyFunction = factory.createFunctionExpression(
103076             /*modifiers*/ undefined, 
103077             /*asteriskToken*/ undefined, 
103078             /*name*/ undefined, 
103079             /*typeParameters*/ undefined, [
103080                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
103081                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
103082             ], 
103083             /*type*/ undefined, moduleBodyBlock);
103084             // Write the call to `System.register`
103085             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
103086             // So the helper will be emit at the correct position instead of at the top of the source-file
103087             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
103088             var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
103089             var updated = ts.setEmitFlags(factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
103090                 factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"), 
103091                 /*typeArguments*/ undefined, moduleName
103092                     ? [moduleName, dependencies, moduleBodyFunction]
103093                     : [dependencies, moduleBodyFunction]))
103094             ]), node.statements)), 1024 /* NoTrailingComments */);
103095             if (!ts.outFile(compilerOptions)) {
103096                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
103097             }
103098             if (noSubstitution) {
103099                 noSubstitutionMap[id] = noSubstitution;
103100                 noSubstitution = undefined;
103101             }
103102             currentSourceFile = undefined;
103103             moduleInfo = undefined;
103104             exportFunction = undefined;
103105             contextObject = undefined;
103106             hoistedStatements = undefined;
103107             enclosingBlockScopedContainer = undefined;
103108             return updated;
103109         }
103110         /**
103111          * Collects the dependency groups for this files imports.
103112          *
103113          * @param externalImports The imports for the file.
103114          */
103115         function collectDependencyGroups(externalImports) {
103116             var groupIndices = new ts.Map();
103117             var dependencyGroups = [];
103118             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
103119                 var externalImport = externalImports_1[_i];
103120                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
103121                 if (externalModuleName) {
103122                     var text = externalModuleName.text;
103123                     var groupIndex = groupIndices.get(text);
103124                     if (groupIndex !== undefined) {
103125                         // deduplicate/group entries in dependency list by the dependency name
103126                         dependencyGroups[groupIndex].externalImports.push(externalImport);
103127                     }
103128                     else {
103129                         groupIndices.set(text, dependencyGroups.length);
103130                         dependencyGroups.push({
103131                             name: externalModuleName,
103132                             externalImports: [externalImport]
103133                         });
103134                     }
103135                 }
103136             }
103137             return dependencyGroups;
103138         }
103139         /**
103140          * Adds the statements for the module body function for the source file.
103141          *
103142          * @param node The source file for the module.
103143          * @param dependencyGroups The grouped dependencies of the module.
103144          */
103145         function createSystemModuleBody(node, dependencyGroups) {
103146             // Shape of the body in system modules:
103147             //
103148             //  function (exports) {
103149             //      <list of local aliases for imports>
103150             //      <hoisted variable declarations>
103151             //      <hoisted function declarations>
103152             //      return {
103153             //          setters: [
103154             //              <list of setter function for imports>
103155             //          ],
103156             //          execute: function() {
103157             //              <module statements>
103158             //          }
103159             //      }
103160             //      <temp declarations>
103161             //  }
103162             //
103163             // i.e:
103164             //
103165             //   import {x} from 'file1'
103166             //   var y = 1;
103167             //   export function foo() { return y + x(); }
103168             //   console.log(y);
103169             //
103170             // Will be transformed to:
103171             //
103172             //  function(exports) {
103173             //      function foo() { return y + file_1.x(); }
103174             //      exports("foo", foo);
103175             //      var file_1, y;
103176             //      return {
103177             //          setters: [
103178             //              function(v) { file_1 = v }
103179             //          ],
103180             //          execute(): function() {
103181             //              y = 1;
103182             //              console.log(y);
103183             //          }
103184             //      };
103185             //  }
103186             var statements = [];
103187             // We start a new lexical environment in this function body, but *not* in the
103188             // body of the execute function. This allows us to emit temporary declarations
103189             // only in the outer module body and not in the inner one.
103190             startLexicalEnvironment();
103191             // Add any prologue directives.
103192             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
103193             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, topLevelVisitor);
103194             // var __moduleName = context_1 && context_1.id;
103195             statements.push(factory.createVariableStatement(
103196             /*modifiers*/ undefined, factory.createVariableDeclarationList([
103197                 factory.createVariableDeclaration("__moduleName", 
103198                 /*exclamationToken*/ undefined, 
103199                 /*type*/ undefined, factory.createLogicalAnd(contextObject, factory.createPropertyAccessExpression(contextObject, "id")))
103200             ])));
103201             // Visit the synthetic external helpers import declaration if present
103202             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, topLevelVisitor, ts.isStatement);
103203             // Visit the statements of the source file, emitting any transformations into
103204             // the `executeStatements` array. We do this *before* we fill the `setters` array
103205             // as we both emit transformations as well as aggregate some data used when creating
103206             // setters. This allows us to reduce the number of times we need to loop through the
103207             // statements of the source file.
103208             var executeStatements = ts.visitNodes(node.statements, topLevelVisitor, ts.isStatement, statementOffset);
103209             // Emit early exports for function declarations.
103210             ts.addRange(statements, hoistedStatements);
103211             // We emit hoisted variables early to align roughly with our previous emit output.
103212             // Two key differences in this approach are:
103213             // - Temporary variables will appear at the top rather than at the bottom of the file
103214             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
103215             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
103216             var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ?
103217                 factory.createModifiersFromModifierFlags(256 /* Async */) :
103218                 undefined;
103219             var moduleObject = factory.createObjectLiteralExpression([
103220                 factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
103221                 factory.createPropertyAssignment("execute", factory.createFunctionExpression(modifiers, 
103222                 /*asteriskToken*/ undefined, 
103223                 /*name*/ undefined, 
103224                 /*typeParameters*/ undefined, 
103225                 /*parameters*/ [], 
103226                 /*type*/ undefined, factory.createBlock(executeStatements, /*multiLine*/ true)))
103227             ], /*multiLine*/ true);
103228             statements.push(factory.createReturnStatement(moduleObject));
103229             return factory.createBlock(statements, /*multiLine*/ true);
103230         }
103231         /**
103232          * Adds an exportStar function to a statement list if it is needed for the file.
103233          *
103234          * @param statements A statement list.
103235          */
103236         function addExportStarIfNeeded(statements) {
103237             if (!moduleInfo.hasExportStarsToExportValues) {
103238                 return;
103239             }
103240             // when resolving exports local exported entries/indirect exported entries in the module
103241             // should always win over entries with similar names that were added via star exports
103242             // to support this we store names of local/indirect exported entries in a set.
103243             // this set is used to filter names brought by star expors.
103244             // local names set should only be added if we have anything exported
103245             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
103246                 // no exported declarations (export var ...) or export specifiers (export {x})
103247                 // check if we have any non star export declarations.
103248                 var hasExportDeclarationWithExportClause = false;
103249                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
103250                     var externalImport = _a[_i];
103251                     if (externalImport.kind === 271 /* ExportDeclaration */ && externalImport.exportClause) {
103252                         hasExportDeclarationWithExportClause = true;
103253                         break;
103254                     }
103255                 }
103256                 if (!hasExportDeclarationWithExportClause) {
103257                     // we still need to emit exportStar helper
103258                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
103259                     statements.push(exportStarFunction_1);
103260                     return exportStarFunction_1.name;
103261                 }
103262             }
103263             var exportedNames = [];
103264             if (moduleInfo.exportedNames) {
103265                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
103266                     var exportedLocalName = _c[_b];
103267                     if (exportedLocalName.escapedText === "default") {
103268                         continue;
103269                     }
103270                     // write name of exported declaration, i.e 'export var x...'
103271                     exportedNames.push(factory.createPropertyAssignment(factory.createStringLiteralFromNode(exportedLocalName), factory.createTrue()));
103272                 }
103273             }
103274             var exportedNamesStorageRef = factory.createUniqueName("exportedNames");
103275             statements.push(factory.createVariableStatement(
103276             /*modifiers*/ undefined, factory.createVariableDeclarationList([
103277                 factory.createVariableDeclaration(exportedNamesStorageRef, 
103278                 /*exclamationToken*/ undefined, 
103279                 /*type*/ undefined, factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true))
103280             ])));
103281             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
103282             statements.push(exportStarFunction);
103283             return exportStarFunction.name;
103284         }
103285         /**
103286          * Creates an exportStar function for the file, with an optional set of excluded local
103287          * names.
103288          *
103289          * @param localNames An optional reference to an object containing a set of excluded local
103290          * names.
103291          */
103292         function createExportStarFunction(localNames) {
103293             var exportStarFunction = factory.createUniqueName("exportStar");
103294             var m = factory.createIdentifier("m");
103295             var n = factory.createIdentifier("n");
103296             var exports = factory.createIdentifier("exports");
103297             var condition = factory.createStrictInequality(n, factory.createStringLiteral("default"));
103298             if (localNames) {
103299                 condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), 
103300                 /*typeArguments*/ undefined, [n])));
103301             }
103302             return factory.createFunctionDeclaration(
103303             /*decorators*/ undefined, 
103304             /*modifiers*/ undefined, 
103305             /*asteriskToken*/ undefined, exportStarFunction, 
103306             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
103307             /*type*/ undefined, factory.createBlock([
103308                 factory.createVariableStatement(
103309                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
103310                     factory.createVariableDeclaration(exports, 
103311                     /*exclamationToken*/ undefined, 
103312                     /*type*/ undefined, factory.createObjectLiteralExpression([]))
103313                 ])),
103314                 factory.createForInStatement(factory.createVariableDeclarationList([
103315                     factory.createVariableDeclaration(n)
103316                 ]), m, factory.createBlock([
103317                     ts.setEmitFlags(factory.createIfStatement(condition, factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(exports, n), factory.createElementAccessExpression(m, n)))), 1 /* SingleLine */)
103318                 ])),
103319                 factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
103320                 /*typeArguments*/ undefined, [exports]))
103321             ], /*multiline*/ true));
103322         }
103323         /**
103324          * Creates an array setter callbacks for each dependency group.
103325          *
103326          * @param exportStarFunction A reference to an exportStarFunction for the file.
103327          * @param dependencyGroups An array of grouped dependencies.
103328          */
103329         function createSettersArray(exportStarFunction, dependencyGroups) {
103330             var setters = [];
103331             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
103332                 var group_2 = dependencyGroups_1[_i];
103333                 // derive a unique name for parameter from the first named entry in the group
103334                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(factory, i, currentSourceFile); });
103335                 var parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
103336                 var statements = [];
103337                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
103338                     var entry = _b[_a];
103339                     var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217
103340                     switch (entry.kind) {
103341                         case 265 /* ImportDeclaration */:
103342                             if (!entry.importClause) {
103343                                 // 'import "..."' case
103344                                 // module is imported only for side-effects, no emit required
103345                                 break;
103346                             }
103347                         // falls through
103348                         case 264 /* ImportEqualsDeclaration */:
103349                             ts.Debug.assert(importVariableName !== undefined);
103350                             // save import into the local
103351                             statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName)));
103352                             break;
103353                         case 271 /* ExportDeclaration */:
103354                             ts.Debug.assert(importVariableName !== undefined);
103355                             if (entry.exportClause) {
103356                                 if (ts.isNamedExports(entry.exportClause)) {
103357                                     //  export {a, b as c} from 'foo'
103358                                     //
103359                                     // emit as:
103360                                     //
103361                                     //  exports_({
103362                                     //     "a": _["a"],
103363                                     //     "c": _["b"]
103364                                     //  });
103365                                     var properties = [];
103366                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
103367                                         var e = _d[_c];
103368                                         properties.push(factory.createPropertyAssignment(factory.createStringLiteral(ts.idText(e.name)), factory.createElementAccessExpression(parameterName, factory.createStringLiteral(ts.idText(e.propertyName || e.name)))));
103369                                     }
103370                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
103371                                     /*typeArguments*/ undefined, [factory.createObjectLiteralExpression(properties, /*multiline*/ true)])));
103372                                 }
103373                                 else {
103374                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
103375                                     /*typeArguments*/ undefined, [
103376                                         factory.createStringLiteral(ts.idText(entry.exportClause.name)),
103377                                         parameterName
103378                                     ])));
103379                                 }
103380                             }
103381                             else {
103382                                 //  export * from 'foo'
103383                                 //
103384                                 // emit as:
103385                                 //
103386                                 //  exportStar(foo_1_1);
103387                                 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportStarFunction, 
103388                                 /*typeArguments*/ undefined, [parameterName])));
103389                             }
103390                             break;
103391                     }
103392                 }
103393                 setters.push(factory.createFunctionExpression(
103394                 /*modifiers*/ undefined, 
103395                 /*asteriskToken*/ undefined, 
103396                 /*name*/ undefined, 
103397                 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
103398                 /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true)));
103399             }
103400             return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
103401         }
103402         //
103403         // Top-level Source Element Visitors
103404         //
103405         /**
103406          * Visit source elements at the top-level of a module.
103407          *
103408          * @param node The node to visit.
103409          */
103410         function topLevelVisitor(node) {
103411             switch (node.kind) {
103412                 case 265 /* ImportDeclaration */:
103413                     return visitImportDeclaration(node);
103414                 case 264 /* ImportEqualsDeclaration */:
103415                     return visitImportEqualsDeclaration(node);
103416                 case 271 /* ExportDeclaration */:
103417                     return visitExportDeclaration(node);
103418                 case 270 /* ExportAssignment */:
103419                     return visitExportAssignment(node);
103420                 default:
103421                     return topLevelNestedVisitor(node);
103422             }
103423         }
103424         /**
103425          * Visits an ImportDeclaration node.
103426          *
103427          * @param node The node to visit.
103428          */
103429         function visitImportDeclaration(node) {
103430             var statements;
103431             if (node.importClause) {
103432                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
103433             }
103434             if (hasAssociatedEndOfDeclarationMarker(node)) {
103435                 // Defer exports until we encounter an EndOfDeclarationMarker node
103436                 var id = ts.getOriginalNodeId(node);
103437                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
103438             }
103439             else {
103440                 statements = appendExportsOfImportDeclaration(statements, node);
103441             }
103442             return ts.singleOrMany(statements);
103443         }
103444         function visitExportDeclaration(node) {
103445             ts.Debug.assertIsDefined(node);
103446             return undefined;
103447         }
103448         /**
103449          * Visits an ImportEqualsDeclaration node.
103450          *
103451          * @param node The node to visit.
103452          */
103453         function visitImportEqualsDeclaration(node) {
103454             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
103455             var statements;
103456             hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
103457             if (hasAssociatedEndOfDeclarationMarker(node)) {
103458                 // Defer exports until we encounter an EndOfDeclarationMarker node
103459                 var id = ts.getOriginalNodeId(node);
103460                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
103461             }
103462             else {
103463                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
103464             }
103465             return ts.singleOrMany(statements);
103466         }
103467         /**
103468          * Visits an ExportAssignment node.
103469          *
103470          * @param node The node to visit.
103471          */
103472         function visitExportAssignment(node) {
103473             if (node.isExportEquals) {
103474                 // Elide `export=` as it is illegal in a SystemJS module.
103475                 return undefined;
103476             }
103477             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
103478             var original = node.original;
103479             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
103480                 // Defer exports until we encounter an EndOfDeclarationMarker node
103481                 var id = ts.getOriginalNodeId(node);
103482                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
103483             }
103484             else {
103485                 return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
103486             }
103487         }
103488         /**
103489          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
103490          *
103491          * @param node The node to visit.
103492          */
103493         function visitFunctionDeclaration(node) {
103494             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
103495                 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), 
103496                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), 
103497                 /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)));
103498             }
103499             else {
103500                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, visitor, context));
103501             }
103502             if (hasAssociatedEndOfDeclarationMarker(node)) {
103503                 // Defer exports until we encounter an EndOfDeclarationMarker node
103504                 var id = ts.getOriginalNodeId(node);
103505                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
103506             }
103507             else {
103508                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
103509             }
103510             return undefined;
103511         }
103512         /**
103513          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
103514          *
103515          * @param node The node to visit.
103516          */
103517         function visitClassDeclaration(node) {
103518             var statements;
103519             // Hoist the name of the class declaration to the outer module body function.
103520             var name = factory.getLocalName(node);
103521             hoistVariableDeclaration(name);
103522             // Rewrite the class declaration into an assignment of a class expression.
103523             statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), 
103524             /*modifiers*/ undefined, node.name, 
103525             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node));
103526             if (hasAssociatedEndOfDeclarationMarker(node)) {
103527                 // Defer exports until we encounter an EndOfDeclarationMarker node
103528                 var id = ts.getOriginalNodeId(node);
103529                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
103530             }
103531             else {
103532                 statements = appendExportsOfHoistedDeclaration(statements, node);
103533             }
103534             return ts.singleOrMany(statements);
103535         }
103536         /**
103537          * Visits a variable statement, hoisting declared names to the top-level module body.
103538          * Each declaration is rewritten into an assignment expression.
103539          *
103540          * @param node The node to visit.
103541          */
103542         function visitVariableStatement(node) {
103543             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
103544                 return ts.visitNode(node, visitor, ts.isStatement);
103545             }
103546             var expressions;
103547             var isExportedDeclaration = ts.hasSyntacticModifier(node, 1 /* Export */);
103548             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
103549             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
103550                 var variable = _a[_i];
103551                 if (variable.initializer) {
103552                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
103553                 }
103554                 else {
103555                     hoistBindingElement(variable);
103556                 }
103557             }
103558             var statements;
103559             if (expressions) {
103560                 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
103561             }
103562             if (isMarkedDeclaration) {
103563                 // Defer exports until we encounter an EndOfDeclarationMarker node
103564                 var id = ts.getOriginalNodeId(node);
103565                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
103566             }
103567             else {
103568                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
103569             }
103570             return ts.singleOrMany(statements);
103571         }
103572         /**
103573          * Hoists the declared names of a VariableDeclaration or BindingElement.
103574          *
103575          * @param node The declaration to hoist.
103576          */
103577         function hoistBindingElement(node) {
103578             if (ts.isBindingPattern(node.name)) {
103579                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
103580                     var element = _a[_i];
103581                     if (!ts.isOmittedExpression(element)) {
103582                         hoistBindingElement(element);
103583                     }
103584                 }
103585             }
103586             else {
103587                 hoistVariableDeclaration(factory.cloneNode(node.name));
103588             }
103589         }
103590         /**
103591          * Determines whether a VariableDeclarationList should be hoisted.
103592          *
103593          * @param node The node to test.
103594          */
103595         function shouldHoistVariableDeclarationList(node) {
103596             // hoist only non-block scoped declarations or block scoped declarations parented by source file
103597             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
103598                 && (enclosingBlockScopedContainer.kind === 303 /* SourceFile */
103599                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
103600         }
103601         /**
103602          * Transform an initialized variable declaration into an expression.
103603          *
103604          * @param node The node to transform.
103605          * @param isExportedDeclaration A value indicating whether the variable is exported.
103606          */
103607         function transformInitializedVariable(node, isExportedDeclaration) {
103608             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
103609             return ts.isBindingPattern(node.name)
103610                 ? ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
103611                 /*needsValue*/ false, createAssignment)
103612                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, visitor, ts.isExpression)) : node.name;
103613         }
103614         /**
103615          * Creates an assignment expression for an exported variable declaration.
103616          *
103617          * @param name The name of the variable.
103618          * @param value The value of the variable's initializer.
103619          * @param location The source map location for the assignment.
103620          */
103621         function createExportedVariableAssignment(name, value, location) {
103622             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
103623         }
103624         /**
103625          * Creates an assignment expression for a non-exported variable declaration.
103626          *
103627          * @param name The name of the variable.
103628          * @param value The value of the variable's initializer.
103629          * @param location The source map location for the assignment.
103630          */
103631         function createNonExportedVariableAssignment(name, value, location) {
103632             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
103633         }
103634         /**
103635          * Creates an assignment expression for a variable declaration.
103636          *
103637          * @param name The name of the variable.
103638          * @param value The value of the variable's initializer.
103639          * @param location The source map location for the assignment.
103640          * @param isExportedDeclaration A value indicating whether the variable is exported.
103641          */
103642         function createVariableAssignment(name, value, location, isExportedDeclaration) {
103643             hoistVariableDeclaration(factory.cloneNode(name));
103644             return isExportedDeclaration
103645                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)))
103646                 : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location));
103647         }
103648         /**
103649          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
103650          * and transformed declaration.
103651          *
103652          * @param node The node to visit.
103653          */
103654         function visitMergeDeclarationMarker(node) {
103655             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
103656             // declaration we do not emit a leading variable declaration. To preserve the
103657             // begin/end semantics of the declararation and to properly handle exports
103658             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
103659             //
103660             // To balance the declaration, we defer the exports of the elided variable
103661             // statement until we visit this declaration's `EndOfDeclarationMarker`.
103662             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 236 /* VariableStatement */) {
103663                 var id = ts.getOriginalNodeId(node);
103664                 var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */);
103665                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
103666             }
103667             return node;
103668         }
103669         /**
103670          * Determines whether a node has an associated EndOfDeclarationMarker.
103671          *
103672          * @param node The node to test.
103673          */
103674         function hasAssociatedEndOfDeclarationMarker(node) {
103675             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
103676         }
103677         /**
103678          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
103679          * declaration.
103680          *
103681          * @param node The node to visit.
103682          */
103683         function visitEndOfDeclarationMarker(node) {
103684             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
103685             // end of the transformed declaration. We use this marker to emit any deferred exports
103686             // of the declaration.
103687             var id = ts.getOriginalNodeId(node);
103688             var statements = deferredExports[id];
103689             if (statements) {
103690                 delete deferredExports[id];
103691                 return ts.append(statements, node);
103692             }
103693             else {
103694                 var original = ts.getOriginalNode(node);
103695                 if (ts.isModuleOrEnumDeclaration(original)) {
103696                     return ts.append(appendExportsOfDeclaration(statements, original), node);
103697                 }
103698             }
103699             return node;
103700         }
103701         /**
103702          * Appends the exports of an ImportDeclaration to a statement list, returning the
103703          * statement list.
103704          *
103705          * @param statements A statement list to which the down-level export statements are to be
103706          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103707          * appended.
103708          * @param decl The declaration whose exports are to be recorded.
103709          */
103710         function appendExportsOfImportDeclaration(statements, decl) {
103711             if (moduleInfo.exportEquals) {
103712                 return statements;
103713             }
103714             var importClause = decl.importClause;
103715             if (!importClause) {
103716                 return statements;
103717             }
103718             if (importClause.name) {
103719                 statements = appendExportsOfDeclaration(statements, importClause);
103720             }
103721             var namedBindings = importClause.namedBindings;
103722             if (namedBindings) {
103723                 switch (namedBindings.kind) {
103724                     case 267 /* NamespaceImport */:
103725                         statements = appendExportsOfDeclaration(statements, namedBindings);
103726                         break;
103727                     case 268 /* NamedImports */:
103728                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
103729                             var importBinding = _a[_i];
103730                             statements = appendExportsOfDeclaration(statements, importBinding);
103731                         }
103732                         break;
103733                 }
103734             }
103735             return statements;
103736         }
103737         /**
103738          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
103739          * statement list.
103740          *
103741          * @param statements A statement list to which the down-level export statements are to be
103742          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103743          * appended.
103744          * @param decl The declaration whose exports are to be recorded.
103745          */
103746         function appendExportsOfImportEqualsDeclaration(statements, decl) {
103747             if (moduleInfo.exportEquals) {
103748                 return statements;
103749             }
103750             return appendExportsOfDeclaration(statements, decl);
103751         }
103752         /**
103753          * Appends the exports of a VariableStatement to a statement list, returning the statement
103754          * list.
103755          *
103756          * @param statements A statement list to which the down-level export statements are to be
103757          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103758          * appended.
103759          * @param node The VariableStatement whose exports are to be recorded.
103760          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
103761          * `nodes` declaration list.
103762          */
103763         function appendExportsOfVariableStatement(statements, node, exportSelf) {
103764             if (moduleInfo.exportEquals) {
103765                 return statements;
103766             }
103767             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
103768                 var decl = _a[_i];
103769                 if (decl.initializer || exportSelf) {
103770                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
103771                 }
103772             }
103773             return statements;
103774         }
103775         /**
103776          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
103777          * returning the statement list.
103778          *
103779          * @param statements A statement list to which the down-level export statements are to be
103780          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103781          * appended.
103782          * @param decl The declaration whose exports are to be recorded.
103783          * @param exportSelf A value indicating whether to also export the declaration itself.
103784          */
103785         function appendExportsOfBindingElement(statements, decl, exportSelf) {
103786             if (moduleInfo.exportEquals) {
103787                 return statements;
103788             }
103789             if (ts.isBindingPattern(decl.name)) {
103790                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
103791                     var element = _a[_i];
103792                     if (!ts.isOmittedExpression(element)) {
103793                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
103794                     }
103795                 }
103796             }
103797             else if (!ts.isGeneratedIdentifier(decl.name)) {
103798                 var excludeName = void 0;
103799                 if (exportSelf) {
103800                     statements = appendExportStatement(statements, decl.name, factory.getLocalName(decl));
103801                     excludeName = ts.idText(decl.name);
103802                 }
103803                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
103804             }
103805             return statements;
103806         }
103807         /**
103808          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
103809          * returning the statement list.
103810          *
103811          * @param statements A statement list to which the down-level export statements are to be
103812          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103813          * appended.
103814          * @param decl The declaration whose exports are to be recorded.
103815          */
103816         function appendExportsOfHoistedDeclaration(statements, decl) {
103817             if (moduleInfo.exportEquals) {
103818                 return statements;
103819             }
103820             var excludeName;
103821             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
103822                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createStringLiteral("default") : decl.name;
103823                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl));
103824                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
103825             }
103826             if (decl.name) {
103827                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
103828             }
103829             return statements;
103830         }
103831         /**
103832          * Appends the exports of a declaration to a statement list, returning the statement list.
103833          *
103834          * @param statements A statement list to which the down-level export statements are to be
103835          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103836          * appended.
103837          * @param decl The declaration to export.
103838          * @param excludeName An optional name to exclude from exports.
103839          */
103840         function appendExportsOfDeclaration(statements, decl, excludeName) {
103841             if (moduleInfo.exportEquals) {
103842                 return statements;
103843             }
103844             var name = factory.getDeclarationName(decl);
103845             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
103846             if (exportSpecifiers) {
103847                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
103848                     var exportSpecifier = exportSpecifiers_2[_i];
103849                     if (exportSpecifier.name.escapedText !== excludeName) {
103850                         statements = appendExportStatement(statements, exportSpecifier.name, name);
103851                     }
103852                 }
103853             }
103854             return statements;
103855         }
103856         /**
103857          * Appends the down-level representation of an export to a statement list, returning the
103858          * statement list.
103859          *
103860          * @param statements A statement list to which the down-level export statements are to be
103861          * appended. If `statements` is `undefined`, a new array is allocated if statements are
103862          * appended.
103863          * @param exportName The name of the export.
103864          * @param expression The expression to export.
103865          * @param allowComments Whether to allow comments on the export.
103866          */
103867         function appendExportStatement(statements, exportName, expression, allowComments) {
103868             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
103869             return statements;
103870         }
103871         /**
103872          * Creates a call to the current file's export function to export a value.
103873          *
103874          * @param name The bound name of the export.
103875          * @param value The exported value.
103876          * @param allowComments An optional value indicating whether to emit comments for the statement.
103877          */
103878         function createExportStatement(name, value, allowComments) {
103879             var statement = factory.createExpressionStatement(createExportExpression(name, value));
103880             ts.startOnNewLine(statement);
103881             if (!allowComments) {
103882                 ts.setEmitFlags(statement, 1536 /* NoComments */);
103883             }
103884             return statement;
103885         }
103886         /**
103887          * Creates a call to the current file's export function to export a value.
103888          *
103889          * @param name The bound name of the export.
103890          * @param value The exported value.
103891          */
103892         function createExportExpression(name, value) {
103893             var exportName = ts.isIdentifier(name) ? factory.createStringLiteralFromNode(name) : name;
103894             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
103895             return ts.setCommentRange(factory.createCallExpression(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
103896         }
103897         //
103898         // Top-Level or Nested Source Element Visitors
103899         //
103900         /**
103901          * Visit nested elements at the top-level of a module.
103902          *
103903          * @param node The node to visit.
103904          */
103905         function topLevelNestedVisitor(node) {
103906             switch (node.kind) {
103907                 case 236 /* VariableStatement */:
103908                     return visitVariableStatement(node);
103909                 case 255 /* FunctionDeclaration */:
103910                     return visitFunctionDeclaration(node);
103911                 case 256 /* ClassDeclaration */:
103912                     return visitClassDeclaration(node);
103913                 case 241 /* ForStatement */:
103914                     return visitForStatement(node, /*isTopLevel*/ true);
103915                 case 242 /* ForInStatement */:
103916                     return visitForInStatement(node);
103917                 case 243 /* ForOfStatement */:
103918                     return visitForOfStatement(node);
103919                 case 239 /* DoStatement */:
103920                     return visitDoStatement(node);
103921                 case 240 /* WhileStatement */:
103922                     return visitWhileStatement(node);
103923                 case 249 /* LabeledStatement */:
103924                     return visitLabeledStatement(node);
103925                 case 247 /* WithStatement */:
103926                     return visitWithStatement(node);
103927                 case 248 /* SwitchStatement */:
103928                     return visitSwitchStatement(node);
103929                 case 262 /* CaseBlock */:
103930                     return visitCaseBlock(node);
103931                 case 288 /* CaseClause */:
103932                     return visitCaseClause(node);
103933                 case 289 /* DefaultClause */:
103934                     return visitDefaultClause(node);
103935                 case 251 /* TryStatement */:
103936                     return visitTryStatement(node);
103937                 case 291 /* CatchClause */:
103938                     return visitCatchClause(node);
103939                 case 234 /* Block */:
103940                     return visitBlock(node);
103941                 case 350 /* MergeDeclarationMarker */:
103942                     return visitMergeDeclarationMarker(node);
103943                 case 351 /* EndOfDeclarationMarker */:
103944                     return visitEndOfDeclarationMarker(node);
103945                 default:
103946                     return visitor(node);
103947             }
103948         }
103949         /**
103950          * Visits the body of a ForStatement to hoist declarations.
103951          *
103952          * @param node The node to visit.
103953          */
103954         function visitForStatement(node, isTopLevel) {
103955             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
103956             enclosingBlockScopedContainer = node;
103957             node = factory.updateForStatement(node, ts.visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, discardedValueVisitor, ts.isExpression), ts.visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context));
103958             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
103959             return node;
103960         }
103961         /**
103962          * Visits the body of a ForInStatement to hoist declarations.
103963          *
103964          * @param node The node to visit.
103965          */
103966         function visitForInStatement(node) {
103967             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
103968             enclosingBlockScopedContainer = node;
103969             node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, topLevelNestedVisitor, context));
103970             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
103971             return node;
103972         }
103973         /**
103974          * Visits the body of a ForOfStatement to hoist declarations.
103975          *
103976          * @param node The node to visit.
103977          */
103978         function visitForOfStatement(node) {
103979             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
103980             enclosingBlockScopedContainer = node;
103981             node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, topLevelNestedVisitor, context));
103982             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
103983             return node;
103984         }
103985         /**
103986          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
103987          * ForOfStatement.
103988          *
103989          * @param node The node to test.
103990          */
103991         function shouldHoistForInitializer(node) {
103992             return ts.isVariableDeclarationList(node)
103993                 && shouldHoistVariableDeclarationList(node);
103994         }
103995         /**
103996          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
103997          *
103998          * @param node The node to visit.
103999          */
104000         function visitForInitializer(node) {
104001             if (shouldHoistForInitializer(node)) {
104002                 var expressions = void 0;
104003                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
104004                     var variable = _a[_i];
104005                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
104006                     if (!variable.initializer) {
104007                         hoistBindingElement(variable);
104008                     }
104009                 }
104010                 return expressions ? factory.inlineExpressions(expressions) : factory.createOmittedExpression();
104011             }
104012             else {
104013                 return ts.visitNode(node, discardedValueVisitor, ts.isExpression);
104014             }
104015         }
104016         /**
104017          * Visits the body of a DoStatement to hoist declarations.
104018          *
104019          * @param node The node to visit.
104020          */
104021         function visitDoStatement(node) {
104022             return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, topLevelNestedVisitor, context), ts.visitNode(node.expression, visitor, ts.isExpression));
104023         }
104024         /**
104025          * Visits the body of a WhileStatement to hoist declarations.
104026          *
104027          * @param node The node to visit.
104028          */
104029         function visitWhileStatement(node) {
104030             return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, topLevelNestedVisitor, context));
104031         }
104032         /**
104033          * Visits the body of a LabeledStatement to hoist declarations.
104034          *
104035          * @param node The node to visit.
104036          */
104037         function visitLabeledStatement(node) {
104038             return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, topLevelNestedVisitor, ts.isStatement, factory.liftToBlock));
104039         }
104040         /**
104041          * Visits the body of a WithStatement to hoist declarations.
104042          *
104043          * @param node The node to visit.
104044          */
104045         function visitWithStatement(node) {
104046             return factory.updateWithStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, topLevelNestedVisitor, ts.isStatement, factory.liftToBlock));
104047         }
104048         /**
104049          * Visits the body of a SwitchStatement to hoist declarations.
104050          *
104051          * @param node The node to visit.
104052          */
104053         function visitSwitchStatement(node) {
104054             return factory.updateSwitchStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.caseBlock, topLevelNestedVisitor, ts.isCaseBlock));
104055         }
104056         /**
104057          * Visits the body of a CaseBlock to hoist declarations.
104058          *
104059          * @param node The node to visit.
104060          */
104061         function visitCaseBlock(node) {
104062             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
104063             enclosingBlockScopedContainer = node;
104064             node = factory.updateCaseBlock(node, ts.visitNodes(node.clauses, topLevelNestedVisitor, ts.isCaseOrDefaultClause));
104065             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
104066             return node;
104067         }
104068         /**
104069          * Visits the body of a CaseClause to hoist declarations.
104070          *
104071          * @param node The node to visit.
104072          */
104073         function visitCaseClause(node) {
104074             return factory.updateCaseClause(node, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNodes(node.statements, topLevelNestedVisitor, ts.isStatement));
104075         }
104076         /**
104077          * Visits the body of a DefaultClause to hoist declarations.
104078          *
104079          * @param node The node to visit.
104080          */
104081         function visitDefaultClause(node) {
104082             return ts.visitEachChild(node, topLevelNestedVisitor, context);
104083         }
104084         /**
104085          * Visits the body of a TryStatement to hoist declarations.
104086          *
104087          * @param node The node to visit.
104088          */
104089         function visitTryStatement(node) {
104090             return ts.visitEachChild(node, topLevelNestedVisitor, context);
104091         }
104092         /**
104093          * Visits the body of a CatchClause to hoist declarations.
104094          *
104095          * @param node The node to visit.
104096          */
104097         function visitCatchClause(node) {
104098             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
104099             enclosingBlockScopedContainer = node;
104100             node = factory.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, topLevelNestedVisitor, ts.isBlock));
104101             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
104102             return node;
104103         }
104104         /**
104105          * Visits the body of a Block to hoist declarations.
104106          *
104107          * @param node The node to visit.
104108          */
104109         function visitBlock(node) {
104110             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
104111             enclosingBlockScopedContainer = node;
104112             node = ts.visitEachChild(node, topLevelNestedVisitor, context);
104113             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
104114             return node;
104115         }
104116         //
104117         // Destructuring Assignment Visitors
104118         //
104119         /**
104120          * Visit nodes to flatten destructuring assignments to exported symbols.
104121          *
104122          * @param node The node to visit.
104123          */
104124         function visitorWorker(node, valueIsDiscarded) {
104125             if (!(node.transformFlags & (2048 /* ContainsDestructuringAssignment */ | 4194304 /* ContainsDynamicImport */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) {
104126                 return node;
104127             }
104128             switch (node.kind) {
104129                 case 241 /* ForStatement */:
104130                     return visitForStatement(node, /*isTopLevel*/ false);
104131                 case 237 /* ExpressionStatement */:
104132                     return visitExpressionStatement(node);
104133                 case 211 /* ParenthesizedExpression */:
104134                     return visitParenthesizedExpression(node, valueIsDiscarded);
104135                 case 348 /* PartiallyEmittedExpression */:
104136                     return visitPartiallyEmittedExpression(node, valueIsDiscarded);
104137                 case 220 /* BinaryExpression */:
104138                     if (ts.isDestructuringAssignment(node)) {
104139                         return visitDestructuringAssignment(node, valueIsDiscarded);
104140                     }
104141                     break;
104142                 case 207 /* CallExpression */:
104143                     if (ts.isImportCall(node)) {
104144                         return visitImportCallExpression(node);
104145                     }
104146                     break;
104147                 case 218 /* PrefixUnaryExpression */:
104148                 case 219 /* PostfixUnaryExpression */:
104149                     return visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded);
104150             }
104151             return ts.visitEachChild(node, visitor, context);
104152         }
104153         /**
104154          * Visit nodes to flatten destructuring assignments to exported symbols.
104155          *
104156          * @param node The node to visit.
104157          */
104158         function visitor(node) {
104159             return visitorWorker(node, /*valueIsDiscarded*/ false);
104160         }
104161         function discardedValueVisitor(node) {
104162             return visitorWorker(node, /*valueIsDiscarded*/ true);
104163         }
104164         function visitExpressionStatement(node) {
104165             return factory.updateExpressionStatement(node, ts.visitNode(node.expression, discardedValueVisitor, ts.isExpression));
104166         }
104167         function visitParenthesizedExpression(node, valueIsDiscarded) {
104168             return factory.updateParenthesizedExpression(node, ts.visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, ts.isExpression));
104169         }
104170         function visitPartiallyEmittedExpression(node, valueIsDiscarded) {
104171             return factory.updatePartiallyEmittedExpression(node, ts.visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, ts.isExpression));
104172         }
104173         function visitImportCallExpression(node) {
104174             // import("./blah")
104175             // emit as
104176             // System.register([], function (_export, _context) {
104177             //     return {
104178             //         setters: [],
104179             //         execute: () => {
104180             //             _context.import('./blah');
104181             //         }
104182             //     };
104183             // });
104184             var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
104185             var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor);
104186             // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
104187             var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
104188             return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")), 
104189             /*typeArguments*/ undefined, argument ? [argument] : []);
104190         }
104191         /**
104192          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
104193          *
104194          * @param node The node to visit.
104195          */
104196         function visitDestructuringAssignment(node, valueIsDiscarded) {
104197             if (hasExportedReferenceInDestructuringTarget(node.left)) {
104198                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !valueIsDiscarded);
104199             }
104200             return ts.visitEachChild(node, visitor, context);
104201         }
104202         /**
104203          * Determines whether the target of a destructuring assignment refers to an exported symbol.
104204          *
104205          * @param node The destructuring target.
104206          */
104207         function hasExportedReferenceInDestructuringTarget(node) {
104208             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
104209                 return hasExportedReferenceInDestructuringTarget(node.left);
104210             }
104211             else if (ts.isSpreadElement(node)) {
104212                 return hasExportedReferenceInDestructuringTarget(node.expression);
104213             }
104214             else if (ts.isObjectLiteralExpression(node)) {
104215                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
104216             }
104217             else if (ts.isArrayLiteralExpression(node)) {
104218                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
104219             }
104220             else if (ts.isShorthandPropertyAssignment(node)) {
104221                 return hasExportedReferenceInDestructuringTarget(node.name);
104222             }
104223             else if (ts.isPropertyAssignment(node)) {
104224                 return hasExportedReferenceInDestructuringTarget(node.initializer);
104225             }
104226             else if (ts.isIdentifier(node)) {
104227                 var container = resolver.getReferencedExportContainer(node);
104228                 return container !== undefined && container.kind === 303 /* SourceFile */;
104229             }
104230             else {
104231                 return false;
104232             }
104233         }
104234         function visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded) {
104235             // When we see a prefix or postfix increment expression whose operand is an exported
104236             // symbol, we should ensure all exports of that symbol are updated with the correct
104237             // value.
104238             //
104239             // - We do not transform generated identifiers for any reason.
104240             // - We do not transform identifiers tagged with the LocalName flag.
104241             // - We do not transform identifiers that were originally the name of an enum or
104242             //   namespace due to how they are transformed in TypeScript.
104243             // - We only transform identifiers that are exported at the top level.
104244             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
104245                 && ts.isIdentifier(node.operand)
104246                 && !ts.isGeneratedIdentifier(node.operand)
104247                 && !ts.isLocalName(node.operand)
104248                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
104249                 var exportedNames = getExports(node.operand);
104250                 if (exportedNames) {
104251                     var temp = void 0;
104252                     var expression = ts.visitNode(node.operand, visitor, ts.isExpression);
104253                     if (ts.isPrefixUnaryExpression(node)) {
104254                         expression = factory.updatePrefixUnaryExpression(node, expression);
104255                     }
104256                     else {
104257                         expression = factory.updatePostfixUnaryExpression(node, expression);
104258                         if (!valueIsDiscarded) {
104259                             temp = factory.createTempVariable(hoistVariableDeclaration);
104260                             expression = factory.createAssignment(temp, expression);
104261                             ts.setTextRange(expression, node);
104262                         }
104263                         expression = factory.createComma(expression, factory.cloneNode(node.operand));
104264                         ts.setTextRange(expression, node);
104265                     }
104266                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
104267                         var exportName = exportedNames_4[_i];
104268                         expression = createExportExpression(exportName, preventSubstitution(expression));
104269                     }
104270                     if (temp) {
104271                         expression = factory.createComma(expression, temp);
104272                         ts.setTextRange(expression, node);
104273                     }
104274                     return expression;
104275                 }
104276             }
104277             return ts.visitEachChild(node, visitor, context);
104278         }
104279         //
104280         // Modifier Visitors
104281         //
104282         /**
104283          * Visit nodes to elide module-specific modifiers.
104284          *
104285          * @param node The node to visit.
104286          */
104287         function modifierVisitor(node) {
104288             switch (node.kind) {
104289                 case 93 /* ExportKeyword */:
104290                 case 88 /* DefaultKeyword */:
104291                     return undefined;
104292             }
104293             return node;
104294         }
104295         //
104296         // Emit Notification
104297         //
104298         /**
104299          * Hook for node emit notifications.
104300          *
104301          * @param hint A hint as to the intended usage of the node.
104302          * @param node The node to emit.
104303          * @param emitCallback A callback used to emit the node in the printer.
104304          */
104305         function onEmitNode(hint, node, emitCallback) {
104306             if (node.kind === 303 /* SourceFile */) {
104307                 var id = ts.getOriginalNodeId(node);
104308                 currentSourceFile = node;
104309                 moduleInfo = moduleInfoMap[id];
104310                 exportFunction = exportFunctionsMap[id];
104311                 noSubstitution = noSubstitutionMap[id];
104312                 contextObject = contextObjectMap[id];
104313                 if (noSubstitution) {
104314                     delete noSubstitutionMap[id];
104315                 }
104316                 previousOnEmitNode(hint, node, emitCallback);
104317                 currentSourceFile = undefined;
104318                 moduleInfo = undefined;
104319                 exportFunction = undefined;
104320                 contextObject = undefined;
104321                 noSubstitution = undefined;
104322             }
104323             else {
104324                 previousOnEmitNode(hint, node, emitCallback);
104325             }
104326         }
104327         //
104328         // Substitutions
104329         //
104330         /**
104331          * Hooks node substitutions.
104332          *
104333          * @param hint A hint as to the intended usage of the node.
104334          * @param node The node to substitute.
104335          */
104336         function onSubstituteNode(hint, node) {
104337             node = previousOnSubstituteNode(hint, node);
104338             if (isSubstitutionPrevented(node)) {
104339                 return node;
104340             }
104341             if (hint === 1 /* Expression */) {
104342                 return substituteExpression(node);
104343             }
104344             else if (hint === 4 /* Unspecified */) {
104345                 return substituteUnspecified(node);
104346             }
104347             return node;
104348         }
104349         /**
104350          * Substitute the node, if necessary.
104351          *
104352          * @param node The node to substitute.
104353          */
104354         function substituteUnspecified(node) {
104355             switch (node.kind) {
104356                 case 295 /* ShorthandPropertyAssignment */:
104357                     return substituteShorthandPropertyAssignment(node);
104358             }
104359             return node;
104360         }
104361         /**
104362          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
104363          *
104364          * @param node The node to substitute.
104365          */
104366         function substituteShorthandPropertyAssignment(node) {
104367             var _a, _b;
104368             var name = node.name;
104369             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
104370                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
104371                 if (importDeclaration) {
104372                     if (ts.isImportClause(importDeclaration)) {
104373                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default"))), 
104374                         /*location*/ node);
104375                     }
104376                     else if (ts.isImportSpecifier(importDeclaration)) {
104377                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))), 
104378                         /*location*/ node);
104379                     }
104380                 }
104381             }
104382             return node;
104383         }
104384         /**
104385          * Substitute the expression, if necessary.
104386          *
104387          * @param node The node to substitute.
104388          */
104389         function substituteExpression(node) {
104390             switch (node.kind) {
104391                 case 79 /* Identifier */:
104392                     return substituteExpressionIdentifier(node);
104393                 case 220 /* BinaryExpression */:
104394                     return substituteBinaryExpression(node);
104395                 case 230 /* MetaProperty */:
104396                     return substituteMetaProperty(node);
104397             }
104398             return node;
104399         }
104400         /**
104401          * Substitution for an Identifier expression that may contain an imported or exported symbol.
104402          *
104403          * @param node The node to substitute.
104404          */
104405         function substituteExpressionIdentifier(node) {
104406             var _a, _b;
104407             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
104408                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
104409                 if (externalHelpersModuleName) {
104410                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
104411                 }
104412                 return node;
104413             }
104414             // When we see an identifier in an expression position that
104415             // points to an imported symbol, we should substitute a qualified
104416             // reference to the imported symbol if one is needed.
104417             //
104418             // - We do not substitute generated identifiers for any reason.
104419             // - We do not substitute identifiers tagged with the LocalName flag.
104420             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
104421                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
104422                 if (importDeclaration) {
104423                     if (ts.isImportClause(importDeclaration)) {
104424                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
104425                         /*location*/ node);
104426                     }
104427                     else if (ts.isImportSpecifier(importDeclaration)) {
104428                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) || importDeclaration), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)), 
104429                         /*location*/ node);
104430                     }
104431                 }
104432             }
104433             return node;
104434         }
104435         /**
104436          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
104437          *
104438          * @param node The node to substitute.
104439          */
104440         function substituteBinaryExpression(node) {
104441             // When we see an assignment expression whose left-hand side is an exported symbol,
104442             // we should ensure all exports of that symbol are updated with the correct value.
104443             //
104444             // - We do not substitute generated identifiers for any reason.
104445             // - We do not substitute identifiers tagged with the LocalName flag.
104446             // - We do not substitute identifiers that were originally the name of an enum or
104447             //   namespace due to how they are transformed in TypeScript.
104448             // - We only substitute identifiers that are exported at the top level.
104449             if (ts.isAssignmentOperator(node.operatorToken.kind)
104450                 && ts.isIdentifier(node.left)
104451                 && !ts.isGeneratedIdentifier(node.left)
104452                 && !ts.isLocalName(node.left)
104453                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
104454                 var exportedNames = getExports(node.left);
104455                 if (exportedNames) {
104456                     // For each additional export of the declaration, apply an export assignment.
104457                     var expression = node;
104458                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
104459                         var exportName = exportedNames_5[_i];
104460                         expression = createExportExpression(exportName, preventSubstitution(expression));
104461                     }
104462                     return expression;
104463                 }
104464             }
104465             return node;
104466         }
104467         function substituteMetaProperty(node) {
104468             if (ts.isImportMeta(node)) {
104469                 return factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("meta"));
104470             }
104471             return node;
104472         }
104473         /**
104474          * Gets the exports of a name.
104475          *
104476          * @param name The name.
104477          */
104478         function getExports(name) {
104479             var exportedNames;
104480             if (!ts.isGeneratedIdentifier(name)) {
104481                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
104482                     || resolver.getReferencedValueDeclaration(name);
104483                 if (valueDeclaration) {
104484                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
104485                     if (exportContainer && exportContainer.kind === 303 /* SourceFile */) {
104486                         exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration));
104487                     }
104488                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
104489                 }
104490             }
104491             return exportedNames;
104492         }
104493         /**
104494          * Prevent substitution of a node for this transformer.
104495          *
104496          * @param node The node which should not be substituted.
104497          */
104498         function preventSubstitution(node) {
104499             if (noSubstitution === undefined)
104500                 noSubstitution = [];
104501             noSubstitution[ts.getNodeId(node)] = true;
104502             return node;
104503         }
104504         /**
104505          * Determines whether a node should not be substituted.
104506          *
104507          * @param node The node to test.
104508          */
104509         function isSubstitutionPrevented(node) {
104510             return noSubstitution && node.id && noSubstitution[node.id];
104511         }
104512     }
104513     ts.transformSystemModule = transformSystemModule;
104514 })(ts || (ts = {}));
104515 /*@internal*/
104516 var ts;
104517 (function (ts) {
104518     function transformECMAScriptModule(context) {
104519         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
104520         var host = context.getEmitHost();
104521         var resolver = context.getEmitResolver();
104522         var compilerOptions = context.getCompilerOptions();
104523         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
104524         var previousOnEmitNode = context.onEmitNode;
104525         var previousOnSubstituteNode = context.onSubstituteNode;
104526         context.onEmitNode = onEmitNode;
104527         context.onSubstituteNode = onSubstituteNode;
104528         context.enableEmitNotification(303 /* SourceFile */);
104529         context.enableSubstitution(79 /* Identifier */);
104530         var helperNameSubstitutions;
104531         var currentSourceFile;
104532         var importRequireStatements;
104533         return ts.chainBundle(context, transformSourceFile);
104534         function transformSourceFile(node) {
104535             if (node.isDeclarationFile) {
104536                 return node;
104537             }
104538             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
104539                 currentSourceFile = node;
104540                 importRequireStatements = undefined;
104541                 var result = updateExternalModule(node);
104542                 currentSourceFile = undefined;
104543                 if (importRequireStatements) {
104544                     result = factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(ts.insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements));
104545                 }
104546                 if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
104547                     return result;
104548                 }
104549                 return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], result.statements, true), [ts.createEmptyExports(factory)], false)), result.statements));
104550             }
104551             return node;
104552         }
104553         function updateExternalModule(node) {
104554             var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
104555             if (externalHelpersImportDeclaration) {
104556                 var statements = [];
104557                 var statementOffset = factory.copyPrologue(node.statements, statements);
104558                 ts.append(statements, externalHelpersImportDeclaration);
104559                 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
104560                 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
104561             }
104562             else {
104563                 return ts.visitEachChild(node, visitor, context);
104564             }
104565         }
104566         function visitor(node) {
104567             switch (node.kind) {
104568                 case 264 /* ImportEqualsDeclaration */:
104569                     // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call
104570                     // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url`
104571                     // is available, just because the output is reasonable for a node-like runtime.
104572                     return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined;
104573                 case 270 /* ExportAssignment */:
104574                     return visitExportAssignment(node);
104575                 case 271 /* ExportDeclaration */:
104576                     var exportDecl = node;
104577                     return visitExportDeclaration(exportDecl);
104578             }
104579             return node;
104580         }
104581         /**
104582          * Creates a `require()` call to import an external module.
104583          *
104584          * @param importNode The declaration to import.
104585          */
104586         function createRequireCall(importNode) {
104587             var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, ts.Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions);
104588             var args = [];
104589             if (moduleName) {
104590                 args.push(moduleName);
104591             }
104592             if (!importRequireStatements) {
104593                 var createRequireName = factory.createUniqueName("_createRequire", 16 /* Optimistic */ | 32 /* FileLevel */);
104594                 var importStatement = factory.createImportDeclaration(
104595                 /*decorators*/ undefined, 
104596                 /*modifiers*/ undefined, factory.createImportClause(
104597                 /*isTypeOnly*/ false, 
104598                 /*name*/ undefined, factory.createNamedImports([
104599                     factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName)
104600                 ])), factory.createStringLiteral("module"));
104601                 var requireHelperName = factory.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */);
104602                 var requireStatement = factory.createVariableStatement(
104603                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
104604                     factory.createVariableDeclaration(requireHelperName, 
104605                     /*exclamationToken*/ undefined, 
104606                     /*type*/ undefined, factory.createCallExpression(factory.cloneNode(createRequireName), /*typeArguments*/ undefined, [
104607                         factory.createPropertyAccessExpression(factory.createMetaProperty(100 /* ImportKeyword */, factory.createIdentifier("meta")), factory.createIdentifier("url"))
104608                     ]))
104609                 ], 
104610                 /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */));
104611                 importRequireStatements = [importStatement, requireStatement];
104612             }
104613             var name = importRequireStatements[1].declarationList.declarations[0].name;
104614             ts.Debug.assertNode(name, ts.isIdentifier);
104615             return factory.createCallExpression(factory.cloneNode(name), /*typeArguments*/ undefined, args);
104616         }
104617         /**
104618          * Visits an ImportEqualsDeclaration node.
104619          *
104620          * @param node The node to visit.
104621          */
104622         function visitImportEqualsDeclaration(node) {
104623             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
104624             var statements;
104625             statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
104626             /*modifiers*/ undefined, factory.createVariableDeclarationList([
104627                 factory.createVariableDeclaration(factory.cloneNode(node.name), 
104628                 /*exclamationToken*/ undefined, 
104629                 /*type*/ undefined, createRequireCall(node))
104630             ], 
104631             /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
104632             statements = appendExportsOfImportEqualsDeclaration(statements, node);
104633             return ts.singleOrMany(statements);
104634         }
104635         function appendExportsOfImportEqualsDeclaration(statements, node) {
104636             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
104637                 statements = ts.append(statements, factory.createExportDeclaration(
104638                 /*decorators*/ undefined, 
104639                 /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))])));
104640             }
104641             return statements;
104642         }
104643         function visitExportAssignment(node) {
104644             // Elide `export=` as it is not legal with --module ES6
104645             return node.isExportEquals ? undefined : node;
104646         }
104647         function visitExportDeclaration(node) {
104648             // `export * as ns` only needs to be transformed in ES2015
104649             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
104650                 return node;
104651             }
104652             // Either ill-formed or don't need to be tranformed.
104653             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
104654                 return node;
104655             }
104656             var oldIdentifier = node.exportClause.name;
104657             var synthName = factory.getGeneratedNameForNode(oldIdentifier);
104658             var importDecl = factory.createImportDeclaration(
104659             /*decorators*/ undefined, 
104660             /*modifiers*/ undefined, factory.createImportClause(
104661             /*isTypeOnly*/ false, 
104662             /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause);
104663             ts.setOriginalNode(importDecl, node.exportClause);
104664             var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(
104665             /*decorators*/ undefined, 
104666             /*modifiers*/ undefined, 
104667             /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)]));
104668             ts.setOriginalNode(exportDecl, node);
104669             return [importDecl, exportDecl];
104670         }
104671         //
104672         // Emit Notification
104673         //
104674         /**
104675          * Hook for node emit.
104676          *
104677          * @param hint A hint as to the intended usage of the node.
104678          * @param node The node to emit.
104679          * @param emit A callback used to emit the node in the printer.
104680          */
104681         function onEmitNode(hint, node, emitCallback) {
104682             if (ts.isSourceFile(node)) {
104683                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
104684                     helperNameSubstitutions = new ts.Map();
104685                 }
104686                 previousOnEmitNode(hint, node, emitCallback);
104687                 helperNameSubstitutions = undefined;
104688             }
104689             else {
104690                 previousOnEmitNode(hint, node, emitCallback);
104691             }
104692         }
104693         //
104694         // Substitutions
104695         //
104696         /**
104697          * Hooks node substitutions.
104698          *
104699          * @param hint A hint as to the intended usage of the node.
104700          * @param node The node to substitute.
104701          */
104702         function onSubstituteNode(hint, node) {
104703             node = previousOnSubstituteNode(hint, node);
104704             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
104705                 return substituteHelperName(node);
104706             }
104707             return node;
104708         }
104709         function substituteHelperName(node) {
104710             var name = ts.idText(node);
104711             var substitution = helperNameSubstitutions.get(name);
104712             if (!substitution) {
104713                 helperNameSubstitutions.set(name, substitution = factory.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
104714             }
104715             return substitution;
104716         }
104717     }
104718     ts.transformECMAScriptModule = transformECMAScriptModule;
104719 })(ts || (ts = {}));
104720 /*@internal*/
104721 var ts;
104722 (function (ts) {
104723     function transformNodeModule(context) {
104724         var previousOnSubstituteNode = context.onSubstituteNode;
104725         var previousOnEmitNode = context.onEmitNode;
104726         var esmTransform = ts.transformECMAScriptModule(context);
104727         var esmOnSubstituteNode = context.onSubstituteNode;
104728         var esmOnEmitNode = context.onEmitNode;
104729         context.onSubstituteNode = previousOnSubstituteNode;
104730         context.onEmitNode = previousOnEmitNode;
104731         var cjsTransform = ts.transformModule(context);
104732         var cjsOnSubstituteNode = context.onSubstituteNode;
104733         var cjsOnEmitNode = context.onEmitNode;
104734         context.onSubstituteNode = onSubstituteNode;
104735         context.onEmitNode = onEmitNode;
104736         context.enableSubstitution(303 /* SourceFile */);
104737         context.enableEmitNotification(303 /* SourceFile */);
104738         var currentSourceFile;
104739         return transformSourceFileOrBundle;
104740         function onSubstituteNode(hint, node) {
104741             if (ts.isSourceFile(node)) {
104742                 currentSourceFile = node;
104743                 // Neither component transform wants substitution notifications for `SourceFile`s, and, in fact, relies on
104744                 // the source file emit notification to setup scope variables for substitutions (so we _cannot_ call their substitute
104745                 // functions on source files safely, as that context only gets setup in a later pipeline phase!)
104746                 return previousOnSubstituteNode(hint, node);
104747             }
104748             else {
104749                 if (!currentSourceFile) {
104750                     return previousOnSubstituteNode(hint, node);
104751                 }
104752                 if (currentSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) {
104753                     return esmOnSubstituteNode(hint, node);
104754                 }
104755                 return cjsOnSubstituteNode(hint, node);
104756             }
104757         }
104758         function onEmitNode(hint, node, emitCallback) {
104759             if (ts.isSourceFile(node)) {
104760                 currentSourceFile = node;
104761             }
104762             if (!currentSourceFile) {
104763                 return previousOnEmitNode(hint, node, emitCallback);
104764             }
104765             if (currentSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) {
104766                 return esmOnEmitNode(hint, node, emitCallback);
104767             }
104768             return cjsOnEmitNode(hint, node, emitCallback);
104769         }
104770         function getModuleTransformForFile(file) {
104771             return file.impliedNodeFormat === ts.ModuleKind.ESNext ? esmTransform : cjsTransform;
104772         }
104773         function transformSourceFile(node) {
104774             if (node.isDeclarationFile) {
104775                 return node;
104776             }
104777             currentSourceFile = node;
104778             var result = getModuleTransformForFile(node)(node);
104779             currentSourceFile = undefined;
104780             ts.Debug.assert(ts.isSourceFile(result));
104781             return result;
104782         }
104783         function transformSourceFileOrBundle(node) {
104784             return node.kind === 303 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
104785         }
104786         function transformBundle(node) {
104787             return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
104788         }
104789     }
104790     ts.transformNodeModule = transformNodeModule;
104791 })(ts || (ts = {}));
104792 /* @internal */
104793 var ts;
104794 (function (ts) {
104795     function canProduceDiagnostics(node) {
104796         return ts.isVariableDeclaration(node) ||
104797             ts.isPropertyDeclaration(node) ||
104798             ts.isPropertySignature(node) ||
104799             ts.isBindingElement(node) ||
104800             ts.isSetAccessor(node) ||
104801             ts.isGetAccessor(node) ||
104802             ts.isConstructSignatureDeclaration(node) ||
104803             ts.isCallSignatureDeclaration(node) ||
104804             ts.isMethodDeclaration(node) ||
104805             ts.isMethodSignature(node) ||
104806             ts.isFunctionDeclaration(node) ||
104807             ts.isParameter(node) ||
104808             ts.isTypeParameterDeclaration(node) ||
104809             ts.isExpressionWithTypeArguments(node) ||
104810             ts.isImportEqualsDeclaration(node) ||
104811             ts.isTypeAliasDeclaration(node) ||
104812             ts.isConstructorDeclaration(node) ||
104813             ts.isIndexSignatureDeclaration(node) ||
104814             ts.isPropertyAccessExpression(node) ||
104815             ts.isJSDocTypeAlias(node);
104816     }
104817     ts.canProduceDiagnostics = canProduceDiagnostics;
104818     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
104819         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
104820             return getAccessorNameVisibilityError;
104821         }
104822         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
104823             return getMethodNameVisibilityError;
104824         }
104825         else {
104826             return createGetSymbolAccessibilityDiagnosticForNode(node);
104827         }
104828         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
104829             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
104830             return diagnosticMessage !== undefined ? {
104831                 diagnosticMessage: diagnosticMessage,
104832                 errorNode: node,
104833                 typeName: node.name
104834             } : undefined;
104835         }
104836         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
104837             if (ts.isStatic(node)) {
104838                 return symbolAccessibilityResult.errorModuleName ?
104839                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104840                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104841                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104842                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
104843             }
104844             else if (node.parent.kind === 256 /* ClassDeclaration */) {
104845                 return symbolAccessibilityResult.errorModuleName ?
104846                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104847                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104848                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104849                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
104850             }
104851             else {
104852                 return symbolAccessibilityResult.errorModuleName ?
104853                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
104854                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
104855             }
104856         }
104857         function getMethodNameVisibilityError(symbolAccessibilityResult) {
104858             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
104859             return diagnosticMessage !== undefined ? {
104860                 diagnosticMessage: diagnosticMessage,
104861                 errorNode: node,
104862                 typeName: node.name
104863             } : undefined;
104864         }
104865         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
104866             if (ts.isStatic(node)) {
104867                 return symbolAccessibilityResult.errorModuleName ?
104868                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104869                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104870                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104871                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
104872             }
104873             else if (node.parent.kind === 256 /* ClassDeclaration */) {
104874                 return symbolAccessibilityResult.errorModuleName ?
104875                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104876                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104877                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104878                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
104879             }
104880             else {
104881                 return symbolAccessibilityResult.errorModuleName ?
104882                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
104883                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
104884             }
104885         }
104886     }
104887     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
104888     function createGetSymbolAccessibilityDiagnosticForNode(node) {
104889         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
104890             return getVariableDeclarationTypeVisibilityError;
104891         }
104892         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
104893             return getAccessorDeclarationTypeVisibilityError;
104894         }
104895         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
104896             return getReturnTypeVisibilityError;
104897         }
104898         else if (ts.isParameter(node)) {
104899             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasSyntacticModifier(node.parent, 8 /* Private */)) {
104900                 return getVariableDeclarationTypeVisibilityError;
104901             }
104902             return getParameterDeclarationTypeVisibilityError;
104903         }
104904         else if (ts.isTypeParameterDeclaration(node)) {
104905             return getTypeParameterConstraintVisibilityError;
104906         }
104907         else if (ts.isExpressionWithTypeArguments(node)) {
104908             return getHeritageClauseVisibilityError;
104909         }
104910         else if (ts.isImportEqualsDeclaration(node)) {
104911             return getImportEntityNameVisibilityError;
104912         }
104913         else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) {
104914             return getTypeAliasDeclarationVisibilityError;
104915         }
104916         else {
104917             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind]));
104918         }
104919         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
104920             if (node.kind === 253 /* VariableDeclaration */ || node.kind === 202 /* BindingElement */) {
104921                 return symbolAccessibilityResult.errorModuleName ?
104922                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104923                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104924                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
104925                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
104926             }
104927             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
104928             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
104929             else if (node.kind === 166 /* PropertyDeclaration */ || node.kind === 205 /* PropertyAccessExpression */ || node.kind === 165 /* PropertySignature */ ||
104930                 (node.kind === 163 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) {
104931                 // TODO(jfreeman): Deal with computed properties in error reporting.
104932                 if (ts.isStatic(node)) {
104933                     return symbolAccessibilityResult.errorModuleName ?
104934                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104935                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104936                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104937                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
104938                 }
104939                 else if (node.parent.kind === 256 /* ClassDeclaration */ || node.kind === 163 /* Parameter */) {
104940                     return symbolAccessibilityResult.errorModuleName ?
104941                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104942                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
104943                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
104944                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
104945                 }
104946                 else {
104947                     // Interfaces cannot have types that cannot be named
104948                     return symbolAccessibilityResult.errorModuleName ?
104949                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
104950                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
104951                 }
104952             }
104953         }
104954         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
104955             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
104956             return diagnosticMessage !== undefined ? {
104957                 diagnosticMessage: diagnosticMessage,
104958                 errorNode: node,
104959                 typeName: node.name
104960             } : undefined;
104961         }
104962         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
104963             var diagnosticMessage;
104964             if (node.kind === 172 /* SetAccessor */) {
104965                 // Getters can infer the return type from the returned expression, but setters cannot, so the
104966                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
104967                 if (ts.isStatic(node)) {
104968                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
104969                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
104970                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
104971                 }
104972                 else {
104973                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
104974                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
104975                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
104976                 }
104977             }
104978             else {
104979                 if (ts.isStatic(node)) {
104980                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
104981                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104982                             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 :
104983                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
104984                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
104985                 }
104986                 else {
104987                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
104988                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
104989                             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 :
104990                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
104991                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
104992                 }
104993             }
104994             return {
104995                 diagnosticMessage: diagnosticMessage,
104996                 errorNode: node.name,
104997                 typeName: node.name
104998             };
104999         }
105000         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
105001             var diagnosticMessage;
105002             switch (node.kind) {
105003                 case 174 /* ConstructSignature */:
105004                     // Interfaces cannot have return types that cannot be named
105005                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105006                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
105007                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
105008                     break;
105009                 case 173 /* CallSignature */:
105010                     // Interfaces cannot have return types that cannot be named
105011                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105012                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
105013                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
105014                     break;
105015                 case 175 /* IndexSignature */:
105016                     // Interfaces cannot have return types that cannot be named
105017                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105018                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
105019                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
105020                     break;
105021                 case 168 /* MethodDeclaration */:
105022                 case 167 /* MethodSignature */:
105023                     if (ts.isStatic(node)) {
105024                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105025                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105026                                 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 :
105027                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
105028                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
105029                     }
105030                     else if (node.parent.kind === 256 /* ClassDeclaration */) {
105031                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105032                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105033                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
105034                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
105035                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
105036                     }
105037                     else {
105038                         // Interfaces cannot have return types that cannot be named
105039                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105040                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
105041                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
105042                     }
105043                     break;
105044                 case 255 /* FunctionDeclaration */:
105045                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
105046                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105047                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
105048                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
105049                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
105050                     break;
105051                 default:
105052                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
105053             }
105054             return {
105055                 diagnosticMessage: diagnosticMessage,
105056                 errorNode: node.name || node
105057             };
105058         }
105059         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
105060             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
105061             return diagnosticMessage !== undefined ? {
105062                 diagnosticMessage: diagnosticMessage,
105063                 errorNode: node,
105064                 typeName: node.name
105065             } : undefined;
105066         }
105067         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
105068             switch (node.parent.kind) {
105069                 case 170 /* Constructor */:
105070                     return symbolAccessibilityResult.errorModuleName ?
105071                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105072                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
105073                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
105074                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
105075                 case 174 /* ConstructSignature */:
105076                 case 179 /* ConstructorType */:
105077                     // Interfaces cannot have parameter types that cannot be named
105078                     return symbolAccessibilityResult.errorModuleName ?
105079                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
105080                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
105081                 case 173 /* CallSignature */:
105082                     // Interfaces cannot have parameter types that cannot be named
105083                     return symbolAccessibilityResult.errorModuleName ?
105084                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
105085                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
105086                 case 175 /* IndexSignature */:
105087                     // Interfaces cannot have parameter types that cannot be named
105088                     return symbolAccessibilityResult.errorModuleName ?
105089                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
105090                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
105091                 case 168 /* MethodDeclaration */:
105092                 case 167 /* MethodSignature */:
105093                     if (ts.isStatic(node.parent)) {
105094                         return symbolAccessibilityResult.errorModuleName ?
105095                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105096                                 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 :
105097                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
105098                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
105099                     }
105100                     else if (node.parent.parent.kind === 256 /* ClassDeclaration */) {
105101                         return symbolAccessibilityResult.errorModuleName ?
105102                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105103                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
105104                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
105105                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
105106                     }
105107                     else {
105108                         // Interfaces cannot have parameter types that cannot be named
105109                         return symbolAccessibilityResult.errorModuleName ?
105110                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
105111                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
105112                     }
105113                 case 255 /* FunctionDeclaration */:
105114                 case 178 /* FunctionType */:
105115                     return symbolAccessibilityResult.errorModuleName ?
105116                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105117                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
105118                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
105119                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
105120                 case 172 /* SetAccessor */:
105121                 case 171 /* GetAccessor */:
105122                     return symbolAccessibilityResult.errorModuleName ?
105123                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
105124                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
105125                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
105126                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
105127                 default:
105128                     return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind]));
105129             }
105130         }
105131         function getTypeParameterConstraintVisibilityError() {
105132             // Type parameter constraints are named by user so we should always be able to name it
105133             var diagnosticMessage;
105134             switch (node.parent.kind) {
105135                 case 256 /* ClassDeclaration */:
105136                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
105137                     break;
105138                 case 257 /* InterfaceDeclaration */:
105139                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
105140                     break;
105141                 case 194 /* MappedType */:
105142                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
105143                     break;
105144                 case 179 /* ConstructorType */:
105145                 case 174 /* ConstructSignature */:
105146                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
105147                     break;
105148                 case 173 /* CallSignature */:
105149                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
105150                     break;
105151                 case 168 /* MethodDeclaration */:
105152                 case 167 /* MethodSignature */:
105153                     if (ts.isStatic(node.parent)) {
105154                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
105155                     }
105156                     else if (node.parent.parent.kind === 256 /* ClassDeclaration */) {
105157                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
105158                     }
105159                     else {
105160                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
105161                     }
105162                     break;
105163                 case 178 /* FunctionType */:
105164                 case 255 /* FunctionDeclaration */:
105165                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
105166                     break;
105167                 case 258 /* TypeAliasDeclaration */:
105168                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
105169                     break;
105170                 default:
105171                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
105172             }
105173             return {
105174                 diagnosticMessage: diagnosticMessage,
105175                 errorNode: node,
105176                 typeName: node.name
105177             };
105178         }
105179         function getHeritageClauseVisibilityError() {
105180             var diagnosticMessage;
105181             // Heritage clause is written by user so it can always be named
105182             if (ts.isClassDeclaration(node.parent.parent)) {
105183                 // Class or Interface implemented/extended is inaccessible
105184                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 117 /* ImplementsKeyword */ ?
105185                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
105186                     node.parent.parent.name ? ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 :
105187                         ts.Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
105188             }
105189             else {
105190                 // interface is inaccessible
105191                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
105192             }
105193             return {
105194                 diagnosticMessage: diagnosticMessage,
105195                 errorNode: node,
105196                 typeName: ts.getNameOfDeclaration(node.parent.parent)
105197             };
105198         }
105199         function getImportEntityNameVisibilityError() {
105200             return {
105201                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
105202                 errorNode: node,
105203                 typeName: node.name
105204             };
105205         }
105206         function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) {
105207             return {
105208                 diagnosticMessage: symbolAccessibilityResult.errorModuleName
105209                     ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2
105210                     : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
105211                 errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type,
105212                 typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name,
105213             };
105214         }
105215     }
105216     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
105217 })(ts || (ts = {}));
105218 /*@internal*/
105219 var ts;
105220 (function (ts) {
105221     function getDeclarationDiagnostics(host, resolver, file) {
105222         var compilerOptions = host.getCompilerOptions();
105223         var result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
105224         return result.diagnostics;
105225     }
105226     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
105227     function hasInternalAnnotation(range, currentSourceFile) {
105228         var comment = currentSourceFile.text.substring(range.pos, range.end);
105229         return ts.stringContains(comment, "@internal");
105230     }
105231     function isInternalDeclaration(node, currentSourceFile) {
105232         var parseTreeNode = ts.getParseTreeNode(node);
105233         if (parseTreeNode && parseTreeNode.kind === 163 /* Parameter */) {
105234             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
105235             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
105236             var text = currentSourceFile.text;
105237             var commentRanges = previousSibling
105238                 ? ts.concatenate(
105239                 // to handle
105240                 // ... parameters, /* @internal */
105241                 // public param: string
105242                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
105243                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
105244             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
105245         }
105246         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
105247         return !!ts.forEach(leadingCommentRanges, function (range) {
105248             return hasInternalAnnotation(range, currentSourceFile);
105249         });
105250     }
105251     ts.isInternalDeclaration = isInternalDeclaration;
105252     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
105253         2048 /* WriteClassExpressionAsTypeLiteral */ |
105254         4096 /* UseTypeOfFunction */ |
105255         8 /* UseStructuralFallback */ |
105256         524288 /* AllowEmptyTuple */ |
105257         4 /* GenerateNamesForShadowedTypeParams */ |
105258         1 /* NoTruncation */;
105259     /**
105260      * Transforms a ts file into a .d.ts file
105261      * This process requires type information, which is retrieved through the emit resolver. Because of this,
105262      * in many places this transformer assumes it will be operating on parse tree nodes directly.
105263      * This means that _no transforms should be allowed to occur before this one_.
105264      */
105265     function transformDeclarations(context) {
105266         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
105267         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
105268         var needsDeclare = true;
105269         var isBundledEmit = false;
105270         var resultHasExternalModuleIndicator = false;
105271         var needsScopeFixMarker = false;
105272         var resultHasScopeMarker = false;
105273         var enclosingDeclaration;
105274         var necessaryTypeReferences;
105275         var lateMarkedStatements;
105276         var lateStatementReplacementMap;
105277         var suppressNewDiagnosticContexts;
105278         var exportedModulesFromDeclarationEmit;
105279         var factory = context.factory;
105280         var host = context.getEmitHost();
105281         var symbolTracker = {
105282             trackSymbol: trackSymbol,
105283             reportInaccessibleThisError: reportInaccessibleThisError,
105284             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
105285             reportCyclicStructureError: reportCyclicStructureError,
105286             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
105287             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
105288             reportTruncationError: reportTruncationError,
105289             moduleResolverHost: host,
105290             trackReferencedAmbientModule: trackReferencedAmbientModule,
105291             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
105292             reportNonlocalAugmentation: reportNonlocalAugmentation,
105293             reportNonSerializableProperty: reportNonSerializableProperty
105294         };
105295         var errorNameNode;
105296         var errorFallbackNode;
105297         var currentSourceFile;
105298         var refs;
105299         var libs;
105300         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
105301         var resolver = context.getEmitResolver();
105302         var options = context.getCompilerOptions();
105303         var noResolve = options.noResolve, stripInternal = options.stripInternal;
105304         return transformRoot;
105305         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
105306             if (!typeReferenceDirectives) {
105307                 return;
105308             }
105309             necessaryTypeReferences = necessaryTypeReferences || new ts.Set();
105310             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
105311                 var ref = typeReferenceDirectives_2[_i];
105312                 necessaryTypeReferences.add(ref);
105313             }
105314         }
105315         function trackReferencedAmbientModule(node, symbol) {
105316             // If it is visible via `// <reference types="..."/>`, then we should just use that
105317             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
105318             if (ts.length(directives)) {
105319                 return recordTypeReferenceDirectivesIfNecessary(directives);
105320             }
105321             // Otherwise we should emit a path-based reference
105322             var container = ts.getSourceFileOfNode(node);
105323             refs.set(ts.getOriginalNodeId(container), container);
105324         }
105325         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
105326             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
105327                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
105328                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
105329                     if (!lateMarkedStatements) {
105330                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
105331                     }
105332                     else {
105333                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
105334                             var ref = _a[_i];
105335                             ts.pushIfUnique(lateMarkedStatements, ref);
105336                         }
105337                     }
105338                 }
105339                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
105340             }
105341             else {
105342                 // Report error
105343                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
105344                 if (errorInfo) {
105345                     if (errorInfo.typeName) {
105346                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
105347                     }
105348                     else {
105349                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
105350                     }
105351                     return true;
105352                 }
105353             }
105354             return false;
105355         }
105356         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
105357             if (!isBundledEmit) {
105358                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
105359             }
105360         }
105361         function trackSymbol(symbol, enclosingDeclaration, meaning) {
105362             if (symbol.flags & 262144 /* TypeParameter */)
105363                 return false;
105364             var issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
105365             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
105366             return issuedDiagnostic;
105367         }
105368         function reportPrivateInBaseOfClassExpression(propertyName) {
105369             if (errorNameNode || errorFallbackNode) {
105370                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
105371             }
105372         }
105373         function errorDeclarationNameWithFallback() {
105374             return errorNameNode ? ts.declarationNameToString(errorNameNode) :
105375                 errorFallbackNode && ts.getNameOfDeclaration(errorFallbackNode) ? ts.declarationNameToString(ts.getNameOfDeclaration(errorFallbackNode)) :
105376                     errorFallbackNode && ts.isExportAssignment(errorFallbackNode) ? errorFallbackNode.isExportEquals ? "export=" : "default" :
105377                         "(Missing)"; // same fallback declarationNameToString uses when node is zero-width (ie, nameless)
105378         }
105379         function reportInaccessibleUniqueSymbolError() {
105380             if (errorNameNode || errorFallbackNode) {
105381                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "unique symbol"));
105382             }
105383         }
105384         function reportCyclicStructureError() {
105385             if (errorNameNode || errorFallbackNode) {
105386                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, errorDeclarationNameWithFallback()));
105387             }
105388         }
105389         function reportInaccessibleThisError() {
105390             if (errorNameNode || errorFallbackNode) {
105391                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "this"));
105392             }
105393         }
105394         function reportLikelyUnsafeImportRequiredError(specifier) {
105395             if (errorNameNode || errorFallbackNode) {
105396                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), 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, errorDeclarationNameWithFallback(), specifier));
105397             }
105398         }
105399         function reportTruncationError() {
105400             if (errorNameNode || errorFallbackNode) {
105401                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
105402             }
105403         }
105404         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
105405             var _a;
105406             var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
105407             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
105408             if (augmentingDeclarations) {
105409                 for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
105410                     var augmentations = augmentingDeclarations_1[_i];
105411                     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)));
105412                 }
105413             }
105414         }
105415         function reportNonSerializableProperty(propertyName) {
105416             if (errorNameNode || errorFallbackNode) {
105417                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName));
105418             }
105419         }
105420         function transformDeclarationsForJS(sourceFile, bundled) {
105421             var oldDiag = getSymbolAccessibilityDiagnostic;
105422             getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({
105423                 diagnosticMessage: s.errorModuleName
105424                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
105425                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
105426                 errorNode: s.errorNode || sourceFile
105427             })); };
105428             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
105429             getSymbolAccessibilityDiagnostic = oldDiag;
105430             return result;
105431         }
105432         function transformRoot(node) {
105433             if (node.kind === 303 /* SourceFile */ && node.isDeclarationFile) {
105434                 return node;
105435             }
105436             if (node.kind === 304 /* Bundle */) {
105437                 isBundledEmit = true;
105438                 refs = new ts.Map();
105439                 libs = new ts.Map();
105440                 var hasNoDefaultLib_1 = false;
105441                 var bundle = factory.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
105442                     if (sourceFile.isDeclarationFile)
105443                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
105444                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
105445                     currentSourceFile = sourceFile;
105446                     enclosingDeclaration = sourceFile;
105447                     lateMarkedStatements = undefined;
105448                     suppressNewDiagnosticContexts = false;
105449                     lateStatementReplacementMap = new ts.Map();
105450                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
105451                     needsScopeFixMarker = false;
105452                     resultHasScopeMarker = false;
105453                     collectReferences(sourceFile, refs);
105454                     collectLibs(sourceFile, libs);
105455                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
105456                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
105457                         needsDeclare = false;
105458                         var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
105459                         var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* 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*/ []);
105460                         return newFile;
105461                     }
105462                     needsDeclare = true;
105463                     var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
105464                     return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
105465                 }), ts.mapDefined(node.prepends, function (prepend) {
105466                     if (prepend.kind === 306 /* InputFiles */) {
105467                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
105468                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
105469                         collectReferences(sourceFile, refs);
105470                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
105471                         collectLibs(sourceFile, libs);
105472                         return sourceFile;
105473                     }
105474                     return prepend;
105475                 }));
105476                 bundle.syntheticFileReferences = [];
105477                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
105478                 bundle.syntheticLibReferences = getLibReferences();
105479                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
105480                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
105481                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
105482                 refs.forEach(referenceVisitor_1);
105483                 return bundle;
105484             }
105485             // Single source file
105486             needsDeclare = true;
105487             needsScopeFixMarker = false;
105488             resultHasScopeMarker = false;
105489             enclosingDeclaration = node;
105490             currentSourceFile = node;
105491             getSymbolAccessibilityDiagnostic = throwDiagnostic;
105492             isBundledEmit = false;
105493             resultHasExternalModuleIndicator = false;
105494             suppressNewDiagnosticContexts = false;
105495             lateMarkedStatements = undefined;
105496             lateStatementReplacementMap = new ts.Map();
105497             necessaryTypeReferences = undefined;
105498             refs = collectReferences(currentSourceFile, new ts.Map());
105499             libs = collectLibs(currentSourceFile, new ts.Map());
105500             var references = [];
105501             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
105502             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
105503             var combinedStatements;
105504             if (ts.isSourceFileJS(currentSourceFile)) {
105505                 combinedStatements = factory.createNodeArray(transformDeclarationsForJS(node));
105506                 refs.forEach(referenceVisitor);
105507                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
105508             }
105509             else {
105510                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
105511                 combinedStatements = ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
105512                 refs.forEach(referenceVisitor);
105513                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
105514                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
105515                     combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], combinedStatements, true), [ts.createEmptyExports(factory)], false)), combinedStatements);
105516                 }
105517             }
105518             var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
105519             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
105520             return updated;
105521             function getLibReferences() {
105522                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
105523             }
105524             function getFileReferencesForUsedTypeReferences() {
105525                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
105526             }
105527             function getFileReferenceForTypeName(typeName) {
105528                 // Elide type references for which we have imports
105529                 if (emittedImports) {
105530                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
105531                         var importStatement = emittedImports_1[_i];
105532                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
105533                             var expr = importStatement.moduleReference.expression;
105534                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
105535                                 return undefined;
105536                             }
105537                         }
105538                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
105539                             return undefined;
105540                         }
105541                     }
105542                 }
105543                 return { fileName: typeName, pos: -1, end: -1 };
105544             }
105545             function mapReferencesIntoArray(references, outputFilePath) {
105546                 return function (file) {
105547                     var declFileName;
105548                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
105549                         declFileName = file.fileName;
105550                     }
105551                     else {
105552                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
105553                             return; // Omit references to files which are being merged
105554                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
105555                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
105556                     }
105557                     if (declFileName) {
105558                         var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host);
105559                         if (!ts.pathIsRelative(specifier)) {
105560                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
105561                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
105562                             // a relative path to the declaration file
105563                             recordTypeReferenceDirectivesIfNecessary([specifier]);
105564                             return;
105565                         }
105566                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
105567                         /*isAbsolutePathAnUrl*/ false);
105568                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
105569                             fileName = fileName.substring(2);
105570                         }
105571                         // omit references to files from node_modules (npm may disambiguate module
105572                         // references when installing this package, making the path is unreliable).
105573                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
105574                             return;
105575                         }
105576                         references.push({ pos: -1, end: -1, fileName: fileName });
105577                     }
105578                 };
105579             }
105580         }
105581         function collectReferences(sourceFile, ret) {
105582             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
105583                 return ret;
105584             ts.forEach(sourceFile.referencedFiles, function (f) {
105585                 var elem = host.getSourceFileFromReference(sourceFile, f);
105586                 if (elem) {
105587                     ret.set(ts.getOriginalNodeId(elem), elem);
105588                 }
105589             });
105590             return ret;
105591         }
105592         function collectLibs(sourceFile, ret) {
105593             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
105594                 var lib = host.getLibFileFromReference(ref);
105595                 if (lib) {
105596                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
105597                 }
105598             });
105599             return ret;
105600         }
105601         function filterBindingPatternInitializers(name) {
105602             if (name.kind === 79 /* Identifier */) {
105603                 return name;
105604             }
105605             else {
105606                 if (name.kind === 201 /* ArrayBindingPattern */) {
105607                     return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
105608                 }
105609                 else {
105610                     return factory.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
105611                 }
105612             }
105613             function visitBindingElement(elem) {
105614                 if (elem.kind === 226 /* OmittedExpression */) {
105615                     return elem;
105616                 }
105617                 return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
105618             }
105619         }
105620         function ensureParameter(p, modifierMask, type) {
105621             var oldDiag;
105622             if (!suppressNewDiagnosticContexts) {
105623                 oldDiag = getSymbolAccessibilityDiagnostic;
105624                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
105625             }
105626             var newParam = factory.updateParameterDeclaration(p, 
105627             /*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
105628             ensureNoInitializer(p));
105629             if (!suppressNewDiagnosticContexts) {
105630                 getSymbolAccessibilityDiagnostic = oldDiag;
105631             }
105632             return newParam;
105633         }
105634         function shouldPrintWithInitializer(node) {
105635             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
105636         }
105637         function ensureNoInitializer(node) {
105638             if (shouldPrintWithInitializer(node)) {
105639                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
105640             }
105641             return undefined;
105642         }
105643         function ensureType(node, type, ignorePrivate) {
105644             if (!ignorePrivate && ts.hasEffectiveModifier(node, 8 /* Private */)) {
105645                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
105646                 return;
105647             }
105648             if (shouldPrintWithInitializer(node)) {
105649                 // Literal const declarations will have an initializer ensured rather than a type
105650                 return;
105651             }
105652             var shouldUseResolverType = node.kind === 163 /* Parameter */ &&
105653                 (resolver.isRequiredInitializedParameter(node) ||
105654                     resolver.isOptionalUninitializedParameterProperty(node));
105655             if (type && !shouldUseResolverType) {
105656                 return ts.visitNode(type, visitDeclarationSubtree);
105657             }
105658             if (!ts.getParseTreeNode(node)) {
105659                 return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(130 /* AnyKeyword */);
105660             }
105661             if (node.kind === 172 /* SetAccessor */) {
105662                 // 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
105663                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
105664                 return factory.createKeywordTypeNode(130 /* AnyKeyword */);
105665             }
105666             errorNameNode = node.name;
105667             var oldDiag;
105668             if (!suppressNewDiagnosticContexts) {
105669                 oldDiag = getSymbolAccessibilityDiagnostic;
105670                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
105671             }
105672             if (node.kind === 253 /* VariableDeclaration */ || node.kind === 202 /* BindingElement */) {
105673                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
105674             }
105675             if (node.kind === 163 /* Parameter */
105676                 || node.kind === 166 /* PropertyDeclaration */
105677                 || node.kind === 165 /* PropertySignature */) {
105678                 if (!node.initializer)
105679                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
105680                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
105681             }
105682             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
105683             function cleanup(returnValue) {
105684                 errorNameNode = undefined;
105685                 if (!suppressNewDiagnosticContexts) {
105686                     getSymbolAccessibilityDiagnostic = oldDiag;
105687                 }
105688                 return returnValue || factory.createKeywordTypeNode(130 /* AnyKeyword */);
105689             }
105690         }
105691         function isDeclarationAndNotVisible(node) {
105692             node = ts.getParseTreeNode(node);
105693             switch (node.kind) {
105694                 case 255 /* FunctionDeclaration */:
105695                 case 260 /* ModuleDeclaration */:
105696                 case 257 /* InterfaceDeclaration */:
105697                 case 256 /* ClassDeclaration */:
105698                 case 258 /* TypeAliasDeclaration */:
105699                 case 259 /* EnumDeclaration */:
105700                     return !resolver.isDeclarationVisible(node);
105701                 // The following should be doing their own visibility checks based on filtering their members
105702                 case 253 /* VariableDeclaration */:
105703                     return !getBindingNameVisible(node);
105704                 case 264 /* ImportEqualsDeclaration */:
105705                 case 265 /* ImportDeclaration */:
105706                 case 271 /* ExportDeclaration */:
105707                 case 270 /* ExportAssignment */:
105708                     return false;
105709                 case 169 /* ClassStaticBlockDeclaration */:
105710                     return true;
105711             }
105712             return false;
105713         }
105714         // If the ExpandoFunctionDeclaration have multiple overloads, then we only need to emit properties for the last one.
105715         function shouldEmitFunctionProperties(input) {
105716             var _a;
105717             if (input.body) {
105718                 return true;
105719             }
105720             var overloadSignatures = (_a = input.symbol.declarations) === null || _a === void 0 ? void 0 : _a.filter(function (decl) { return ts.isFunctionDeclaration(decl) && !decl.body; });
105721             return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1;
105722         }
105723         function getBindingNameVisible(elem) {
105724             if (ts.isOmittedExpression(elem)) {
105725                 return false;
105726             }
105727             if (ts.isBindingPattern(elem.name)) {
105728                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
105729                 return ts.some(elem.name.elements, getBindingNameVisible);
105730             }
105731             else {
105732                 return resolver.isDeclarationVisible(elem);
105733             }
105734         }
105735         function updateParamsList(node, params, modifierMask) {
105736             if (ts.hasEffectiveModifier(node, 8 /* Private */)) {
105737                 return undefined; // TODO: GH#18217
105738             }
105739             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
105740             if (!newParams) {
105741                 return undefined; // TODO: GH#18217
105742             }
105743             return factory.createNodeArray(newParams, params.hasTrailingComma);
105744         }
105745         function updateAccessorParamsList(input, isPrivate) {
105746             var newParams;
105747             if (!isPrivate) {
105748                 var thisParameter = ts.getThisParameter(input);
105749                 if (thisParameter) {
105750                     newParams = [ensureParameter(thisParameter)];
105751                 }
105752             }
105753             if (ts.isSetAccessorDeclaration(input)) {
105754                 var newValueParameter = void 0;
105755                 if (!isPrivate) {
105756                     var valueParameter = ts.getSetAccessorValueParameter(input);
105757                     if (valueParameter) {
105758                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
105759                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
105760                     }
105761                 }
105762                 if (!newValueParameter) {
105763                     newValueParameter = factory.createParameterDeclaration(
105764                     /*decorators*/ undefined, 
105765                     /*modifiers*/ undefined, 
105766                     /*dotDotDotToken*/ undefined, "value");
105767                 }
105768                 newParams = ts.append(newParams, newValueParameter);
105769             }
105770             return factory.createNodeArray(newParams || ts.emptyArray);
105771         }
105772         function ensureTypeParams(node, params) {
105773             return ts.hasEffectiveModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
105774         }
105775         function isEnclosingDeclaration(node) {
105776             return ts.isSourceFile(node)
105777                 || ts.isTypeAliasDeclaration(node)
105778                 || ts.isModuleDeclaration(node)
105779                 || ts.isClassDeclaration(node)
105780                 || ts.isInterfaceDeclaration(node)
105781                 || ts.isFunctionLike(node)
105782                 || ts.isIndexSignatureDeclaration(node)
105783                 || ts.isMappedTypeNode(node);
105784         }
105785         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
105786             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
105787             handleSymbolAccessibilityError(visibilityResult);
105788             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
105789         }
105790         function preserveJsDoc(updated, original) {
105791             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
105792                 updated.jsDoc = original.jsDoc;
105793             }
105794             return ts.setCommentRange(updated, ts.getCommentRange(original));
105795         }
105796         function rewriteModuleSpecifier(parent, input) {
105797             if (!input)
105798                 return undefined; // TODO: GH#18217
105799             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 260 /* ModuleDeclaration */ && parent.kind !== 199 /* ImportType */);
105800             if (ts.isStringLiteralLike(input)) {
105801                 if (isBundledEmit) {
105802                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
105803                     if (newName) {
105804                         return factory.createStringLiteral(newName);
105805                     }
105806                 }
105807                 else {
105808                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
105809                     if (symbol) {
105810                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
105811                     }
105812                 }
105813             }
105814             return input;
105815         }
105816         function transformImportEqualsDeclaration(decl) {
105817             if (!resolver.isDeclarationVisible(decl))
105818                 return;
105819             if (decl.moduleReference.kind === 276 /* ExternalModuleReference */) {
105820                 // Rewrite external module names if necessary
105821                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
105822                 return factory.updateImportEqualsDeclaration(decl, 
105823                 /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
105824             }
105825             else {
105826                 var oldDiag = getSymbolAccessibilityDiagnostic;
105827                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
105828                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
105829                 getSymbolAccessibilityDiagnostic = oldDiag;
105830                 return decl;
105831             }
105832         }
105833         function transformImportDeclaration(decl) {
105834             if (!decl.importClause) {
105835                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
105836                 return factory.updateImportDeclaration(decl, 
105837                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), 
105838                 /*assertClause*/ undefined);
105839             }
105840             // The `importClause` visibility corresponds to the default's visibility.
105841             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
105842             if (!decl.importClause.namedBindings) {
105843                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
105844                 return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, 
105845                 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), /*assertClause*/ undefined);
105846             }
105847             if (decl.importClause.namedBindings.kind === 267 /* NamespaceImport */) {
105848                 // Namespace import (optionally with visible default)
105849                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
105850                 return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), /*assertClause*/ undefined) : undefined;
105851             }
105852             // Named imports (optionally with visible default)
105853             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
105854             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
105855                 return factory.updateImportDeclaration(decl, 
105856                 /*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), 
105857                 /*assertClause*/ undefined);
105858             }
105859             // Augmentation of export depends on import
105860             if (resolver.isImportRequiredByAugmentation(decl)) {
105861                 return factory.updateImportDeclaration(decl, 
105862                 /*decorators*/ undefined, decl.modifiers, 
105863                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), 
105864                 /*assertClause*/ undefined);
105865             }
105866             // Nothing visible
105867         }
105868         function transformAndReplaceLatePaintedStatements(statements) {
105869             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
105870             // error handling which must now be included in the output and themselves checked for errors.
105871             // For example:
105872             // ```
105873             // module A {
105874             //   export module Q {}
105875             //   import B = Q;
105876             //   import C = B;
105877             //   export import D = C;
105878             // }
105879             // ```
105880             // 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
105881             // 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
105882             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
105883             while (ts.length(lateMarkedStatements)) {
105884                 var i = lateMarkedStatements.shift();
105885                 if (!ts.isLateVisibilityPaintedStatement(i)) {
105886                     return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
105887                 }
105888                 var priorNeedsDeclare = needsDeclare;
105889                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
105890                 var result = transformTopLevelDeclaration(i);
105891                 needsDeclare = priorNeedsDeclare;
105892                 lateStatementReplacementMap.set(ts.getOriginalNodeId(i), result);
105893             }
105894             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
105895             // (and remove them from the set to examine for outter declarations)
105896             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
105897             function visitLateVisibilityMarkedStatements(statement) {
105898                 if (ts.isLateVisibilityPaintedStatement(statement)) {
105899                     var key = ts.getOriginalNodeId(statement);
105900                     if (lateStatementReplacementMap.has(key)) {
105901                         var result = lateStatementReplacementMap.get(key);
105902                         lateStatementReplacementMap.delete(key);
105903                         if (result) {
105904                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
105905                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
105906                                 needsScopeFixMarker = true;
105907                             }
105908                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
105909                                 resultHasExternalModuleIndicator = true;
105910                             }
105911                         }
105912                         return result;
105913                     }
105914                 }
105915                 return statement;
105916             }
105917         }
105918         function visitDeclarationSubtree(input) {
105919             if (shouldStripInternal(input))
105920                 return;
105921             if (ts.isDeclaration(input)) {
105922                 if (isDeclarationAndNotVisible(input))
105923                     return;
105924                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
105925                     return;
105926                 }
105927             }
105928             // Elide implementation signatures from overload sets
105929             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
105930                 return;
105931             // Elide semicolon class statements
105932             if (ts.isSemicolonClassElement(input))
105933                 return;
105934             var previousEnclosingDeclaration;
105935             if (isEnclosingDeclaration(input)) {
105936                 previousEnclosingDeclaration = enclosingDeclaration;
105937                 enclosingDeclaration = input;
105938             }
105939             var oldDiag = getSymbolAccessibilityDiagnostic;
105940             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
105941             // We'd see a TDZ violation at runtime
105942             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
105943             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
105944             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 181 /* TypeLiteral */ || input.kind === 194 /* MappedType */) && input.parent.kind !== 258 /* TypeAliasDeclaration */);
105945             // Emit methods which are private as properties with no type information
105946             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
105947                 if (ts.hasEffectiveModifier(input, 8 /* Private */)) {
105948                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
105949                         return; // Elide all but the first overload
105950                     return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
105951                 }
105952             }
105953             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
105954                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
105955             }
105956             if (ts.isTypeQueryNode(input)) {
105957                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
105958             }
105959             if (shouldEnterSuppressNewDiagnosticsContextContext) {
105960                 // 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.
105961                 suppressNewDiagnosticContexts = true;
105962             }
105963             if (isProcessedComponent(input)) {
105964                 switch (input.kind) {
105965                     case 227 /* ExpressionWithTypeArguments */: {
105966                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
105967                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
105968                         }
105969                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
105970                         return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
105971                     }
105972                     case 177 /* TypeReference */: {
105973                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
105974                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
105975                         return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
105976                     }
105977                     case 174 /* ConstructSignature */:
105978                         return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
105979                     case 170 /* Constructor */: {
105980                         // A constructor declaration may not have a type annotation
105981                         var ctor = factory.createConstructorDeclaration(
105982                         /*decorators*/ undefined, 
105983                         /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */), 
105984                         /*body*/ undefined);
105985                         return cleanup(ctor);
105986                     }
105987                     case 168 /* MethodDeclaration */: {
105988                         if (ts.isPrivateIdentifier(input.name)) {
105989                             return cleanup(/*returnValue*/ undefined);
105990                         }
105991                         var sig = factory.createMethodDeclaration(
105992                         /*decorators*/ undefined, ensureModifiers(input), 
105993                         /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
105994                         /*body*/ undefined);
105995                         return cleanup(sig);
105996                     }
105997                     case 171 /* GetAccessor */: {
105998                         if (ts.isPrivateIdentifier(input.name)) {
105999                             return cleanup(/*returnValue*/ undefined);
106000                         }
106001                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
106002                         return cleanup(factory.updateGetAccessorDeclaration(input, 
106003                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
106004                         /*body*/ undefined));
106005                     }
106006                     case 172 /* SetAccessor */: {
106007                         if (ts.isPrivateIdentifier(input.name)) {
106008                             return cleanup(/*returnValue*/ undefined);
106009                         }
106010                         return cleanup(factory.updateSetAccessorDeclaration(input, 
106011                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), 
106012                         /*body*/ undefined));
106013                     }
106014                     case 166 /* PropertyDeclaration */:
106015                         if (ts.isPrivateIdentifier(input.name)) {
106016                             return cleanup(/*returnValue*/ undefined);
106017                         }
106018                         return cleanup(factory.updatePropertyDeclaration(input, 
106019                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
106020                     case 165 /* PropertySignature */:
106021                         if (ts.isPrivateIdentifier(input.name)) {
106022                             return cleanup(/*returnValue*/ undefined);
106023                         }
106024                         return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type)));
106025                     case 167 /* MethodSignature */: {
106026                         if (ts.isPrivateIdentifier(input.name)) {
106027                             return cleanup(/*returnValue*/ undefined);
106028                         }
106029                         return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
106030                     }
106031                     case 173 /* CallSignature */: {
106032                         return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
106033                     }
106034                     case 175 /* IndexSignature */: {
106035                         return cleanup(factory.updateIndexSignature(input, 
106036                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* AnyKeyword */)));
106037                     }
106038                     case 253 /* VariableDeclaration */: {
106039                         if (ts.isBindingPattern(input.name)) {
106040                             return recreateBindingPattern(input.name);
106041                         }
106042                         shouldEnterSuppressNewDiagnosticsContextContext = true;
106043                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
106044                         return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
106045                     }
106046                     case 162 /* TypeParameter */: {
106047                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
106048                             return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
106049                         }
106050                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
106051                     }
106052                     case 188 /* ConditionalType */: {
106053                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
106054                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
106055                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
106056                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
106057                         var oldEnclosingDecl = enclosingDeclaration;
106058                         enclosingDeclaration = input.trueType;
106059                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
106060                         enclosingDeclaration = oldEnclosingDecl;
106061                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
106062                         return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
106063                     }
106064                     case 178 /* FunctionType */: {
106065                         return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
106066                     }
106067                     case 179 /* ConstructorType */: {
106068                         return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
106069                     }
106070                     case 199 /* ImportType */: {
106071                         if (!ts.isLiteralImportTypeNode(input))
106072                             return cleanup(input);
106073                         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));
106074                     }
106075                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind]));
106076                 }
106077             }
106078             if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) {
106079                 ts.setEmitFlags(input, 1 /* SingleLine */);
106080             }
106081             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
106082             function cleanup(returnValue) {
106083                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
106084                     checkName(input);
106085                 }
106086                 if (isEnclosingDeclaration(input)) {
106087                     enclosingDeclaration = previousEnclosingDeclaration;
106088                 }
106089                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
106090                     getSymbolAccessibilityDiagnostic = oldDiag;
106091                 }
106092                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
106093                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
106094                 }
106095                 if (returnValue === input) {
106096                     return returnValue;
106097                 }
106098                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
106099             }
106100         }
106101         function isPrivateMethodTypeParameter(node) {
106102             return node.parent.kind === 168 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */);
106103         }
106104         function visitDeclarationStatements(input) {
106105             if (!isPreservedDeclarationStatement(input)) {
106106                 // return undefined for unmatched kinds to omit them from the tree
106107                 return;
106108             }
106109             if (shouldStripInternal(input))
106110                 return;
106111             switch (input.kind) {
106112                 case 271 /* ExportDeclaration */: {
106113                     if (ts.isSourceFile(input.parent)) {
106114                         resultHasExternalModuleIndicator = true;
106115                     }
106116                     resultHasScopeMarker = true;
106117                     // Always visible if the parent node isn't dropped for being not visible
106118                     // Rewrite external module names if necessary
106119                     return factory.updateExportDeclaration(input, 
106120                     /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), 
106121                     /*assertClause*/ undefined);
106122                 }
106123                 case 270 /* ExportAssignment */: {
106124                     // Always visible if the parent node isn't dropped for being not visible
106125                     if (ts.isSourceFile(input.parent)) {
106126                         resultHasExternalModuleIndicator = true;
106127                     }
106128                     resultHasScopeMarker = true;
106129                     if (input.expression.kind === 79 /* Identifier */) {
106130                         return input;
106131                     }
106132                     else {
106133                         var newId = factory.createUniqueName("_default", 16 /* Optimistic */);
106134                         getSymbolAccessibilityDiagnostic = function () { return ({
106135                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
106136                             errorNode: input
106137                         }); };
106138                         errorFallbackNode = input;
106139                         var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
106140                         errorFallbackNode = undefined;
106141                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
106142                         return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
106143                     }
106144                 }
106145             }
106146             var result = transformTopLevelDeclaration(input);
106147             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
106148             lateStatementReplacementMap.set(ts.getOriginalNodeId(input), result);
106149             return input;
106150         }
106151         function stripExportModifiers(statement) {
106152             if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* Default */) || !ts.canHaveModifiers(statement)) {
106153                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
106154                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
106155                 return statement;
106156             }
106157             var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */));
106158             return factory.updateModifiers(statement, modifiers);
106159         }
106160         function transformTopLevelDeclaration(input) {
106161             if (shouldStripInternal(input))
106162                 return;
106163             switch (input.kind) {
106164                 case 264 /* ImportEqualsDeclaration */: {
106165                     return transformImportEqualsDeclaration(input);
106166                 }
106167                 case 265 /* ImportDeclaration */: {
106168                     return transformImportDeclaration(input);
106169                 }
106170             }
106171             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
106172                 return;
106173             // Elide implementation signatures from overload sets
106174             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
106175                 return;
106176             var previousEnclosingDeclaration;
106177             if (isEnclosingDeclaration(input)) {
106178                 previousEnclosingDeclaration = enclosingDeclaration;
106179                 enclosingDeclaration = input;
106180             }
106181             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
106182             var oldDiag = getSymbolAccessibilityDiagnostic;
106183             if (canProdiceDiagnostic) {
106184                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
106185             }
106186             var previousNeedsDeclare = needsDeclare;
106187             switch (input.kind) {
106188                 case 258 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
106189                     return cleanup(factory.updateTypeAliasDeclaration(input, 
106190                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
106191                 case 257 /* InterfaceDeclaration */: {
106192                     return cleanup(factory.updateInterfaceDeclaration(input, 
106193                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
106194                 }
106195                 case 255 /* FunctionDeclaration */: {
106196                     // Generators lose their generator-ness, excepting their return type
106197                     var clean = cleanup(factory.updateFunctionDeclaration(input, 
106198                     /*decorators*/ undefined, ensureModifiers(input), 
106199                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
106200                     /*body*/ undefined));
106201                     if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) {
106202                         var props = resolver.getPropertiesOfContainerFunction(input);
106203                         // Use parseNodeFactory so it is usable as an enclosing declaration
106204                         var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* Namespace */);
106205                         ts.setParent(fakespace_1, enclosingDeclaration);
106206                         fakespace_1.locals = ts.createSymbolTable(props);
106207                         fakespace_1.symbol = props[0].parent;
106208                         var exportMappings_1 = [];
106209                         var declarations = ts.mapDefined(props, function (p) {
106210                             if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) {
106211                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
106212                             }
106213                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
106214                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
106215                             getSymbolAccessibilityDiagnostic = oldDiag;
106216                             var nameStr = ts.unescapeLeadingUnderscores(p.escapedName);
106217                             var isNonContextualKeywordName = ts.isStringANonContextualKeyword(nameStr);
106218                             var name = isNonContextualKeywordName ? factory.getGeneratedNameForNode(p.valueDeclaration) : factory.createIdentifier(nameStr);
106219                             if (isNonContextualKeywordName) {
106220                                 exportMappings_1.push([name, nameStr]);
106221                             }
106222                             var varDecl = factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, type, /*initializer*/ undefined);
106223                             return factory.createVariableStatement(isNonContextualKeywordName ? undefined : [factory.createToken(93 /* ExportKeyword */)], factory.createVariableDeclarationList([varDecl]));
106224                         });
106225                         if (!exportMappings_1.length) {
106226                             declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0 /* None */); });
106227                         }
106228                         else {
106229                             declarations.push(factory.createExportDeclaration(
106230                             /*decorators*/ undefined, 
106231                             /*modifiers*/ undefined, 
106232                             /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) {
106233                                 var gen = _a[0], exp = _a[1];
106234                                 return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp);
106235                             }))));
106236                         }
106237                         var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* Namespace */);
106238                         if (!ts.hasEffectiveModifier(clean, 512 /* Default */)) {
106239                             return [clean, namespaceDecl];
106240                         }
106241                         var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
106242                         var cleanDeclaration = factory.updateFunctionDeclaration(clean, 
106243                         /*decorators*/ undefined, modifiers, 
106244                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
106245                         /*body*/ undefined);
106246                         var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, 
106247                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
106248                         var exportDefaultDeclaration = factory.createExportAssignment(
106249                         /*decorators*/ undefined, 
106250                         /*modifiers*/ undefined, 
106251                         /*isExportEquals*/ false, namespaceDecl.name);
106252                         if (ts.isSourceFile(input.parent)) {
106253                             resultHasExternalModuleIndicator = true;
106254                         }
106255                         resultHasScopeMarker = true;
106256                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
106257                     }
106258                     else {
106259                         return clean;
106260                     }
106261                 }
106262                 case 260 /* ModuleDeclaration */: {
106263                     needsDeclare = false;
106264                     var inner = input.body;
106265                     if (inner && inner.kind === 261 /* ModuleBlock */) {
106266                         var oldNeedsScopeFix = needsScopeFixMarker;
106267                         var oldHasScopeFix = resultHasScopeMarker;
106268                         resultHasScopeMarker = false;
106269                         needsScopeFixMarker = false;
106270                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
106271                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
106272                         if (input.flags & 8388608 /* Ambient */) {
106273                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
106274                         }
106275                         // With the final list of statements, there are 3 possibilities:
106276                         // 1. There's an export assignment or export declaration in the namespace - do nothing
106277                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
106278                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
106279                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
106280                             if (needsScopeFixMarker) {
106281                                 lateStatements = factory.createNodeArray(__spreadArray(__spreadArray([], lateStatements, true), [ts.createEmptyExports(factory)], false));
106282                             }
106283                             else {
106284                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
106285                             }
106286                         }
106287                         var body = factory.updateModuleBlock(inner, lateStatements);
106288                         needsDeclare = previousNeedsDeclare;
106289                         needsScopeFixMarker = oldNeedsScopeFix;
106290                         resultHasScopeMarker = oldHasScopeFix;
106291                         var mods = ensureModifiers(input);
106292                         return cleanup(factory.updateModuleDeclaration(input, 
106293                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
106294                     }
106295                     else {
106296                         needsDeclare = previousNeedsDeclare;
106297                         var mods = ensureModifiers(input);
106298                         needsDeclare = false;
106299                         ts.visitNode(inner, visitDeclarationStatements);
106300                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
106301                         var id = ts.getOriginalNodeId(inner); // TODO: GH#18217
106302                         var body = lateStatementReplacementMap.get(id);
106303                         lateStatementReplacementMap.delete(id);
106304                         return cleanup(factory.updateModuleDeclaration(input, 
106305                         /*decorators*/ undefined, mods, input.name, body));
106306                     }
106307                 }
106308                 case 256 /* ClassDeclaration */: {
106309                     errorNameNode = input.name;
106310                     errorFallbackNode = input;
106311                     var modifiers = factory.createNodeArray(ensureModifiers(input));
106312                     var typeParameters = ensureTypeParams(input, input.typeParameters);
106313                     var ctor = ts.getFirstConstructorWithBody(input);
106314                     var parameterProperties = void 0;
106315                     if (ctor) {
106316                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
106317                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
106318                             if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param))
106319                                 return;
106320                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
106321                             if (param.name.kind === 79 /* Identifier */) {
106322                                 return preserveJsDoc(factory.createPropertyDeclaration(
106323                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
106324                             }
106325                             else {
106326                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
106327                                 return walkBindingPattern(param.name);
106328                             }
106329                             function walkBindingPattern(pattern) {
106330                                 var elems;
106331                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
106332                                     var elem = _a[_i];
106333                                     if (ts.isOmittedExpression(elem))
106334                                         continue;
106335                                     if (ts.isBindingPattern(elem.name)) {
106336                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
106337                                     }
106338                                     elems = elems || [];
106339                                     elems.push(factory.createPropertyDeclaration(
106340                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
106341                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
106342                                     /*initializer*/ undefined));
106343                                 }
106344                                 return elems;
106345                             }
106346                         }));
106347                         getSymbolAccessibilityDiagnostic = oldDiag_1;
106348                     }
106349                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
106350                     // When the class has at least one private identifier, create a unique constant identifier to retain the nominal typing behavior
106351                     // Prevents other classes with the same public members from being used in place of the current class
106352                     var privateIdentifier = hasPrivateIdentifier ? [
106353                         factory.createPropertyDeclaration(
106354                         /*decorators*/ undefined, 
106355                         /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), 
106356                         /*questionToken*/ undefined, 
106357                         /*type*/ undefined, 
106358                         /*initializer*/ undefined)
106359                     ] : undefined;
106360                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
106361                     var members = factory.createNodeArray(memberNodes);
106362                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
106363                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 104 /* NullKeyword */) {
106364                         // We must add a temporary declaration for the extends clause expression
106365                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
106366                         var newId_1 = factory.createUniqueName("".concat(oldId, "_base"), 16 /* Optimistic */);
106367                         getSymbolAccessibilityDiagnostic = function () { return ({
106368                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
106369                             errorNode: extendsClause_1,
106370                             typeName: input.name
106371                         }); };
106372                         var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
106373                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
106374                         var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) {
106375                             if (clause.token === 94 /* ExtendsKeyword */) {
106376                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
106377                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
106378                                 var newClause = factory.updateHeritageClause(clause, ts.map(clause.types, function (t) { return factory.updateExpressionWithTypeArguments(t, newId_1, ts.visitNodes(t.typeArguments, visitDeclarationSubtree)); }));
106379                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
106380                                 return newClause;
106381                             }
106382                             return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* NullKeyword */; })), visitDeclarationSubtree));
106383                         }));
106384                         return [statement, cleanup(factory.updateClassDeclaration(input, 
106385                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
106386                     }
106387                     else {
106388                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
106389                         return cleanup(factory.updateClassDeclaration(input, 
106390                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
106391                     }
106392                 }
106393                 case 236 /* VariableStatement */: {
106394                     return cleanup(transformVariableStatement(input));
106395                 }
106396                 case 259 /* EnumDeclaration */: {
106397                     return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) {
106398                         if (shouldStripInternal(m))
106399                             return;
106400                         // Rewrite enum values to their constants, if available
106401                         var constValue = resolver.getConstantValue(m);
106402                         return preserveJsDoc(factory.updateEnumMember(m, m.name, constValue !== undefined ? typeof constValue === "string" ? factory.createStringLiteral(constValue) : factory.createNumericLiteral(constValue) : undefined), m);
106403                     }))));
106404                 }
106405             }
106406             // Anything left unhandled is an error, so this should be unreachable
106407             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind]));
106408             function cleanup(node) {
106409                 if (isEnclosingDeclaration(input)) {
106410                     enclosingDeclaration = previousEnclosingDeclaration;
106411                 }
106412                 if (canProdiceDiagnostic) {
106413                     getSymbolAccessibilityDiagnostic = oldDiag;
106414                 }
106415                 if (input.kind === 260 /* ModuleDeclaration */) {
106416                     needsDeclare = previousNeedsDeclare;
106417                 }
106418                 if (node === input) {
106419                     return node;
106420                 }
106421                 errorFallbackNode = undefined;
106422                 errorNameNode = undefined;
106423                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
106424             }
106425         }
106426         function transformVariableStatement(input) {
106427             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
106428                 return;
106429             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
106430             if (!ts.length(nodes))
106431                 return;
106432             return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes));
106433         }
106434         function recreateBindingPattern(d) {
106435             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
106436         }
106437         function recreateBindingElement(e) {
106438             if (e.kind === 226 /* OmittedExpression */) {
106439                 return;
106440             }
106441             if (e.name) {
106442                 if (!getBindingNameVisible(e))
106443                     return;
106444                 if (ts.isBindingPattern(e.name)) {
106445                     return recreateBindingPattern(e.name);
106446                 }
106447                 else {
106448                     return factory.createVariableDeclaration(e.name, /*exclamationToken*/ undefined, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
106449                 }
106450             }
106451         }
106452         function checkName(node) {
106453             var oldDiag;
106454             if (!suppressNewDiagnosticContexts) {
106455                 oldDiag = getSymbolAccessibilityDiagnostic;
106456                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
106457             }
106458             errorNameNode = node.name;
106459             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
106460             var decl = node;
106461             var entityName = decl.name.expression;
106462             checkEntityNameVisibility(entityName, enclosingDeclaration);
106463             if (!suppressNewDiagnosticContexts) {
106464                 getSymbolAccessibilityDiagnostic = oldDiag;
106465             }
106466             errorNameNode = undefined;
106467         }
106468         function shouldStripInternal(node) {
106469             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
106470         }
106471         function isScopeMarker(node) {
106472             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
106473         }
106474         function hasScopeMarker(statements) {
106475             return ts.some(statements, isScopeMarker);
106476         }
106477         function ensureModifiers(node) {
106478             var currentFlags = ts.getEffectiveModifierFlags(node);
106479             var newFlags = ensureModifierFlags(node);
106480             if (currentFlags === newFlags) {
106481                 return node.modifiers;
106482             }
106483             return factory.createModifiersFromModifierFlags(newFlags);
106484         }
106485         function ensureModifierFlags(node) {
106486             var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files
106487             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
106488             var parentIsFile = node.parent.kind === 303 /* SourceFile */;
106489             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
106490                 mask ^= 2 /* Ambient */;
106491                 additions = 0 /* None */;
106492             }
106493             return maskModifierFlags(node, mask, additions);
106494         }
106495         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
106496             var accessorType = getTypeAnnotationFromAccessor(node);
106497             if (!accessorType && node !== accessors.firstAccessor) {
106498                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
106499                 // 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
106500                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
106501             }
106502             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
106503                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
106504                 // 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
106505                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
106506             }
106507             return accessorType;
106508         }
106509         function transformHeritageClauses(nodes) {
106510             return factory.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) {
106511                 return ts.isEntityNameExpression(t.expression) || (clause.token === 94 /* ExtendsKeyword */ && t.expression.kind === 104 /* NullKeyword */);
106512             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
106513         }
106514     }
106515     ts.transformDeclarations = transformDeclarations;
106516     function isAlwaysType(node) {
106517         if (node.kind === 257 /* InterfaceDeclaration */) {
106518             return true;
106519         }
106520         return false;
106521     }
106522     // Elide "public" modifier, as it is the default
106523     function maskModifiers(node, modifierMask, modifierAdditions) {
106524         return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
106525     }
106526     function maskModifierFlags(node, modifierMask, modifierAdditions) {
106527         if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; }
106528         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
106529         var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions;
106530         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
106531             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
106532             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
106533             flags ^= 1 /* Export */;
106534         }
106535         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
106536             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
106537         }
106538         return flags;
106539     }
106540     function getTypeAnnotationFromAccessor(accessor) {
106541         if (accessor) {
106542             return accessor.kind === 171 /* GetAccessor */
106543                 ? accessor.type // Getter - return type
106544                 : accessor.parameters.length > 0
106545                     ? accessor.parameters[0].type // Setter parameter type
106546                     : undefined;
106547         }
106548     }
106549     function canHaveLiteralInitializer(node) {
106550         switch (node.kind) {
106551             case 166 /* PropertyDeclaration */:
106552             case 165 /* PropertySignature */:
106553                 return !ts.hasEffectiveModifier(node, 8 /* Private */);
106554             case 163 /* Parameter */:
106555             case 253 /* VariableDeclaration */:
106556                 return true;
106557         }
106558         return false;
106559     }
106560     function isPreservedDeclarationStatement(node) {
106561         switch (node.kind) {
106562             case 255 /* FunctionDeclaration */:
106563             case 260 /* ModuleDeclaration */:
106564             case 264 /* ImportEqualsDeclaration */:
106565             case 257 /* InterfaceDeclaration */:
106566             case 256 /* ClassDeclaration */:
106567             case 258 /* TypeAliasDeclaration */:
106568             case 259 /* EnumDeclaration */:
106569             case 236 /* VariableStatement */:
106570             case 265 /* ImportDeclaration */:
106571             case 271 /* ExportDeclaration */:
106572             case 270 /* ExportAssignment */:
106573                 return true;
106574         }
106575         return false;
106576     }
106577     function isProcessedComponent(node) {
106578         switch (node.kind) {
106579             case 174 /* ConstructSignature */:
106580             case 170 /* Constructor */:
106581             case 168 /* MethodDeclaration */:
106582             case 171 /* GetAccessor */:
106583             case 172 /* SetAccessor */:
106584             case 166 /* PropertyDeclaration */:
106585             case 165 /* PropertySignature */:
106586             case 167 /* MethodSignature */:
106587             case 173 /* CallSignature */:
106588             case 175 /* IndexSignature */:
106589             case 253 /* VariableDeclaration */:
106590             case 162 /* TypeParameter */:
106591             case 227 /* ExpressionWithTypeArguments */:
106592             case 177 /* TypeReference */:
106593             case 188 /* ConditionalType */:
106594             case 178 /* FunctionType */:
106595             case 179 /* ConstructorType */:
106596             case 199 /* ImportType */:
106597                 return true;
106598         }
106599         return false;
106600     }
106601 })(ts || (ts = {}));
106602 /* @internal */
106603 var ts;
106604 (function (ts) {
106605     function getModuleTransformer(moduleKind) {
106606         switch (moduleKind) {
106607             case ts.ModuleKind.ESNext:
106608             case ts.ModuleKind.ES2022:
106609             case ts.ModuleKind.ES2020:
106610             case ts.ModuleKind.ES2015:
106611                 return ts.transformECMAScriptModule;
106612             case ts.ModuleKind.System:
106613                 return ts.transformSystemModule;
106614             case ts.ModuleKind.Node12:
106615             case ts.ModuleKind.NodeNext:
106616                 return ts.transformNodeModule;
106617             default:
106618                 return ts.transformModule;
106619         }
106620     }
106621     var TransformationState;
106622     (function (TransformationState) {
106623         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
106624         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
106625         TransformationState[TransformationState["Completed"] = 2] = "Completed";
106626         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
106627     })(TransformationState || (TransformationState = {}));
106628     var SyntaxKindFeatureFlags;
106629     (function (SyntaxKindFeatureFlags) {
106630         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
106631         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
106632     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
106633     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
106634     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
106635         return {
106636             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
106637             declarationTransformers: getDeclarationTransformers(customTransformers),
106638         };
106639     }
106640     ts.getTransformers = getTransformers;
106641     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
106642         if (emitOnlyDtsFiles)
106643             return ts.emptyArray;
106644         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
106645         var moduleKind = ts.getEmitModuleKind(compilerOptions);
106646         var transformers = [];
106647         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
106648         transformers.push(ts.transformTypeScript);
106649         transformers.push(ts.transformClassFields);
106650         if (ts.getJSXTransformEnabled(compilerOptions)) {
106651             transformers.push(ts.transformJsx);
106652         }
106653         if (languageVersion < 99 /* ESNext */) {
106654             transformers.push(ts.transformESNext);
106655         }
106656         if (languageVersion < 8 /* ES2021 */) {
106657             transformers.push(ts.transformES2021);
106658         }
106659         if (languageVersion < 7 /* ES2020 */) {
106660             transformers.push(ts.transformES2020);
106661         }
106662         if (languageVersion < 6 /* ES2019 */) {
106663             transformers.push(ts.transformES2019);
106664         }
106665         if (languageVersion < 5 /* ES2018 */) {
106666             transformers.push(ts.transformES2018);
106667         }
106668         if (languageVersion < 4 /* ES2017 */) {
106669             transformers.push(ts.transformES2017);
106670         }
106671         if (languageVersion < 3 /* ES2016 */) {
106672             transformers.push(ts.transformES2016);
106673         }
106674         if (languageVersion < 2 /* ES2015 */) {
106675             transformers.push(ts.transformES2015);
106676             transformers.push(ts.transformGenerators);
106677         }
106678         transformers.push(getModuleTransformer(moduleKind));
106679         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
106680         // for ES3.
106681         if (languageVersion < 1 /* ES5 */) {
106682             transformers.push(ts.transformES5);
106683         }
106684         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
106685         return transformers;
106686     }
106687     function getDeclarationTransformers(customTransformers) {
106688         var transformers = [];
106689         transformers.push(ts.transformDeclarations);
106690         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
106691         return transformers;
106692     }
106693     /**
106694      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
106695      */
106696     function wrapCustomTransformer(transformer) {
106697         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
106698     }
106699     /**
106700      * Wrap a transformer factory that may return a custom script or declaration transformer object.
106701      */
106702     function wrapCustomTransformerFactory(transformer, handleDefault) {
106703         return function (context) {
106704             var customTransformer = transformer(context);
106705             return typeof customTransformer === "function"
106706                 ? handleDefault(context, customTransformer)
106707                 : wrapCustomTransformer(customTransformer);
106708         };
106709     }
106710     function wrapScriptTransformerFactory(transformer) {
106711         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
106712     }
106713     function wrapDeclarationTransformerFactory(transformer) {
106714         return wrapCustomTransformerFactory(transformer, function (_, node) { return node; });
106715     }
106716     function noEmitSubstitution(_hint, node) {
106717         return node;
106718     }
106719     ts.noEmitSubstitution = noEmitSubstitution;
106720     function noEmitNotification(hint, node, callback) {
106721         callback(hint, node);
106722     }
106723     ts.noEmitNotification = noEmitNotification;
106724     /**
106725      * Transforms an array of SourceFiles by passing them through each transformer.
106726      *
106727      * @param resolver The emit resolver provided by the checker.
106728      * @param host The emit host object used to interact with the file system.
106729      * @param options Compiler options to surface in the `TransformationContext`.
106730      * @param nodes An array of nodes to transform.
106731      * @param transforms An array of `TransformerFactory` callbacks.
106732      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
106733      */
106734     function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) {
106735         var enabledSyntaxKindFeatures = new Array(353 /* Count */);
106736         var lexicalEnvironmentVariableDeclarations;
106737         var lexicalEnvironmentFunctionDeclarations;
106738         var lexicalEnvironmentStatements;
106739         var lexicalEnvironmentFlags = 0 /* None */;
106740         var lexicalEnvironmentVariableDeclarationsStack = [];
106741         var lexicalEnvironmentFunctionDeclarationsStack = [];
106742         var lexicalEnvironmentStatementsStack = [];
106743         var lexicalEnvironmentFlagsStack = [];
106744         var lexicalEnvironmentStackOffset = 0;
106745         var lexicalEnvironmentSuspended = false;
106746         var blockScopedVariableDeclarationsStack = [];
106747         var blockScopeStackOffset = 0;
106748         var blockScopedVariableDeclarations;
106749         var emitHelpers;
106750         var onSubstituteNode = noEmitSubstitution;
106751         var onEmitNode = noEmitNotification;
106752         var state = 0 /* Uninitialized */;
106753         var diagnostics = [];
106754         // The transformation context is provided to each transformer as part of transformer
106755         // initialization.
106756         var context = {
106757             factory: factory,
106758             getCompilerOptions: function () { return options; },
106759             getEmitResolver: function () { return resolver; },
106760             getEmitHost: function () { return host; },
106761             getEmitHelperFactory: ts.memoize(function () { return ts.createEmitHelperFactory(context); }),
106762             startLexicalEnvironment: startLexicalEnvironment,
106763             suspendLexicalEnvironment: suspendLexicalEnvironment,
106764             resumeLexicalEnvironment: resumeLexicalEnvironment,
106765             endLexicalEnvironment: endLexicalEnvironment,
106766             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
106767             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
106768             hoistVariableDeclaration: hoistVariableDeclaration,
106769             hoistFunctionDeclaration: hoistFunctionDeclaration,
106770             addInitializationStatement: addInitializationStatement,
106771             startBlockScope: startBlockScope,
106772             endBlockScope: endBlockScope,
106773             addBlockScopedVariable: addBlockScopedVariable,
106774             requestEmitHelper: requestEmitHelper,
106775             readEmitHelpers: readEmitHelpers,
106776             enableSubstitution: enableSubstitution,
106777             enableEmitNotification: enableEmitNotification,
106778             isSubstitutionEnabled: isSubstitutionEnabled,
106779             isEmitNotificationEnabled: isEmitNotificationEnabled,
106780             get onSubstituteNode() { return onSubstituteNode; },
106781             set onSubstituteNode(value) {
106782                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
106783                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
106784                 onSubstituteNode = value;
106785             },
106786             get onEmitNode() { return onEmitNode; },
106787             set onEmitNode(value) {
106788                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
106789                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
106790                 onEmitNode = value;
106791             },
106792             addDiagnostic: function (diag) {
106793                 diagnostics.push(diag);
106794             }
106795         };
106796         // Ensure the parse tree is clean before applying transformations
106797         for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
106798             var node = nodes_2[_i];
106799             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
106800         }
106801         ts.performance.mark("beforeTransform");
106802         // Chain together and initialize each transformer.
106803         var transformersWithContext = transformers.map(function (t) { return t(context); });
106804         var transformation = function (node) {
106805             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
106806                 var transform = transformersWithContext_1[_i];
106807                 node = transform(node);
106808             }
106809             return node;
106810         };
106811         // prevent modification of transformation hooks.
106812         state = 1 /* Initialized */;
106813         // Transform each node.
106814         var transformed = [];
106815         for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) {
106816             var node = nodes_3[_a];
106817             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 303 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
106818             transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
106819             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106820         }
106821         // prevent modification of the lexical environment.
106822         state = 2 /* Completed */;
106823         ts.performance.mark("afterTransform");
106824         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
106825         return {
106826             transformed: transformed,
106827             substituteNode: substituteNode,
106828             emitNodeWithNotification: emitNodeWithNotification,
106829             isEmitNotificationEnabled: isEmitNotificationEnabled,
106830             dispose: dispose,
106831             diagnostics: diagnostics
106832         };
106833         function transformRoot(node) {
106834             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
106835         }
106836         /**
106837          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
106838          */
106839         function enableSubstitution(kind) {
106840             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
106841             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
106842         }
106843         /**
106844          * Determines whether expression substitutions are enabled for the provided node.
106845          */
106846         function isSubstitutionEnabled(node) {
106847             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
106848                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
106849         }
106850         /**
106851          * Emits a node with possible substitution.
106852          *
106853          * @param hint A hint as to the intended usage of the node.
106854          * @param node The node to emit.
106855          * @param emitCallback The callback used to emit the node or its substitute.
106856          */
106857         function substituteNode(hint, node) {
106858             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
106859             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
106860         }
106861         /**
106862          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
106863          */
106864         function enableEmitNotification(kind) {
106865             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
106866             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
106867         }
106868         /**
106869          * Determines whether before/after emit notifications should be raised in the pretty
106870          * printer when it emits a node.
106871          */
106872         function isEmitNotificationEnabled(node) {
106873             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
106874                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
106875         }
106876         /**
106877          * Emits a node with possible emit notification.
106878          *
106879          * @param hint A hint as to the intended usage of the node.
106880          * @param node The node to emit.
106881          * @param emitCallback The callback used to emit the node.
106882          */
106883         function emitNodeWithNotification(hint, node, emitCallback) {
106884             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
106885             if (node) {
106886                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
106887                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
106888                 if (isEmitNotificationEnabled(node)) {
106889                     onEmitNode(hint, node, emitCallback);
106890                 }
106891                 else {
106892                     emitCallback(hint, node);
106893                 }
106894             }
106895         }
106896         /**
106897          * Records a hoisted variable declaration for the provided name within a lexical environment.
106898          */
106899         function hoistVariableDeclaration(name) {
106900             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106901             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106902             var decl = ts.setEmitFlags(factory.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
106903             if (!lexicalEnvironmentVariableDeclarations) {
106904                 lexicalEnvironmentVariableDeclarations = [decl];
106905             }
106906             else {
106907                 lexicalEnvironmentVariableDeclarations.push(decl);
106908             }
106909             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
106910                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
106911             }
106912         }
106913         /**
106914          * Records a hoisted function declaration within a lexical environment.
106915          */
106916         function hoistFunctionDeclaration(func) {
106917             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106918             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106919             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
106920             if (!lexicalEnvironmentFunctionDeclarations) {
106921                 lexicalEnvironmentFunctionDeclarations = [func];
106922             }
106923             else {
106924                 lexicalEnvironmentFunctionDeclarations.push(func);
106925             }
106926         }
106927         /**
106928          * Adds an initialization statement to the top of the lexical environment.
106929          */
106930         function addInitializationStatement(node) {
106931             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106932             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106933             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
106934             if (!lexicalEnvironmentStatements) {
106935                 lexicalEnvironmentStatements = [node];
106936             }
106937             else {
106938                 lexicalEnvironmentStatements.push(node);
106939             }
106940         }
106941         /**
106942          * Starts a new lexical environment. Any existing hoisted variable or function declarations
106943          * are pushed onto a stack, and the related storage variables are reset.
106944          */
106945         function startLexicalEnvironment() {
106946             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106947             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106948             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
106949             // Save the current lexical environment. Rather than resizing the array we adjust the
106950             // stack size variable. This allows us to reuse existing array slots we've
106951             // already allocated between transformations to avoid allocation and GC overhead during
106952             // transformation.
106953             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
106954             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
106955             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
106956             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
106957             lexicalEnvironmentStackOffset++;
106958             lexicalEnvironmentVariableDeclarations = undefined;
106959             lexicalEnvironmentFunctionDeclarations = undefined;
106960             lexicalEnvironmentStatements = undefined;
106961             lexicalEnvironmentFlags = 0 /* None */;
106962         }
106963         /** Suspends the current lexical environment, usually after visiting a parameter list. */
106964         function suspendLexicalEnvironment() {
106965             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106966             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106967             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
106968             lexicalEnvironmentSuspended = true;
106969         }
106970         /** Resumes a suspended lexical environment, usually before visiting a function body. */
106971         function resumeLexicalEnvironment() {
106972             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106973             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106974             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
106975             lexicalEnvironmentSuspended = false;
106976         }
106977         /**
106978          * Ends a lexical environment. The previous set of hoisted declarations are restored and
106979          * any hoisted declarations added in this environment are returned.
106980          */
106981         function endLexicalEnvironment() {
106982             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
106983             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
106984             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
106985             var statements;
106986             if (lexicalEnvironmentVariableDeclarations ||
106987                 lexicalEnvironmentFunctionDeclarations ||
106988                 lexicalEnvironmentStatements) {
106989                 if (lexicalEnvironmentFunctionDeclarations) {
106990                     statements = __spreadArray([], lexicalEnvironmentFunctionDeclarations, true);
106991                 }
106992                 if (lexicalEnvironmentVariableDeclarations) {
106993                     var statement = factory.createVariableStatement(
106994                     /*modifiers*/ undefined, factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
106995                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
106996                     if (!statements) {
106997                         statements = [statement];
106998                     }
106999                     else {
107000                         statements.push(statement);
107001                     }
107002                 }
107003                 if (lexicalEnvironmentStatements) {
107004                     if (!statements) {
107005                         statements = __spreadArray([], lexicalEnvironmentStatements, true);
107006                     }
107007                     else {
107008                         statements = __spreadArray(__spreadArray([], statements, true), lexicalEnvironmentStatements, true);
107009                     }
107010                 }
107011             }
107012             // Restore the previous lexical environment.
107013             lexicalEnvironmentStackOffset--;
107014             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
107015             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
107016             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
107017             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
107018             if (lexicalEnvironmentStackOffset === 0) {
107019                 lexicalEnvironmentVariableDeclarationsStack = [];
107020                 lexicalEnvironmentFunctionDeclarationsStack = [];
107021                 lexicalEnvironmentStatementsStack = [];
107022                 lexicalEnvironmentFlagsStack = [];
107023             }
107024             return statements;
107025         }
107026         function setLexicalEnvironmentFlags(flags, value) {
107027             lexicalEnvironmentFlags = value ?
107028                 lexicalEnvironmentFlags | flags :
107029                 lexicalEnvironmentFlags & ~flags;
107030         }
107031         function getLexicalEnvironmentFlags() {
107032             return lexicalEnvironmentFlags;
107033         }
107034         /**
107035          * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset.
107036          */
107037         function startBlockScope() {
107038             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization.");
107039             ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed.");
107040             blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations;
107041             blockScopeStackOffset++;
107042             blockScopedVariableDeclarations = undefined;
107043         }
107044         /**
107045          * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned.
107046          */
107047         function endBlockScope() {
107048             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization.");
107049             ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed.");
107050             var statements = ts.some(blockScopedVariableDeclarations) ?
107051                 [
107052                     factory.createVariableStatement(
107053                     /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */))
107054                 ] : undefined;
107055             blockScopeStackOffset--;
107056             blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset];
107057             if (blockScopeStackOffset === 0) {
107058                 blockScopedVariableDeclarationsStack = [];
107059             }
107060             return statements;
107061         }
107062         function addBlockScopedVariable(name) {
107063             ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body.");
107064             (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name);
107065         }
107066         function requestEmitHelper(helper) {
107067             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
107068             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
107069             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
107070             if (helper.dependencies) {
107071                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
107072                     var h = _a[_i];
107073                     requestEmitHelper(h);
107074                 }
107075             }
107076             emitHelpers = ts.append(emitHelpers, helper);
107077         }
107078         function readEmitHelpers() {
107079             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
107080             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
107081             var helpers = emitHelpers;
107082             emitHelpers = undefined;
107083             return helpers;
107084         }
107085         function dispose() {
107086             if (state < 3 /* Disposed */) {
107087                 // Clean up emit nodes on parse tree
107088                 for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
107089                     var node = nodes_4[_i];
107090                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
107091                 }
107092                 // Release references to external entries for GC purposes.
107093                 lexicalEnvironmentVariableDeclarations = undefined;
107094                 lexicalEnvironmentVariableDeclarationsStack = undefined;
107095                 lexicalEnvironmentFunctionDeclarations = undefined;
107096                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
107097                 onSubstituteNode = undefined;
107098                 onEmitNode = undefined;
107099                 emitHelpers = undefined;
107100                 // Prevent further use of the transformation result.
107101                 state = 3 /* Disposed */;
107102             }
107103         }
107104     }
107105     ts.transformNodes = transformNodes;
107106     ts.nullTransformationContext = {
107107         factory: ts.factory,
107108         getCompilerOptions: function () { return ({}); },
107109         getEmitResolver: ts.notImplemented,
107110         getEmitHost: ts.notImplemented,
107111         getEmitHelperFactory: ts.notImplemented,
107112         startLexicalEnvironment: ts.noop,
107113         resumeLexicalEnvironment: ts.noop,
107114         suspendLexicalEnvironment: ts.noop,
107115         endLexicalEnvironment: ts.returnUndefined,
107116         setLexicalEnvironmentFlags: ts.noop,
107117         getLexicalEnvironmentFlags: function () { return 0; },
107118         hoistVariableDeclaration: ts.noop,
107119         hoistFunctionDeclaration: ts.noop,
107120         addInitializationStatement: ts.noop,
107121         startBlockScope: ts.noop,
107122         endBlockScope: ts.returnUndefined,
107123         addBlockScopedVariable: ts.noop,
107124         requestEmitHelper: ts.noop,
107125         readEmitHelpers: ts.notImplemented,
107126         enableSubstitution: ts.noop,
107127         enableEmitNotification: ts.noop,
107128         isSubstitutionEnabled: ts.notImplemented,
107129         isEmitNotificationEnabled: ts.notImplemented,
107130         onSubstituteNode: noEmitSubstitution,
107131         onEmitNode: noEmitNotification,
107132         addDiagnostic: ts.noop,
107133     };
107134 })(ts || (ts = {}));
107135 var ts;
107136 (function (ts) {
107137     var brackets = createBracketsMap();
107138     /*@internal*/
107139     function isBuildInfoFile(file) {
107140         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
107141     }
107142     ts.isBuildInfoFile = isBuildInfoFile;
107143     /*@internal*/
107144     /**
107145      * Iterates over the source files that are expected to have an emit output.
107146      *
107147      * @param host An EmitHost.
107148      * @param action The action to execute.
107149      * @param sourceFilesOrTargetSourceFile
107150      *   If an array, the full list of source files to emit.
107151      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
107152      */
107153     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
107154         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
107155         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
107156         var options = host.getCompilerOptions();
107157         if (ts.outFile(options)) {
107158             var prepends = host.getPrependNodes();
107159             if (sourceFiles.length || prepends.length) {
107160                 var bundle = ts.factory.createBundle(sourceFiles, prepends);
107161                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
107162                 if (result) {
107163                     return result;
107164                 }
107165             }
107166         }
107167         else {
107168             if (!onlyBuildInfo) {
107169                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
107170                     var sourceFile = sourceFiles_1[_a];
107171                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
107172                     if (result) {
107173                         return result;
107174                     }
107175                 }
107176             }
107177             if (includeBuildInfo) {
107178                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
107179                 if (buildInfoPath)
107180                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
107181             }
107182         }
107183     }
107184     ts.forEachEmittedFile = forEachEmittedFile;
107185     function getTsBuildInfoEmitOutputFilePath(options) {
107186         var configFile = options.configFilePath;
107187         if (!ts.isIncrementalCompilation(options))
107188             return undefined;
107189         if (options.tsBuildInfoFile)
107190             return options.tsBuildInfoFile;
107191         var outPath = ts.outFile(options);
107192         var buildInfoExtensionLess;
107193         if (outPath) {
107194             buildInfoExtensionLess = ts.removeFileExtension(outPath);
107195         }
107196         else {
107197             if (!configFile)
107198                 return undefined;
107199             var configFileExtensionLess = ts.removeFileExtension(configFile);
107200             buildInfoExtensionLess = options.outDir ?
107201                 options.rootDir ?
107202                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
107203                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
107204                 configFileExtensionLess;
107205         }
107206         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
107207     }
107208     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
107209     /*@internal*/
107210     function getOutputPathsForBundle(options, forceDtsPaths) {
107211         var outPath = ts.outFile(options);
107212         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
107213         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
107214         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
107215         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
107216         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
107217         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
107218     }
107219     ts.getOutputPathsForBundle = getOutputPathsForBundle;
107220     /*@internal*/
107221     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
107222         var options = host.getCompilerOptions();
107223         if (sourceFile.kind === 304 /* Bundle */) {
107224             return getOutputPathsForBundle(options, forceDtsPaths);
107225         }
107226         else {
107227             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile.fileName, options));
107228             var isJsonFile = ts.isJsonSourceFile(sourceFile);
107229             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
107230             var isJsonEmittedToSameLocation = isJsonFile &&
107231                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107232             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
107233             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
107234             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
107235             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
107236             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
107237         }
107238     }
107239     ts.getOutputPathsFor = getOutputPathsFor;
107240     function getSourceMapFilePath(jsFilePath, options) {
107241         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
107242     }
107243     /* @internal */
107244     function getOutputExtension(fileName, options) {
107245         return ts.fileExtensionIs(fileName, ".json" /* Json */) ? ".json" /* Json */ :
107246             options.jsx === 1 /* Preserve */ && ts.fileExtensionIsOneOf(fileName, [".jsx" /* Jsx */, ".tsx" /* Tsx */]) ? ".jsx" /* Jsx */ :
107247                 ts.fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".mjs" /* Mjs */]) ? ".mjs" /* Mjs */ :
107248                     ts.fileExtensionIsOneOf(fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]) ? ".cjs" /* Cjs */ :
107249                         ".js" /* Js */;
107250     }
107251     ts.getOutputExtension = getOutputExtension;
107252     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir, getCommonSourceDirectory) {
107253         return outputDir ?
107254             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(getCommonSourceDirectory ? getCommonSourceDirectory() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase)) :
107255             inputFileName;
107256     }
107257     /* @internal */
107258     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
107259         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory), ts.getDeclarationEmitExtensionForPath(inputFileName));
107260     }
107261     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
107262     function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
107263         if (configFile.options.emitDeclarationOnly)
107264             return undefined;
107265         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
107266         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory), getOutputExtension(inputFileName, configFile.options));
107267         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
107268             outputFileName :
107269             undefined;
107270     }
107271     function createAddOutput() {
107272         var outputs;
107273         return { addOutput: addOutput, getOutputs: getOutputs };
107274         function addOutput(path) {
107275             if (path) {
107276                 (outputs || (outputs = [])).push(path);
107277             }
107278         }
107279         function getOutputs() {
107280             return outputs || ts.emptyArray;
107281         }
107282     }
107283     function getSingleOutputFileNames(configFile, addOutput) {
107284         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
107285         addOutput(jsFilePath);
107286         addOutput(sourceMapFilePath);
107287         addOutput(declarationFilePath);
107288         addOutput(declarationMapPath);
107289         addOutput(buildInfoPath);
107290     }
107291     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory) {
107292         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
107293             return;
107294         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
107295         addOutput(js);
107296         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
107297             return;
107298         if (js && configFile.options.sourceMap) {
107299             addOutput("".concat(js, ".map"));
107300         }
107301         if (ts.getEmitDeclarations(configFile.options)) {
107302             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
107303             addOutput(dts);
107304             if (configFile.options.declarationMap) {
107305                 addOutput("".concat(dts, ".map"));
107306             }
107307         }
107308     }
107309     /*@internal*/
107310     function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) {
107311         var commonSourceDirectory;
107312         if (options.rootDir) {
107313             // If a rootDir is specified use it as the commonSourceDirectory
107314             commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
107315             checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(options.rootDir);
107316         }
107317         else if (options.composite && options.configFilePath) {
107318             // Project compilations never infer their root from the input source paths
107319             commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
107320             checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(commonSourceDirectory);
107321         }
107322         else {
107323             commonSourceDirectory = ts.computeCommonSourceDirectoryOfFilenames(emittedFiles(), currentDirectory, getCanonicalFileName);
107324         }
107325         if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
107326             // Make sure directory path ends with directory separator so this string can directly
107327             // used to replace with "" to get the relative path of the source file and the relative path doesn't
107328             // start with / making it rooted path
107329             commonSourceDirectory += ts.directorySeparator;
107330         }
107331         return commonSourceDirectory;
107332     }
107333     ts.getCommonSourceDirectory = getCommonSourceDirectory;
107334     /*@internal*/
107335     function getCommonSourceDirectoryOfConfig(_a, ignoreCase) {
107336         var options = _a.options, fileNames = _a.fileNames;
107337         return getCommonSourceDirectory(options, function () { return ts.filter(fileNames, function (file) { return !(options.noEmitForJsFiles && ts.fileExtensionIsOneOf(file, ts.supportedJSExtensionsFlat)) && !ts.fileExtensionIs(file, ".d.ts" /* Dts */); }); }, ts.getDirectoryPath(ts.normalizeSlashes(ts.Debug.checkDefined(options.configFilePath))), ts.createGetCanonicalFileName(!ignoreCase));
107338     }
107339     ts.getCommonSourceDirectoryOfConfig = getCommonSourceDirectoryOfConfig;
107340     /*@internal*/
107341     function getAllProjectOutputs(configFile, ignoreCase) {
107342         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
107343         if (ts.outFile(configFile.options)) {
107344             getSingleOutputFileNames(configFile, addOutput);
107345         }
107346         else {
107347             var getCommonSourceDirectory_1 = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
107348             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
107349                 var inputFileName = _c[_b];
107350                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory_1);
107351             }
107352             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
107353         }
107354         return getOutputs();
107355     }
107356     ts.getAllProjectOutputs = getAllProjectOutputs;
107357     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
107358         inputFileName = ts.normalizePath(inputFileName);
107359         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
107360         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
107361         if (ts.outFile(commandLine.options)) {
107362             getSingleOutputFileNames(commandLine, addOutput);
107363         }
107364         else {
107365             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
107366         }
107367         return getOutputs();
107368     }
107369     ts.getOutputFileNames = getOutputFileNames;
107370     /*@internal*/
107371     function getFirstProjectOutput(configFile, ignoreCase) {
107372         if (ts.outFile(configFile.options)) {
107373             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
107374             return ts.Debug.checkDefined(jsFilePath, "project ".concat(configFile.options.configFilePath, " expected to have at least one output"));
107375         }
107376         var getCommonSourceDirectory = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
107377         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
107378             var inputFileName = _b[_a];
107379             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
107380                 continue;
107381             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
107382             if (jsFilePath)
107383                 return jsFilePath;
107384             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
107385                 continue;
107386             if (ts.getEmitDeclarations(configFile.options)) {
107387                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
107388             }
107389         }
107390         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
107391         if (buildInfoPath)
107392             return buildInfoPath;
107393         return ts.Debug.fail("project ".concat(configFile.options.configFilePath, " expected to have at least one output"));
107394     }
107395     ts.getFirstProjectOutput = getFirstProjectOutput;
107396     /*@internal*/
107397     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
107398     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
107399         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
107400         var compilerOptions = host.getCompilerOptions();
107401         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
107402         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
107403         var emitterDiagnostics = ts.createDiagnosticCollection();
107404         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
107405         var writer = ts.createTextWriter(newLine);
107406         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
107407         var bundleBuildInfo;
107408         var emitSkipped = false;
107409         var exportedModulesFromDeclarationEmit;
107410         // Emit each output file
107411         enter();
107412         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
107413         exit();
107414         return {
107415             emitSkipped: emitSkipped,
107416             diagnostics: emitterDiagnostics.getDiagnostics(),
107417             emittedFiles: emittedFilesList,
107418             sourceMaps: sourceMapDataList,
107419             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
107420         };
107421         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
107422             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
107423             var buildInfoDirectory;
107424             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
107425                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
107426                 bundleBuildInfo = {
107427                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
107428                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
107429                 };
107430             }
107431             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
107432             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
107433             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107434             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
107435             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
107436             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107437             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
107438             emitBuildInfo(bundleBuildInfo, buildInfoPath);
107439             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107440             if (!emitSkipped && emittedFilesList) {
107441                 if (!emitOnlyDtsFiles) {
107442                     if (jsFilePath) {
107443                         emittedFilesList.push(jsFilePath);
107444                     }
107445                     if (sourceMapFilePath) {
107446                         emittedFilesList.push(sourceMapFilePath);
107447                     }
107448                     if (buildInfoPath) {
107449                         emittedFilesList.push(buildInfoPath);
107450                     }
107451                 }
107452                 if (declarationFilePath) {
107453                     emittedFilesList.push(declarationFilePath);
107454                 }
107455                 if (declarationMapPath) {
107456                     emittedFilesList.push(declarationMapPath);
107457                 }
107458             }
107459             function relativeToBuildInfo(path) {
107460                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
107461             }
107462         }
107463         function emitBuildInfo(bundle, buildInfoPath) {
107464             // Write build information if applicable
107465             if (!buildInfoPath || targetSourceFile || emitSkipped)
107466                 return;
107467             var program = host.getProgramBuildInfo();
107468             if (host.isEmitBlocked(buildInfoPath)) {
107469                 emitSkipped = true;
107470                 return;
107471             }
107472             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
107473             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
107474         }
107475         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
107476             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
107477                 return;
107478             }
107479             // Make sure not to write js file and source map file if any of them cannot be written
107480             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
107481                 emitSkipped = true;
107482                 return;
107483             }
107484             // Transform the source files
107485             var transform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
107486             var printerOptions = {
107487                 removeComments: compilerOptions.removeComments,
107488                 newLine: compilerOptions.newLine,
107489                 noEmitHelpers: compilerOptions.noEmitHelpers,
107490                 module: compilerOptions.module,
107491                 target: compilerOptions.target,
107492                 sourceMap: compilerOptions.sourceMap,
107493                 inlineSourceMap: compilerOptions.inlineSourceMap,
107494                 inlineSources: compilerOptions.inlineSources,
107495                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
107496                 writeBundleFileInfo: !!bundleBuildInfo,
107497                 relativeToBuildInfo: relativeToBuildInfo
107498             };
107499             // Create a printer to print the nodes
107500             var printer = createPrinter(printerOptions, {
107501                 // resolver hooks
107502                 hasGlobalName: resolver.hasGlobalName,
107503                 // transform hooks
107504                 onEmitNode: transform.emitNodeWithNotification,
107505                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
107506                 substituteNode: transform.substituteNode,
107507             });
107508             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
107509             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
107510             // Clean up emit nodes on parse tree
107511             transform.dispose();
107512             if (bundleBuildInfo)
107513                 bundleBuildInfo.js = printer.bundleFileInfo;
107514         }
107515         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
107516             if (!sourceFileOrBundle)
107517                 return;
107518             if (!declarationFilePath) {
107519                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
107520                     emitSkipped = true;
107521                 return;
107522             }
107523             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
107524             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
107525             // Setup and perform the transformation to retrieve declarations from the input files
107526             var inputListOrBundle = ts.outFile(compilerOptions) ? [ts.factory.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
107527             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
107528                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
107529                 // Do that here when emitting only dts files
107530                 filesForEmit.forEach(collectLinkedAliases);
107531             }
107532             var declarationTransform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
107533             if (ts.length(declarationTransform.diagnostics)) {
107534                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
107535                     var diagnostic = _b[_a];
107536                     emitterDiagnostics.add(diagnostic);
107537                 }
107538             }
107539             var printerOptions = {
107540                 removeComments: compilerOptions.removeComments,
107541                 newLine: compilerOptions.newLine,
107542                 noEmitHelpers: true,
107543                 module: compilerOptions.module,
107544                 target: compilerOptions.target,
107545                 sourceMap: compilerOptions.sourceMap,
107546                 inlineSourceMap: compilerOptions.inlineSourceMap,
107547                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
107548                 onlyPrintJsDocStyle: true,
107549                 writeBundleFileInfo: !!bundleBuildInfo,
107550                 recordInternalSection: !!bundleBuildInfo,
107551                 relativeToBuildInfo: relativeToBuildInfo
107552             };
107553             var declarationPrinter = createPrinter(printerOptions, {
107554                 // resolver hooks
107555                 hasGlobalName: resolver.hasGlobalName,
107556                 // transform hooks
107557                 onEmitNode: declarationTransform.emitNodeWithNotification,
107558                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
107559                 substituteNode: declarationTransform.substituteNode,
107560             });
107561             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
107562             emitSkipped = emitSkipped || declBlocked;
107563             if (!declBlocked || forceDtsEmit) {
107564                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
107565                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
107566                     sourceMap: !forceDtsEmit && compilerOptions.declarationMap,
107567                     sourceRoot: compilerOptions.sourceRoot,
107568                     mapRoot: compilerOptions.mapRoot,
107569                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
107570                     // Explicitly do not passthru either `inline` option
107571                 });
107572                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 303 /* SourceFile */) {
107573                     var sourceFile = declarationTransform.transformed[0];
107574                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
107575                 }
107576             }
107577             declarationTransform.dispose();
107578             if (bundleBuildInfo)
107579                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
107580         }
107581         function collectLinkedAliases(node) {
107582             if (ts.isExportAssignment(node)) {
107583                 if (node.expression.kind === 79 /* Identifier */) {
107584                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
107585                 }
107586                 return;
107587             }
107588             else if (ts.isExportSpecifier(node)) {
107589                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
107590                 return;
107591             }
107592             ts.forEachChild(node, collectLinkedAliases);
107593         }
107594         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
107595             var bundle = sourceFileOrBundle.kind === 304 /* Bundle */ ? sourceFileOrBundle : undefined;
107596             var sourceFile = sourceFileOrBundle.kind === 303 /* SourceFile */ ? sourceFileOrBundle : undefined;
107597             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
107598             var sourceMapGenerator;
107599             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
107600                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
107601             }
107602             if (bundle) {
107603                 printer.writeBundle(bundle, writer, sourceMapGenerator);
107604             }
107605             else {
107606                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
107607             }
107608             if (sourceMapGenerator) {
107609                 if (sourceMapDataList) {
107610                     sourceMapDataList.push({
107611                         inputSourceFileNames: sourceMapGenerator.getSources(),
107612                         sourceMap: sourceMapGenerator.toJSON()
107613                     });
107614                 }
107615                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
107616                 if (sourceMappingURL) {
107617                     if (!writer.isAtStartOfLine())
107618                         writer.rawWrite(newLine);
107619                     writer.writeComment("//# ".concat("sourceMappingURL", "=").concat(sourceMappingURL)); // Tools can sometimes see this line as a source mapping url comment
107620                 }
107621                 // Write the source map
107622                 if (sourceMapFilePath) {
107623                     var sourceMap = sourceMapGenerator.toString();
107624                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
107625                 }
107626             }
107627             else {
107628                 writer.writeLine();
107629             }
107630             // Write the output file
107631             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
107632             // Reset state
107633             writer.clear();
107634         }
107635         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
107636             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
107637                 && (sourceFileOrBundle.kind !== 303 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
107638         }
107639         function getSourceRoot(mapOptions) {
107640             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
107641             // relative paths of the sources list in the sourcemap
107642             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
107643             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
107644         }
107645         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
107646             if (mapOptions.sourceRoot)
107647                 return host.getCommonSourceDirectory();
107648             if (mapOptions.mapRoot) {
107649                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
107650                 if (sourceFile) {
107651                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
107652                     // 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
107653                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
107654                 }
107655                 if (ts.getRootLength(sourceMapDir) === 0) {
107656                     // The relative paths are relative to the common directory
107657                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
107658                 }
107659                 return sourceMapDir;
107660             }
107661             return ts.getDirectoryPath(ts.normalizePath(filePath));
107662         }
107663         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
107664             if (mapOptions.inlineSourceMap) {
107665                 // Encode the sourceMap into the sourceMap url
107666                 var sourceMapText = sourceMapGenerator.toString();
107667                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
107668                 return "data:application/json;base64,".concat(base64SourceMapText);
107669             }
107670             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
107671             if (mapOptions.mapRoot) {
107672                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
107673                 if (sourceFile) {
107674                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
107675                     // 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
107676                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
107677                 }
107678                 if (ts.getRootLength(sourceMapDir) === 0) {
107679                     // The relative paths are relative to the common directory
107680                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
107681                     return encodeURI(ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
107682                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
107683                     host.getCurrentDirectory(), host.getCanonicalFileName, 
107684                     /*isAbsolutePathAnUrl*/ true));
107685                 }
107686                 else {
107687                     return encodeURI(ts.combinePaths(sourceMapDir, sourceMapFile));
107688                 }
107689             }
107690             return encodeURI(sourceMapFile);
107691         }
107692     }
107693     ts.emitFiles = emitFiles;
107694     /*@internal*/
107695     function getBuildInfoText(buildInfo) {
107696         return JSON.stringify(buildInfo);
107697     }
107698     ts.getBuildInfoText = getBuildInfoText;
107699     /*@internal*/
107700     function getBuildInfo(buildInfoText) {
107701         return JSON.parse(buildInfoText);
107702     }
107703     ts.getBuildInfo = getBuildInfo;
107704     /*@internal*/
107705     ts.notImplementedResolver = {
107706         hasGlobalName: ts.notImplemented,
107707         getReferencedExportContainer: ts.notImplemented,
107708         getReferencedImportDeclaration: ts.notImplemented,
107709         getReferencedDeclarationWithCollidingName: ts.notImplemented,
107710         isDeclarationWithCollidingName: ts.notImplemented,
107711         isValueAliasDeclaration: ts.notImplemented,
107712         isReferencedAliasDeclaration: ts.notImplemented,
107713         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
107714         getNodeCheckFlags: ts.notImplemented,
107715         isDeclarationVisible: ts.notImplemented,
107716         isLateBound: function (_node) { return false; },
107717         collectLinkedAliases: ts.notImplemented,
107718         isImplementationOfOverload: ts.notImplemented,
107719         isRequiredInitializedParameter: ts.notImplemented,
107720         isOptionalUninitializedParameterProperty: ts.notImplemented,
107721         isExpandoFunctionDeclaration: ts.notImplemented,
107722         getPropertiesOfContainerFunction: ts.notImplemented,
107723         createTypeOfDeclaration: ts.notImplemented,
107724         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
107725         createTypeOfExpression: ts.notImplemented,
107726         createLiteralConstValue: ts.notImplemented,
107727         isSymbolAccessible: ts.notImplemented,
107728         isEntityNameVisible: ts.notImplemented,
107729         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
107730         getConstantValue: ts.notImplemented,
107731         getReferencedValueDeclaration: ts.notImplemented,
107732         getTypeReferenceSerializationKind: ts.notImplemented,
107733         isOptionalParameter: ts.notImplemented,
107734         moduleExportsSomeValue: ts.notImplemented,
107735         isArgumentsLocalBinding: ts.notImplemented,
107736         getExternalModuleFileFromDeclaration: ts.notImplemented,
107737         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
107738         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
107739         isLiteralConstDeclaration: ts.notImplemented,
107740         getJsxFactoryEntity: ts.notImplemented,
107741         getJsxFragmentFactoryEntity: ts.notImplemented,
107742         getAllAccessorDeclarations: ts.notImplemented,
107743         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
107744         isBindingCapturedByNode: ts.notImplemented,
107745         getDeclarationStatementsForSourceFile: ts.notImplemented,
107746         isImportRequiredByAugmentation: ts.notImplemented,
107747     };
107748     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
107749         var _a;
107750         var jsBundle = ts.Debug.checkDefined(bundle.js);
107751         var prologueMap = ((_a = jsBundle.sources) === null || _a === void 0 ? void 0 : _a.prologues) && ts.arrayToMap(jsBundle.sources.prologues, function (prologueInfo) { return prologueInfo.file; });
107752         return bundle.sourceFiles.map(function (fileName, index) {
107753             var _a, _b;
107754             var prologueInfo = prologueMap === null || prologueMap === void 0 ? void 0 : prologueMap.get(index);
107755             var statements = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.directives.map(function (directive) {
107756                 var literal = ts.setTextRange(ts.factory.createStringLiteral(directive.expression.text), directive.expression);
107757                 var statement = ts.setTextRange(ts.factory.createExpressionStatement(literal), directive);
107758                 ts.setParent(literal, statement);
107759                 return statement;
107760             });
107761             var eofToken = ts.factory.createToken(1 /* EndOfFileToken */);
107762             var sourceFile = ts.factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */);
107763             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
107764             sourceFile.text = (_a = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text) !== null && _a !== void 0 ? _a : "";
107765             ts.setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text.length) !== null && _b !== void 0 ? _b : 0);
107766             ts.setEachParent(sourceFile.statements, sourceFile);
107767             ts.setTextRangePosWidth(eofToken, sourceFile.end, 0);
107768             ts.setParent(eofToken, sourceFile);
107769             return sourceFile;
107770         });
107771     }
107772     /*@internal*/
107773     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
107774         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
107775         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
107776         if (!buildInfoText)
107777             return buildInfoPath;
107778         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
107779         if (!jsFileText)
107780             return jsFilePath;
107781         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
107782         // error if no source map or for now if inline sourcemap
107783         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
107784             return sourceMapFilePath || "inline sourcemap decoding";
107785         // read declaration text
107786         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
107787         if (declarationFilePath && !declarationText)
107788             return declarationFilePath;
107789         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
107790         // error if no source map or for now if inline sourcemap
107791         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
107792             return declarationMapPath || "inline sourcemap decoding";
107793         var buildInfo = getBuildInfo(buildInfoText);
107794         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
107795             return buildInfoPath;
107796         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
107797         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
107798         /*onlyOwnText*/ true);
107799         var outputFiles = [];
107800         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
107801         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
107802         var emitHost = {
107803             getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }),
107804             getCanonicalFileName: host.getCanonicalFileName,
107805             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
107806             getCompilerOptions: function () { return config.options; },
107807             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
107808             getNewLine: function () { return host.getNewLine(); },
107809             getSourceFile: ts.returnUndefined,
107810             getSourceFileByPath: ts.returnUndefined,
107811             getSourceFiles: function () { return sourceFilesForJsEmit; },
107812             getLibFileFromReference: ts.notImplemented,
107813             isSourceFileFromExternalLibrary: ts.returnFalse,
107814             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
107815             getProjectReferenceRedirect: ts.returnUndefined,
107816             isSourceOfProjectReferenceRedirect: ts.returnFalse,
107817             writeFile: function (name, text, writeByteOrderMark) {
107818                 switch (name) {
107819                     case jsFilePath:
107820                         if (jsFileText === text)
107821                             return;
107822                         break;
107823                     case sourceMapFilePath:
107824                         if (sourceMapText === text)
107825                             return;
107826                         break;
107827                     case buildInfoPath:
107828                         var newBuildInfo = getBuildInfo(text);
107829                         newBuildInfo.program = buildInfo.program;
107830                         // Update sourceFileInfo
107831                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
107832                         newBuildInfo.bundle.js.sources = js.sources;
107833                         if (dts) {
107834                             newBuildInfo.bundle.dts.sources = dts.sources;
107835                         }
107836                         newBuildInfo.bundle.sourceFiles = sourceFiles;
107837                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
107838                         return;
107839                     case declarationFilePath:
107840                         if (declarationText === text)
107841                             return;
107842                         break;
107843                     case declarationMapPath:
107844                         if (declarationMapText === text)
107845                             return;
107846                         break;
107847                     default:
107848                         ts.Debug.fail("Unexpected path: ".concat(name));
107849                 }
107850                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
107851             },
107852             isEmitBlocked: ts.returnFalse,
107853             readFile: function (f) { return host.readFile(f); },
107854             fileExists: function (f) { return host.fileExists(f); },
107855             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
107856             getProgramBuildInfo: ts.returnUndefined,
107857             getSourceFileFromReference: ts.returnUndefined,
107858             redirectTargetsMap: ts.createMultiMap(),
107859             getFileIncludeReasons: ts.notImplemented,
107860         };
107861         emitFiles(ts.notImplementedResolver, emitHost, 
107862         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
107863         return outputFiles;
107864     }
107865     ts.emitUsingBuildInfo = emitUsingBuildInfo;
107866     var PipelinePhase;
107867     (function (PipelinePhase) {
107868         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
107869         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
107870         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
107871         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
107872         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
107873     })(PipelinePhase || (PipelinePhase = {}));
107874     function createPrinter(printerOptions, handlers) {
107875         if (printerOptions === void 0) { printerOptions = {}; }
107876         if (handlers === void 0) { handlers = {}; }
107877         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, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
107878         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
107879         var newLine = ts.getNewLineCharacter(printerOptions);
107880         var moduleKind = ts.getEmitModuleKind(printerOptions);
107881         var bundledHelpers = new ts.Map();
107882         var currentSourceFile;
107883         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
107884         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
107885         var generatedNames; // Set of names generated by the NameGenerator.
107886         var tempFlagsStack; // Stack of enclosing name generation scopes.
107887         var tempFlags; // TempFlags for the current name generation scope.
107888         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
107889         var reservedNames; // TempFlags to reserve in nested name generation scopes.
107890         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
107891         var nextListElementPos; // See comment in `getLeadingLineTerminatorCount`.
107892         var writer;
107893         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
107894         var write = writeBase;
107895         var isOwnFileEmit;
107896         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
107897         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
107898         var recordInternalSection = printerOptions.recordInternalSection;
107899         var sourceFileTextPos = 0;
107900         var sourceFileTextKind = "text" /* Text */;
107901         // Source Maps
107902         var sourceMapsDisabled = true;
107903         var sourceMapGenerator;
107904         var sourceMapSource;
107905         var sourceMapSourceIndex = -1;
107906         var mostRecentlyAddedSourceMapSource;
107907         var mostRecentlyAddedSourceMapSourceIndex = -1;
107908         // Comments
107909         var containerPos = -1;
107910         var containerEnd = -1;
107911         var declarationListContainerEnd = -1;
107912         var currentLineMap;
107913         var detachedCommentsInfo;
107914         var hasWrittenComment = false;
107915         var commentsDisabled = !!printerOptions.removeComments;
107916         var lastSubstitution;
107917         var currentParenthesizerRule;
107918         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
107919         var parenthesizer = ts.factory.parenthesizer;
107920         var emitBinaryExpression = createEmitBinaryExpression();
107921         reset();
107922         return {
107923             // public API
107924             printNode: printNode,
107925             printList: printList,
107926             printFile: printFile,
107927             printBundle: printBundle,
107928             // internal API
107929             writeNode: writeNode,
107930             writeList: writeList,
107931             writeFile: writeFile,
107932             writeBundle: writeBundle,
107933             bundleFileInfo: bundleFileInfo
107934         };
107935         function printNode(hint, node, sourceFile) {
107936             switch (hint) {
107937                 case 0 /* SourceFile */:
107938                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
107939                     break;
107940                 case 2 /* IdentifierName */:
107941                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
107942                     break;
107943                 case 1 /* Expression */:
107944                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
107945                     break;
107946             }
107947             switch (node.kind) {
107948                 case 303 /* SourceFile */: return printFile(node);
107949                 case 304 /* Bundle */: return printBundle(node);
107950                 case 305 /* UnparsedSource */: return printUnparsedSource(node);
107951             }
107952             writeNode(hint, node, sourceFile, beginPrint());
107953             return endPrint();
107954         }
107955         function printList(format, nodes, sourceFile) {
107956             writeList(format, nodes, sourceFile, beginPrint());
107957             return endPrint();
107958         }
107959         function printBundle(bundle) {
107960             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
107961             return endPrint();
107962         }
107963         function printFile(sourceFile) {
107964             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
107965             return endPrint();
107966         }
107967         function printUnparsedSource(unparsed) {
107968             writeUnparsedSource(unparsed, beginPrint());
107969             return endPrint();
107970         }
107971         function writeNode(hint, node, sourceFile, output) {
107972             var previousWriter = writer;
107973             setWriter(output, /*_sourceMapGenerator*/ undefined);
107974             print(hint, node, sourceFile);
107975             reset();
107976             writer = previousWriter;
107977         }
107978         function writeList(format, nodes, sourceFile, output) {
107979             var previousWriter = writer;
107980             setWriter(output, /*_sourceMapGenerator*/ undefined);
107981             if (sourceFile) {
107982                 setSourceFile(sourceFile);
107983             }
107984             emitList(/*parentNode*/ undefined, nodes, format);
107985             reset();
107986             writer = previousWriter;
107987         }
107988         function getTextPosWithWriteLine() {
107989             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
107990         }
107991         function updateOrPushBundleFileTextLike(pos, end, kind) {
107992             var last = ts.lastOrUndefined(bundleFileInfo.sections);
107993             if (last && last.kind === kind) {
107994                 last.end = end;
107995             }
107996             else {
107997                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
107998             }
107999         }
108000         function recordBundleFileInternalSectionStart(node) {
108001             if (recordInternalSection &&
108002                 bundleFileInfo &&
108003                 currentSourceFile &&
108004                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
108005                 ts.isInternalDeclaration(node, currentSourceFile) &&
108006                 sourceFileTextKind !== "internal" /* Internal */) {
108007                 var prevSourceFileTextKind = sourceFileTextKind;
108008                 recordBundleFileTextLikeSection(writer.getTextPos());
108009                 sourceFileTextPos = getTextPosWithWriteLine();
108010                 sourceFileTextKind = "internal" /* Internal */;
108011                 return prevSourceFileTextKind;
108012             }
108013             return undefined;
108014         }
108015         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
108016             if (prevSourceFileTextKind) {
108017                 recordBundleFileTextLikeSection(writer.getTextPos());
108018                 sourceFileTextPos = getTextPosWithWriteLine();
108019                 sourceFileTextKind = prevSourceFileTextKind;
108020             }
108021         }
108022         function recordBundleFileTextLikeSection(end) {
108023             if (sourceFileTextPos < end) {
108024                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
108025                 return true;
108026             }
108027             return false;
108028         }
108029         function writeBundle(bundle, output, sourceMapGenerator) {
108030             var _a;
108031             isOwnFileEmit = false;
108032             var previousWriter = writer;
108033             setWriter(output, sourceMapGenerator);
108034             emitShebangIfNeeded(bundle);
108035             emitPrologueDirectivesIfNeeded(bundle);
108036             emitHelpers(bundle);
108037             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
108038             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
108039                 var prepend = _c[_b];
108040                 writeLine();
108041                 var pos = writer.getTextPos();
108042                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
108043                 if (savedSections)
108044                     bundleFileInfo.sections = [];
108045                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
108046                 if (bundleFileInfo) {
108047                     var newSections = bundleFileInfo.sections;
108048                     bundleFileInfo.sections = savedSections;
108049                     if (prepend.oldFileOfCurrentEmit)
108050                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
108051                     else {
108052                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
108053                         bundleFileInfo.sections.push({
108054                             pos: pos,
108055                             end: writer.getTextPos(),
108056                             kind: "prepend" /* Prepend */,
108057                             data: relativeToBuildInfo(prepend.fileName),
108058                             texts: newSections
108059                         });
108060                     }
108061                 }
108062             }
108063             sourceFileTextPos = getTextPosWithWriteLine();
108064             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
108065                 var sourceFile = _e[_d];
108066                 print(0 /* SourceFile */, sourceFile, sourceFile);
108067             }
108068             if (bundleFileInfo && bundle.sourceFiles.length) {
108069                 var end = writer.getTextPos();
108070                 if (recordBundleFileTextLikeSection(end)) {
108071                     // Store prologues
108072                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
108073                     if (prologues) {
108074                         if (!bundleFileInfo.sources)
108075                             bundleFileInfo.sources = {};
108076                         bundleFileInfo.sources.prologues = prologues;
108077                     }
108078                     // Store helpes
108079                     var helpers = getHelpersFromBundledSourceFiles(bundle);
108080                     if (helpers) {
108081                         if (!bundleFileInfo.sources)
108082                             bundleFileInfo.sources = {};
108083                         bundleFileInfo.sources.helpers = helpers;
108084                     }
108085                 }
108086             }
108087             reset();
108088             writer = previousWriter;
108089         }
108090         function writeUnparsedSource(unparsed, output) {
108091             var previousWriter = writer;
108092             setWriter(output, /*_sourceMapGenerator*/ undefined);
108093             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
108094             reset();
108095             writer = previousWriter;
108096         }
108097         function writeFile(sourceFile, output, sourceMapGenerator) {
108098             isOwnFileEmit = true;
108099             var previousWriter = writer;
108100             setWriter(output, sourceMapGenerator);
108101             emitShebangIfNeeded(sourceFile);
108102             emitPrologueDirectivesIfNeeded(sourceFile);
108103             print(0 /* SourceFile */, sourceFile, sourceFile);
108104             reset();
108105             writer = previousWriter;
108106         }
108107         function beginPrint() {
108108             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
108109         }
108110         function endPrint() {
108111             var text = ownWriter.getText();
108112             ownWriter.clear();
108113             return text;
108114         }
108115         function print(hint, node, sourceFile) {
108116             if (sourceFile) {
108117                 setSourceFile(sourceFile);
108118             }
108119             pipelineEmit(hint, node, /*parenthesizerRule*/ undefined);
108120         }
108121         function setSourceFile(sourceFile) {
108122             currentSourceFile = sourceFile;
108123             currentLineMap = undefined;
108124             detachedCommentsInfo = undefined;
108125             if (sourceFile) {
108126                 setSourceMapSource(sourceFile);
108127             }
108128         }
108129         function setWriter(_writer, _sourceMapGenerator) {
108130             if (_writer && printerOptions.omitTrailingSemicolon) {
108131                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
108132             }
108133             writer = _writer; // TODO: GH#18217
108134             sourceMapGenerator = _sourceMapGenerator;
108135             sourceMapsDisabled = !writer || !sourceMapGenerator;
108136         }
108137         function reset() {
108138             nodeIdToGeneratedName = [];
108139             autoGeneratedIdToGeneratedName = [];
108140             generatedNames = new ts.Set();
108141             tempFlagsStack = [];
108142             tempFlags = 0 /* Auto */;
108143             reservedNamesStack = [];
108144             currentSourceFile = undefined;
108145             currentLineMap = undefined;
108146             detachedCommentsInfo = undefined;
108147             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
108148         }
108149         function getCurrentLineMap() {
108150             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
108151         }
108152         function emit(node, parenthesizerRule) {
108153             if (node === undefined)
108154                 return;
108155             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
108156             pipelineEmit(4 /* Unspecified */, node, parenthesizerRule);
108157             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
108158         }
108159         function emitIdentifierName(node) {
108160             if (node === undefined)
108161                 return;
108162             pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined);
108163         }
108164         function emitExpression(node, parenthesizerRule) {
108165             if (node === undefined)
108166                 return;
108167             pipelineEmit(1 /* Expression */, node, parenthesizerRule);
108168         }
108169         function emitJsxAttributeValue(node) {
108170             pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
108171         }
108172         function beforeEmitNode(node) {
108173             if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
108174                 preserveSourceNewlines = false;
108175             }
108176         }
108177         function afterEmitNode(savedPreserveSourceNewlines) {
108178             preserveSourceNewlines = savedPreserveSourceNewlines;
108179         }
108180         function pipelineEmit(emitHint, node, parenthesizerRule) {
108181             currentParenthesizerRule = parenthesizerRule;
108182             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
108183             pipelinePhase(emitHint, node);
108184             currentParenthesizerRule = undefined;
108185         }
108186         function shouldEmitComments(node) {
108187             return !commentsDisabled && !ts.isSourceFile(node);
108188         }
108189         function shouldEmitSourceMaps(node) {
108190             return !sourceMapsDisabled &&
108191                 !ts.isSourceFile(node) &&
108192                 !ts.isInJsonFile(node) &&
108193                 !ts.isUnparsedSource(node) &&
108194                 !ts.isUnparsedPrepend(node);
108195         }
108196         function getPipelinePhase(phase, emitHint, node) {
108197             switch (phase) {
108198                 case 0 /* Notification */:
108199                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
108200                         return pipelineEmitWithNotification;
108201                     }
108202                 // falls through
108203                 case 1 /* Substitution */:
108204                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) {
108205                         if (currentParenthesizerRule) {
108206                             lastSubstitution = currentParenthesizerRule(lastSubstitution);
108207                         }
108208                         return pipelineEmitWithSubstitution;
108209                     }
108210                 // falls through
108211                 case 2 /* Comments */:
108212                     if (shouldEmitComments(node)) {
108213                         return pipelineEmitWithComments;
108214                     }
108215                 // falls through
108216                 case 3 /* SourceMaps */:
108217                     if (shouldEmitSourceMaps(node)) {
108218                         return pipelineEmitWithSourceMaps;
108219                     }
108220                 // falls through
108221                 case 4 /* Emit */:
108222                     return pipelineEmitWithHint;
108223                 default:
108224                     return ts.Debug.assertNever(phase);
108225             }
108226         }
108227         function getNextPipelinePhase(currentPhase, emitHint, node) {
108228             return getPipelinePhase(currentPhase + 1, emitHint, node);
108229         }
108230         function pipelineEmitWithNotification(hint, node) {
108231             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
108232             onEmitNode(hint, node, pipelinePhase);
108233         }
108234         function pipelineEmitWithHint(hint, node) {
108235             onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node);
108236             if (preserveSourceNewlines) {
108237                 var savedPreserveSourceNewlines = preserveSourceNewlines;
108238                 beforeEmitNode(node);
108239                 pipelineEmitWithHintWorker(hint, node);
108240                 afterEmitNode(savedPreserveSourceNewlines);
108241             }
108242             else {
108243                 pipelineEmitWithHintWorker(hint, node);
108244             }
108245             onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node);
108246             // clear the parenthesizer rule as we ascend
108247             currentParenthesizerRule = undefined;
108248         }
108249         function pipelineEmitWithHintWorker(hint, node, allowSnippets) {
108250             if (allowSnippets === void 0) { allowSnippets = true; }
108251             if (allowSnippets) {
108252                 var snippet = ts.getSnippetElement(node);
108253                 if (snippet) {
108254                     return emitSnippetNode(hint, node, snippet);
108255                 }
108256             }
108257             if (hint === 0 /* SourceFile */)
108258                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
108259             if (hint === 2 /* IdentifierName */)
108260                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
108261             if (hint === 6 /* JsxAttributeValue */)
108262                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
108263             if (hint === 3 /* MappedTypeParameter */)
108264                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
108265             if (hint === 5 /* EmbeddedStatement */) {
108266                 ts.Debug.assertNode(node, ts.isEmptyStatement);
108267                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
108268             }
108269             if (hint === 4 /* Unspecified */) {
108270                 switch (node.kind) {
108271                     // Pseudo-literals
108272                     case 15 /* TemplateHead */:
108273                     case 16 /* TemplateMiddle */:
108274                     case 17 /* TemplateTail */:
108275                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
108276                     // Identifiers
108277                     case 79 /* Identifier */:
108278                         return emitIdentifier(node);
108279                     // PrivateIdentifiers
108280                     case 80 /* PrivateIdentifier */:
108281                         return emitPrivateIdentifier(node);
108282                     // Parse tree nodes
108283                     // Names
108284                     case 160 /* QualifiedName */:
108285                         return emitQualifiedName(node);
108286                     case 161 /* ComputedPropertyName */:
108287                         return emitComputedPropertyName(node);
108288                     // Signature elements
108289                     case 162 /* TypeParameter */:
108290                         return emitTypeParameter(node);
108291                     case 163 /* Parameter */:
108292                         return emitParameter(node);
108293                     case 164 /* Decorator */:
108294                         return emitDecorator(node);
108295                     // Type members
108296                     case 165 /* PropertySignature */:
108297                         return emitPropertySignature(node);
108298                     case 166 /* PropertyDeclaration */:
108299                         return emitPropertyDeclaration(node);
108300                     case 167 /* MethodSignature */:
108301                         return emitMethodSignature(node);
108302                     case 168 /* MethodDeclaration */:
108303                         return emitMethodDeclaration(node);
108304                     case 169 /* ClassStaticBlockDeclaration */:
108305                         return emitClassStaticBlockDeclaration(node);
108306                     case 170 /* Constructor */:
108307                         return emitConstructor(node);
108308                     case 171 /* GetAccessor */:
108309                     case 172 /* SetAccessor */:
108310                         return emitAccessorDeclaration(node);
108311                     case 173 /* CallSignature */:
108312                         return emitCallSignature(node);
108313                     case 174 /* ConstructSignature */:
108314                         return emitConstructSignature(node);
108315                     case 175 /* IndexSignature */:
108316                         return emitIndexSignature(node);
108317                     // Types
108318                     case 176 /* TypePredicate */:
108319                         return emitTypePredicate(node);
108320                     case 177 /* TypeReference */:
108321                         return emitTypeReference(node);
108322                     case 178 /* FunctionType */:
108323                         return emitFunctionType(node);
108324                     case 179 /* ConstructorType */:
108325                         return emitConstructorType(node);
108326                     case 180 /* TypeQuery */:
108327                         return emitTypeQuery(node);
108328                     case 181 /* TypeLiteral */:
108329                         return emitTypeLiteral(node);
108330                     case 182 /* ArrayType */:
108331                         return emitArrayType(node);
108332                     case 183 /* TupleType */:
108333                         return emitTupleType(node);
108334                     case 184 /* OptionalType */:
108335                         return emitOptionalType(node);
108336                     // SyntaxKind.RestType is handled below
108337                     case 186 /* UnionType */:
108338                         return emitUnionType(node);
108339                     case 187 /* IntersectionType */:
108340                         return emitIntersectionType(node);
108341                     case 188 /* ConditionalType */:
108342                         return emitConditionalType(node);
108343                     case 189 /* InferType */:
108344                         return emitInferType(node);
108345                     case 190 /* ParenthesizedType */:
108346                         return emitParenthesizedType(node);
108347                     case 227 /* ExpressionWithTypeArguments */:
108348                         return emitExpressionWithTypeArguments(node);
108349                     case 191 /* ThisType */:
108350                         return emitThisType();
108351                     case 192 /* TypeOperator */:
108352                         return emitTypeOperator(node);
108353                     case 193 /* IndexedAccessType */:
108354                         return emitIndexedAccessType(node);
108355                     case 194 /* MappedType */:
108356                         return emitMappedType(node);
108357                     case 195 /* LiteralType */:
108358                         return emitLiteralType(node);
108359                     case 196 /* NamedTupleMember */:
108360                         return emitNamedTupleMember(node);
108361                     case 197 /* TemplateLiteralType */:
108362                         return emitTemplateType(node);
108363                     case 198 /* TemplateLiteralTypeSpan */:
108364                         return emitTemplateTypeSpan(node);
108365                     case 199 /* ImportType */:
108366                         return emitImportTypeNode(node);
108367                     // Binding patterns
108368                     case 200 /* ObjectBindingPattern */:
108369                         return emitObjectBindingPattern(node);
108370                     case 201 /* ArrayBindingPattern */:
108371                         return emitArrayBindingPattern(node);
108372                     case 202 /* BindingElement */:
108373                         return emitBindingElement(node);
108374                     // Misc
108375                     case 232 /* TemplateSpan */:
108376                         return emitTemplateSpan(node);
108377                     case 233 /* SemicolonClassElement */:
108378                         return emitSemicolonClassElement();
108379                     // Statements
108380                     case 234 /* Block */:
108381                         return emitBlock(node);
108382                     case 236 /* VariableStatement */:
108383                         return emitVariableStatement(node);
108384                     case 235 /* EmptyStatement */:
108385                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
108386                     case 237 /* ExpressionStatement */:
108387                         return emitExpressionStatement(node);
108388                     case 238 /* IfStatement */:
108389                         return emitIfStatement(node);
108390                     case 239 /* DoStatement */:
108391                         return emitDoStatement(node);
108392                     case 240 /* WhileStatement */:
108393                         return emitWhileStatement(node);
108394                     case 241 /* ForStatement */:
108395                         return emitForStatement(node);
108396                     case 242 /* ForInStatement */:
108397                         return emitForInStatement(node);
108398                     case 243 /* ForOfStatement */:
108399                         return emitForOfStatement(node);
108400                     case 244 /* ContinueStatement */:
108401                         return emitContinueStatement(node);
108402                     case 245 /* BreakStatement */:
108403                         return emitBreakStatement(node);
108404                     case 246 /* ReturnStatement */:
108405                         return emitReturnStatement(node);
108406                     case 247 /* WithStatement */:
108407                         return emitWithStatement(node);
108408                     case 248 /* SwitchStatement */:
108409                         return emitSwitchStatement(node);
108410                     case 249 /* LabeledStatement */:
108411                         return emitLabeledStatement(node);
108412                     case 250 /* ThrowStatement */:
108413                         return emitThrowStatement(node);
108414                     case 251 /* TryStatement */:
108415                         return emitTryStatement(node);
108416                     case 252 /* DebuggerStatement */:
108417                         return emitDebuggerStatement(node);
108418                     // Declarations
108419                     case 253 /* VariableDeclaration */:
108420                         return emitVariableDeclaration(node);
108421                     case 254 /* VariableDeclarationList */:
108422                         return emitVariableDeclarationList(node);
108423                     case 255 /* FunctionDeclaration */:
108424                         return emitFunctionDeclaration(node);
108425                     case 256 /* ClassDeclaration */:
108426                         return emitClassDeclaration(node);
108427                     case 257 /* InterfaceDeclaration */:
108428                         return emitInterfaceDeclaration(node);
108429                     case 258 /* TypeAliasDeclaration */:
108430                         return emitTypeAliasDeclaration(node);
108431                     case 259 /* EnumDeclaration */:
108432                         return emitEnumDeclaration(node);
108433                     case 260 /* ModuleDeclaration */:
108434                         return emitModuleDeclaration(node);
108435                     case 261 /* ModuleBlock */:
108436                         return emitModuleBlock(node);
108437                     case 262 /* CaseBlock */:
108438                         return emitCaseBlock(node);
108439                     case 263 /* NamespaceExportDeclaration */:
108440                         return emitNamespaceExportDeclaration(node);
108441                     case 264 /* ImportEqualsDeclaration */:
108442                         return emitImportEqualsDeclaration(node);
108443                     case 265 /* ImportDeclaration */:
108444                         return emitImportDeclaration(node);
108445                     case 266 /* ImportClause */:
108446                         return emitImportClause(node);
108447                     case 267 /* NamespaceImport */:
108448                         return emitNamespaceImport(node);
108449                     case 273 /* NamespaceExport */:
108450                         return emitNamespaceExport(node);
108451                     case 268 /* NamedImports */:
108452                         return emitNamedImports(node);
108453                     case 269 /* ImportSpecifier */:
108454                         return emitImportSpecifier(node);
108455                     case 270 /* ExportAssignment */:
108456                         return emitExportAssignment(node);
108457                     case 271 /* ExportDeclaration */:
108458                         return emitExportDeclaration(node);
108459                     case 272 /* NamedExports */:
108460                         return emitNamedExports(node);
108461                     case 274 /* ExportSpecifier */:
108462                         return emitExportSpecifier(node);
108463                     case 292 /* AssertClause */:
108464                         return emitAssertClause(node);
108465                     case 293 /* AssertEntry */:
108466                         return emitAssertEntry(node);
108467                     case 275 /* MissingDeclaration */:
108468                         return;
108469                     // Module references
108470                     case 276 /* ExternalModuleReference */:
108471                         return emitExternalModuleReference(node);
108472                     // JSX (non-expression)
108473                     case 11 /* JsxText */:
108474                         return emitJsxText(node);
108475                     case 279 /* JsxOpeningElement */:
108476                     case 282 /* JsxOpeningFragment */:
108477                         return emitJsxOpeningElementOrFragment(node);
108478                     case 280 /* JsxClosingElement */:
108479                     case 283 /* JsxClosingFragment */:
108480                         return emitJsxClosingElementOrFragment(node);
108481                     case 284 /* JsxAttribute */:
108482                         return emitJsxAttribute(node);
108483                     case 285 /* JsxAttributes */:
108484                         return emitJsxAttributes(node);
108485                     case 286 /* JsxSpreadAttribute */:
108486                         return emitJsxSpreadAttribute(node);
108487                     case 287 /* JsxExpression */:
108488                         return emitJsxExpression(node);
108489                     // Clauses
108490                     case 288 /* CaseClause */:
108491                         return emitCaseClause(node);
108492                     case 289 /* DefaultClause */:
108493                         return emitDefaultClause(node);
108494                     case 290 /* HeritageClause */:
108495                         return emitHeritageClause(node);
108496                     case 291 /* CatchClause */:
108497                         return emitCatchClause(node);
108498                     // Property assignments
108499                     case 294 /* PropertyAssignment */:
108500                         return emitPropertyAssignment(node);
108501                     case 295 /* ShorthandPropertyAssignment */:
108502                         return emitShorthandPropertyAssignment(node);
108503                     case 296 /* SpreadAssignment */:
108504                         return emitSpreadAssignment(node);
108505                     // Enum
108506                     case 297 /* EnumMember */:
108507                         return emitEnumMember(node);
108508                     // Unparsed
108509                     case 298 /* UnparsedPrologue */:
108510                         return writeUnparsedNode(node);
108511                     case 305 /* UnparsedSource */:
108512                     case 299 /* UnparsedPrepend */:
108513                         return emitUnparsedSourceOrPrepend(node);
108514                     case 300 /* UnparsedText */:
108515                     case 301 /* UnparsedInternalText */:
108516                         return emitUnparsedTextLike(node);
108517                     case 302 /* UnparsedSyntheticReference */:
108518                         return emitUnparsedSyntheticReference(node);
108519                     // Top-level nodes
108520                     case 303 /* SourceFile */:
108521                         return emitSourceFile(node);
108522                     case 304 /* Bundle */:
108523                         return ts.Debug.fail("Bundles should be printed using printBundle");
108524                     // SyntaxKind.UnparsedSource (handled above)
108525                     case 306 /* InputFiles */:
108526                         return ts.Debug.fail("InputFiles should not be printed");
108527                     // JSDoc nodes (only used in codefixes currently)
108528                     case 307 /* JSDocTypeExpression */:
108529                         return emitJSDocTypeExpression(node);
108530                     case 308 /* JSDocNameReference */:
108531                         return emitJSDocNameReference(node);
108532                     case 310 /* JSDocAllType */:
108533                         return writePunctuation("*");
108534                     case 311 /* JSDocUnknownType */:
108535                         return writePunctuation("?");
108536                     case 312 /* JSDocNullableType */:
108537                         return emitJSDocNullableType(node);
108538                     case 313 /* JSDocNonNullableType */:
108539                         return emitJSDocNonNullableType(node);
108540                     case 314 /* JSDocOptionalType */:
108541                         return emitJSDocOptionalType(node);
108542                     case 315 /* JSDocFunctionType */:
108543                         return emitJSDocFunctionType(node);
108544                     case 185 /* RestType */:
108545                     case 316 /* JSDocVariadicType */:
108546                         return emitRestOrJSDocVariadicType(node);
108547                     case 317 /* JSDocNamepathType */:
108548                         return;
108549                     case 318 /* JSDocComment */:
108550                         return emitJSDoc(node);
108551                     case 320 /* JSDocTypeLiteral */:
108552                         return emitJSDocTypeLiteral(node);
108553                     case 321 /* JSDocSignature */:
108554                         return emitJSDocSignature(node);
108555                     case 325 /* JSDocTag */:
108556                     case 330 /* JSDocClassTag */:
108557                         return emitJSDocSimpleTag(node);
108558                     case 326 /* JSDocAugmentsTag */:
108559                     case 327 /* JSDocImplementsTag */:
108560                         return emitJSDocHeritageTag(node);
108561                     case 328 /* JSDocAuthorTag */:
108562                     case 329 /* JSDocDeprecatedTag */:
108563                         return;
108564                     // SyntaxKind.JSDocClassTag (see JSDocTag, above)
108565                     case 331 /* JSDocPublicTag */:
108566                     case 332 /* JSDocPrivateTag */:
108567                     case 333 /* JSDocProtectedTag */:
108568                     case 334 /* JSDocReadonlyTag */:
108569                     case 335 /* JSDocOverrideTag */:
108570                         return;
108571                     case 336 /* JSDocCallbackTag */:
108572                         return emitJSDocCallbackTag(node);
108573                     // SyntaxKind.JSDocEnumTag (see below)
108574                     case 338 /* JSDocParameterTag */:
108575                     case 345 /* JSDocPropertyTag */:
108576                         return emitJSDocPropertyLikeTag(node);
108577                     case 337 /* JSDocEnumTag */:
108578                     case 339 /* JSDocReturnTag */:
108579                     case 340 /* JSDocThisTag */:
108580                     case 341 /* JSDocTypeTag */:
108581                         return emitJSDocSimpleTypedTag(node);
108582                     case 342 /* JSDocTemplateTag */:
108583                         return emitJSDocTemplateTag(node);
108584                     case 343 /* JSDocTypedefTag */:
108585                         return emitJSDocTypedefTag(node);
108586                     case 344 /* JSDocSeeTag */:
108587                         return emitJSDocSeeTag(node);
108588                     // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above)
108589                     // Transformation nodes
108590                     case 347 /* NotEmittedStatement */:
108591                     case 351 /* EndOfDeclarationMarker */:
108592                     case 350 /* MergeDeclarationMarker */:
108593                         return;
108594                 }
108595                 if (ts.isExpression(node)) {
108596                     hint = 1 /* Expression */;
108597                     if (substituteNode !== ts.noEmitSubstitution) {
108598                         var substitute = substituteNode(hint, node) || node;
108599                         if (substitute !== node) {
108600                             node = substitute;
108601                             if (currentParenthesizerRule) {
108602                                 node = currentParenthesizerRule(node);
108603                             }
108604                         }
108605                     }
108606                 }
108607             }
108608             if (hint === 1 /* Expression */) {
108609                 switch (node.kind) {
108610                     // Literals
108611                     case 8 /* NumericLiteral */:
108612                     case 9 /* BigIntLiteral */:
108613                         return emitNumericOrBigIntLiteral(node);
108614                     case 10 /* StringLiteral */:
108615                     case 13 /* RegularExpressionLiteral */:
108616                     case 14 /* NoSubstitutionTemplateLiteral */:
108617                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
108618                     // Identifiers
108619                     case 79 /* Identifier */:
108620                         return emitIdentifier(node);
108621                     case 80 /* PrivateIdentifier */:
108622                         return emitPrivateIdentifier(node);
108623                     // Expressions
108624                     case 203 /* ArrayLiteralExpression */:
108625                         return emitArrayLiteralExpression(node);
108626                     case 204 /* ObjectLiteralExpression */:
108627                         return emitObjectLiteralExpression(node);
108628                     case 205 /* PropertyAccessExpression */:
108629                         return emitPropertyAccessExpression(node);
108630                     case 206 /* ElementAccessExpression */:
108631                         return emitElementAccessExpression(node);
108632                     case 207 /* CallExpression */:
108633                         return emitCallExpression(node);
108634                     case 208 /* NewExpression */:
108635                         return emitNewExpression(node);
108636                     case 209 /* TaggedTemplateExpression */:
108637                         return emitTaggedTemplateExpression(node);
108638                     case 210 /* TypeAssertionExpression */:
108639                         return emitTypeAssertionExpression(node);
108640                     case 211 /* ParenthesizedExpression */:
108641                         return emitParenthesizedExpression(node);
108642                     case 212 /* FunctionExpression */:
108643                         return emitFunctionExpression(node);
108644                     case 213 /* ArrowFunction */:
108645                         return emitArrowFunction(node);
108646                     case 214 /* DeleteExpression */:
108647                         return emitDeleteExpression(node);
108648                     case 215 /* TypeOfExpression */:
108649                         return emitTypeOfExpression(node);
108650                     case 216 /* VoidExpression */:
108651                         return emitVoidExpression(node);
108652                     case 217 /* AwaitExpression */:
108653                         return emitAwaitExpression(node);
108654                     case 218 /* PrefixUnaryExpression */:
108655                         return emitPrefixUnaryExpression(node);
108656                     case 219 /* PostfixUnaryExpression */:
108657                         return emitPostfixUnaryExpression(node);
108658                     case 220 /* BinaryExpression */:
108659                         return emitBinaryExpression(node);
108660                     case 221 /* ConditionalExpression */:
108661                         return emitConditionalExpression(node);
108662                     case 222 /* TemplateExpression */:
108663                         return emitTemplateExpression(node);
108664                     case 223 /* YieldExpression */:
108665                         return emitYieldExpression(node);
108666                     case 224 /* SpreadElement */:
108667                         return emitSpreadElement(node);
108668                     case 225 /* ClassExpression */:
108669                         return emitClassExpression(node);
108670                     case 226 /* OmittedExpression */:
108671                         return;
108672                     case 228 /* AsExpression */:
108673                         return emitAsExpression(node);
108674                     case 229 /* NonNullExpression */:
108675                         return emitNonNullExpression(node);
108676                     case 230 /* MetaProperty */:
108677                         return emitMetaProperty(node);
108678                     case 231 /* SyntheticExpression */:
108679                         return ts.Debug.fail("SyntheticExpression should never be printed.");
108680                     // JSX
108681                     case 277 /* JsxElement */:
108682                         return emitJsxElement(node);
108683                     case 278 /* JsxSelfClosingElement */:
108684                         return emitJsxSelfClosingElement(node);
108685                     case 281 /* JsxFragment */:
108686                         return emitJsxFragment(node);
108687                     // Synthesized list
108688                     case 346 /* SyntaxList */:
108689                         return ts.Debug.fail("SyntaxList should not be printed");
108690                     // Transformation nodes
108691                     case 347 /* NotEmittedStatement */:
108692                         return;
108693                     case 348 /* PartiallyEmittedExpression */:
108694                         return emitPartiallyEmittedExpression(node);
108695                     case 349 /* CommaListExpression */:
108696                         return emitCommaList(node);
108697                     case 350 /* MergeDeclarationMarker */:
108698                     case 351 /* EndOfDeclarationMarker */:
108699                         return;
108700                     case 352 /* SyntheticReferenceExpression */:
108701                         return ts.Debug.fail("SyntheticReferenceExpression should not be printed");
108702                 }
108703             }
108704             if (ts.isKeyword(node.kind))
108705                 return writeTokenNode(node, writeKeyword);
108706             if (ts.isTokenKind(node.kind))
108707                 return writeTokenNode(node, writePunctuation);
108708             ts.Debug.fail("Unhandled SyntaxKind: ".concat(ts.Debug.formatSyntaxKind(node.kind), "."));
108709         }
108710         function emitMappedTypeParameter(node) {
108711             emit(node.name);
108712             writeSpace();
108713             writeKeyword("in");
108714             writeSpace();
108715             emit(node.constraint);
108716         }
108717         function pipelineEmitWithSubstitution(hint, node) {
108718             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
108719             ts.Debug.assertIsDefined(lastSubstitution);
108720             node = lastSubstitution;
108721             lastSubstitution = undefined;
108722             pipelinePhase(hint, node);
108723         }
108724         function getHelpersFromBundledSourceFiles(bundle) {
108725             var result;
108726             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
108727                 return undefined;
108728             }
108729             var bundledHelpers = new ts.Map();
108730             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
108731                 var sourceFile = _b[_a];
108732                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
108733                 var helpers = getSortedEmitHelpers(sourceFile);
108734                 if (!helpers)
108735                     continue;
108736                 for (var _c = 0, helpers_5 = helpers; _c < helpers_5.length; _c++) {
108737                     var helper = helpers_5[_c];
108738                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
108739                         bundledHelpers.set(helper.name, true);
108740                         (result || (result = [])).push(helper.name);
108741                     }
108742                 }
108743             }
108744             return result;
108745         }
108746         function emitHelpers(node) {
108747             var helpersEmitted = false;
108748             var bundle = node.kind === 304 /* Bundle */ ? node : undefined;
108749             if (bundle && moduleKind === ts.ModuleKind.None) {
108750                 return;
108751             }
108752             var numPrepends = bundle ? bundle.prepends.length : 0;
108753             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
108754             for (var i = 0; i < numNodes; i++) {
108755                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
108756                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
108757                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
108758                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
108759                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
108760                 if (helpers) {
108761                     for (var _a = 0, helpers_6 = helpers; _a < helpers_6.length; _a++) {
108762                         var helper = helpers_6[_a];
108763                         if (!helper.scoped) {
108764                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
108765                             // option is set, or if it can be imported and the importHelpers compiler
108766                             // option is set.
108767                             if (shouldSkip)
108768                                 continue;
108769                             // Skip the helper if it can be bundled but hasn't already been emitted and we
108770                             // are emitting a bundled module.
108771                             if (shouldBundle) {
108772                                 if (bundledHelpers.get(helper.name)) {
108773                                     continue;
108774                                 }
108775                                 bundledHelpers.set(helper.name, true);
108776                             }
108777                         }
108778                         else if (bundle) {
108779                             // Skip the helper if it is scoped and we are emitting bundled helpers
108780                             continue;
108781                         }
108782                         var pos = getTextPosWithWriteLine();
108783                         if (typeof helper.text === "string") {
108784                             writeLines(helper.text);
108785                         }
108786                         else {
108787                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
108788                         }
108789                         if (bundleFileInfo)
108790                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
108791                         helpersEmitted = true;
108792                     }
108793                 }
108794             }
108795             return helpersEmitted;
108796         }
108797         function getSortedEmitHelpers(node) {
108798             var helpers = ts.getEmitHelpers(node);
108799             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
108800         }
108801         //
108802         // Literals/Pseudo-literals
108803         //
108804         // SyntaxKind.NumericLiteral
108805         // SyntaxKind.BigIntLiteral
108806         function emitNumericOrBigIntLiteral(node) {
108807             emitLiteral(node, /*jsxAttributeEscape*/ false);
108808         }
108809         // SyntaxKind.StringLiteral
108810         // SyntaxKind.RegularExpressionLiteral
108811         // SyntaxKind.NoSubstitutionTemplateLiteral
108812         // SyntaxKind.TemplateHead
108813         // SyntaxKind.TemplateMiddle
108814         // SyntaxKind.TemplateTail
108815         function emitLiteral(node, jsxAttributeEscape) {
108816             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
108817             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
108818                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
108819                 writeLiteral(text);
108820             }
108821             else {
108822                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
108823                 writeStringLiteral(text);
108824             }
108825         }
108826         // SyntaxKind.UnparsedSource
108827         // SyntaxKind.UnparsedPrepend
108828         function emitUnparsedSourceOrPrepend(unparsed) {
108829             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
108830                 var text = _b[_a];
108831                 writeLine();
108832                 emit(text);
108833             }
108834         }
108835         // SyntaxKind.UnparsedPrologue
108836         // SyntaxKind.UnparsedText
108837         // SyntaxKind.UnparsedInternal
108838         // SyntaxKind.UnparsedSyntheticReference
108839         function writeUnparsedNode(unparsed) {
108840             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
108841         }
108842         // SyntaxKind.UnparsedText
108843         // SyntaxKind.UnparsedInternal
108844         function emitUnparsedTextLike(unparsed) {
108845             var pos = getTextPosWithWriteLine();
108846             writeUnparsedNode(unparsed);
108847             if (bundleFileInfo) {
108848                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 300 /* UnparsedText */ ?
108849                     "text" /* Text */ :
108850                     "internal" /* Internal */);
108851             }
108852         }
108853         // SyntaxKind.UnparsedSyntheticReference
108854         function emitUnparsedSyntheticReference(unparsed) {
108855             var pos = getTextPosWithWriteLine();
108856             writeUnparsedNode(unparsed);
108857             if (bundleFileInfo) {
108858                 var section = ts.clone(unparsed.section);
108859                 section.pos = pos;
108860                 section.end = writer.getTextPos();
108861                 bundleFileInfo.sections.push(section);
108862             }
108863         }
108864         //
108865         // Snippet Elements
108866         //
108867         function emitSnippetNode(hint, node, snippet) {
108868             switch (snippet.kind) {
108869                 case 1 /* Placeholder */:
108870                     emitPlaceholder(hint, node, snippet);
108871                     break;
108872                 case 0 /* TabStop */:
108873                     emitTabStop(snippet);
108874                     break;
108875             }
108876         }
108877         function emitPlaceholder(hint, node, snippet) {
108878             nonEscapingWrite("${".concat(snippet.order, ":")); // `${2:`
108879             pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...`
108880             nonEscapingWrite("}"); // `}`
108881             // `${2:...}`
108882         }
108883         function emitTabStop(snippet) {
108884             nonEscapingWrite("$".concat(snippet.order));
108885         }
108886         //
108887         // Identifiers
108888         //
108889         function emitIdentifier(node) {
108890             var writeText = node.symbol ? writeSymbol : write;
108891             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
108892             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
108893         }
108894         //
108895         // Names
108896         //
108897         function emitPrivateIdentifier(node) {
108898             var writeText = node.symbol ? writeSymbol : write;
108899             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
108900         }
108901         function emitQualifiedName(node) {
108902             emitEntityName(node.left);
108903             writePunctuation(".");
108904             emit(node.right);
108905         }
108906         function emitEntityName(node) {
108907             if (node.kind === 79 /* Identifier */) {
108908                 emitExpression(node);
108909             }
108910             else {
108911                 emit(node);
108912             }
108913         }
108914         function emitComputedPropertyName(node) {
108915             writePunctuation("[");
108916             emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName);
108917             writePunctuation("]");
108918         }
108919         //
108920         // Signature elements
108921         //
108922         function emitTypeParameter(node) {
108923             emit(node.name);
108924             if (node.constraint) {
108925                 writeSpace();
108926                 writeKeyword("extends");
108927                 writeSpace();
108928                 emit(node.constraint);
108929             }
108930             if (node.default) {
108931                 writeSpace();
108932                 writeOperator("=");
108933                 writeSpace();
108934                 emit(node.default);
108935             }
108936         }
108937         function emitParameter(node) {
108938             emitDecorators(node, node.decorators);
108939             emitModifiers(node, node.modifiers);
108940             emit(node.dotDotDotToken);
108941             emitNodeWithWriter(node.name, writeParameter);
108942             emit(node.questionToken);
108943             if (node.parent && node.parent.kind === 315 /* JSDocFunctionType */ && !node.name) {
108944                 emit(node.type);
108945             }
108946             else {
108947                 emitTypeAnnotation(node.type);
108948             }
108949             // 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.
108950             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, parenthesizer.parenthesizeExpressionForDisallowedComma);
108951         }
108952         function emitDecorator(decorator) {
108953             writePunctuation("@");
108954             emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess);
108955         }
108956         //
108957         // Type members
108958         //
108959         function emitPropertySignature(node) {
108960             emitDecorators(node, node.decorators);
108961             emitModifiers(node, node.modifiers);
108962             emitNodeWithWriter(node.name, writeProperty);
108963             emit(node.questionToken);
108964             emitTypeAnnotation(node.type);
108965             writeTrailingSemicolon();
108966         }
108967         function emitPropertyDeclaration(node) {
108968             emitDecorators(node, node.decorators);
108969             emitModifiers(node, node.modifiers);
108970             emit(node.name);
108971             emit(node.questionToken);
108972             emit(node.exclamationToken);
108973             emitTypeAnnotation(node.type);
108974             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
108975             writeTrailingSemicolon();
108976         }
108977         function emitMethodSignature(node) {
108978             pushNameGenerationScope(node);
108979             emitDecorators(node, node.decorators);
108980             emitModifiers(node, node.modifiers);
108981             emit(node.name);
108982             emit(node.questionToken);
108983             emitTypeParameters(node, node.typeParameters);
108984             emitParameters(node, node.parameters);
108985             emitTypeAnnotation(node.type);
108986             writeTrailingSemicolon();
108987             popNameGenerationScope(node);
108988         }
108989         function emitMethodDeclaration(node) {
108990             emitDecorators(node, node.decorators);
108991             emitModifiers(node, node.modifiers);
108992             emit(node.asteriskToken);
108993             emit(node.name);
108994             emit(node.questionToken);
108995             emitSignatureAndBody(node, emitSignatureHead);
108996         }
108997         function emitClassStaticBlockDeclaration(node) {
108998             emitDecorators(node, node.decorators);
108999             emitModifiers(node, node.modifiers);
109000             writeKeyword("static");
109001             emitBlockFunctionBody(node.body);
109002         }
109003         function emitConstructor(node) {
109004             emitModifiers(node, node.modifiers);
109005             writeKeyword("constructor");
109006             emitSignatureAndBody(node, emitSignatureHead);
109007         }
109008         function emitAccessorDeclaration(node) {
109009             emitDecorators(node, node.decorators);
109010             emitModifiers(node, node.modifiers);
109011             writeKeyword(node.kind === 171 /* GetAccessor */ ? "get" : "set");
109012             writeSpace();
109013             emit(node.name);
109014             emitSignatureAndBody(node, emitSignatureHead);
109015         }
109016         function emitCallSignature(node) {
109017             pushNameGenerationScope(node);
109018             emitDecorators(node, node.decorators);
109019             emitModifiers(node, node.modifiers);
109020             emitTypeParameters(node, node.typeParameters);
109021             emitParameters(node, node.parameters);
109022             emitTypeAnnotation(node.type);
109023             writeTrailingSemicolon();
109024             popNameGenerationScope(node);
109025         }
109026         function emitConstructSignature(node) {
109027             pushNameGenerationScope(node);
109028             emitDecorators(node, node.decorators);
109029             emitModifiers(node, node.modifiers);
109030             writeKeyword("new");
109031             writeSpace();
109032             emitTypeParameters(node, node.typeParameters);
109033             emitParameters(node, node.parameters);
109034             emitTypeAnnotation(node.type);
109035             writeTrailingSemicolon();
109036             popNameGenerationScope(node);
109037         }
109038         function emitIndexSignature(node) {
109039             emitDecorators(node, node.decorators);
109040             emitModifiers(node, node.modifiers);
109041             emitParametersForIndexSignature(node, node.parameters);
109042             emitTypeAnnotation(node.type);
109043             writeTrailingSemicolon();
109044         }
109045         function emitTemplateTypeSpan(node) {
109046             emit(node.type);
109047             emit(node.literal);
109048         }
109049         function emitSemicolonClassElement() {
109050             writeTrailingSemicolon();
109051         }
109052         //
109053         // Types
109054         //
109055         function emitTypePredicate(node) {
109056             if (node.assertsModifier) {
109057                 emit(node.assertsModifier);
109058                 writeSpace();
109059             }
109060             emit(node.parameterName);
109061             if (node.type) {
109062                 writeSpace();
109063                 writeKeyword("is");
109064                 writeSpace();
109065                 emit(node.type);
109066             }
109067         }
109068         function emitTypeReference(node) {
109069             emit(node.typeName);
109070             emitTypeArguments(node, node.typeArguments);
109071         }
109072         function emitFunctionType(node) {
109073             pushNameGenerationScope(node);
109074             emitTypeParameters(node, node.typeParameters);
109075             emitParametersForArrow(node, node.parameters);
109076             writeSpace();
109077             writePunctuation("=>");
109078             writeSpace();
109079             emit(node.type);
109080             popNameGenerationScope(node);
109081         }
109082         function emitJSDocFunctionType(node) {
109083             writeKeyword("function");
109084             emitParameters(node, node.parameters);
109085             writePunctuation(":");
109086             emit(node.type);
109087         }
109088         function emitJSDocNullableType(node) {
109089             writePunctuation("?");
109090             emit(node.type);
109091         }
109092         function emitJSDocNonNullableType(node) {
109093             writePunctuation("!");
109094             emit(node.type);
109095         }
109096         function emitJSDocOptionalType(node) {
109097             emit(node.type);
109098             writePunctuation("=");
109099         }
109100         function emitConstructorType(node) {
109101             pushNameGenerationScope(node);
109102             emitModifiers(node, node.modifiers);
109103             writeKeyword("new");
109104             writeSpace();
109105             emitTypeParameters(node, node.typeParameters);
109106             emitParameters(node, node.parameters);
109107             writeSpace();
109108             writePunctuation("=>");
109109             writeSpace();
109110             emit(node.type);
109111             popNameGenerationScope(node);
109112         }
109113         function emitTypeQuery(node) {
109114             writeKeyword("typeof");
109115             writeSpace();
109116             emit(node.exprName);
109117         }
109118         function emitTypeLiteral(node) {
109119             writePunctuation("{");
109120             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
109121             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
109122             writePunctuation("}");
109123         }
109124         function emitArrayType(node) {
109125             emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType);
109126             writePunctuation("[");
109127             writePunctuation("]");
109128         }
109129         function emitRestOrJSDocVariadicType(node) {
109130             writePunctuation("...");
109131             emit(node.type);
109132         }
109133         function emitTupleType(node) {
109134             emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node);
109135             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
109136             emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */);
109137             emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
109138         }
109139         function emitNamedTupleMember(node) {
109140             emit(node.dotDotDotToken);
109141             emit(node.name);
109142             emit(node.questionToken);
109143             emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node);
109144             writeSpace();
109145             emit(node.type);
109146         }
109147         function emitOptionalType(node) {
109148             emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType);
109149             writePunctuation("?");
109150         }
109151         function emitUnionType(node) {
109152             emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType);
109153         }
109154         function emitIntersectionType(node) {
109155             emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType);
109156         }
109157         function emitConditionalType(node) {
109158             emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType);
109159             writeSpace();
109160             writeKeyword("extends");
109161             writeSpace();
109162             emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType);
109163             writeSpace();
109164             writePunctuation("?");
109165             writeSpace();
109166             emit(node.trueType);
109167             writeSpace();
109168             writePunctuation(":");
109169             writeSpace();
109170             emit(node.falseType);
109171         }
109172         function emitInferType(node) {
109173             writeKeyword("infer");
109174             writeSpace();
109175             emit(node.typeParameter);
109176         }
109177         function emitParenthesizedType(node) {
109178             writePunctuation("(");
109179             emit(node.type);
109180             writePunctuation(")");
109181         }
109182         function emitThisType() {
109183             writeKeyword("this");
109184         }
109185         function emitTypeOperator(node) {
109186             writeTokenText(node.operator, writeKeyword);
109187             writeSpace();
109188             emit(node.type, parenthesizer.parenthesizeMemberOfElementType);
109189         }
109190         function emitIndexedAccessType(node) {
109191             emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType);
109192             writePunctuation("[");
109193             emit(node.indexType);
109194             writePunctuation("]");
109195         }
109196         function emitMappedType(node) {
109197             var emitFlags = ts.getEmitFlags(node);
109198             writePunctuation("{");
109199             if (emitFlags & 1 /* SingleLine */) {
109200                 writeSpace();
109201             }
109202             else {
109203                 writeLine();
109204                 increaseIndent();
109205             }
109206             if (node.readonlyToken) {
109207                 emit(node.readonlyToken);
109208                 if (node.readonlyToken.kind !== 144 /* ReadonlyKeyword */) {
109209                     writeKeyword("readonly");
109210                 }
109211                 writeSpace();
109212             }
109213             writePunctuation("[");
109214             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
109215             if (node.nameType) {
109216                 writeSpace();
109217                 writeKeyword("as");
109218                 writeSpace();
109219                 emit(node.nameType);
109220             }
109221             writePunctuation("]");
109222             if (node.questionToken) {
109223                 emit(node.questionToken);
109224                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
109225                     writePunctuation("?");
109226                 }
109227             }
109228             writePunctuation(":");
109229             writeSpace();
109230             emit(node.type);
109231             writeTrailingSemicolon();
109232             if (emitFlags & 1 /* SingleLine */) {
109233                 writeSpace();
109234             }
109235             else {
109236                 writeLine();
109237                 decreaseIndent();
109238             }
109239             writePunctuation("}");
109240         }
109241         function emitLiteralType(node) {
109242             emitExpression(node.literal);
109243         }
109244         function emitTemplateType(node) {
109245             emit(node.head);
109246             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
109247         }
109248         function emitImportTypeNode(node) {
109249             if (node.isTypeOf) {
109250                 writeKeyword("typeof");
109251                 writeSpace();
109252             }
109253             writeKeyword("import");
109254             writePunctuation("(");
109255             emit(node.argument);
109256             writePunctuation(")");
109257             if (node.qualifier) {
109258                 writePunctuation(".");
109259                 emit(node.qualifier);
109260             }
109261             emitTypeArguments(node, node.typeArguments);
109262         }
109263         //
109264         // Binding patterns
109265         //
109266         function emitObjectBindingPattern(node) {
109267             writePunctuation("{");
109268             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
109269             writePunctuation("}");
109270         }
109271         function emitArrayBindingPattern(node) {
109272             writePunctuation("[");
109273             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
109274             writePunctuation("]");
109275         }
109276         function emitBindingElement(node) {
109277             emit(node.dotDotDotToken);
109278             if (node.propertyName) {
109279                 emit(node.propertyName);
109280                 writePunctuation(":");
109281                 writeSpace();
109282             }
109283             emit(node.name);
109284             emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
109285         }
109286         //
109287         // Expressions
109288         //
109289         function emitArrayLiteralExpression(node) {
109290             var elements = node.elements;
109291             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
109292             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma);
109293         }
109294         function emitObjectLiteralExpression(node) {
109295             ts.forEach(node.properties, generateMemberNames);
109296             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
109297             if (indentedFlag) {
109298                 increaseIndent();
109299             }
109300             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
109301             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
109302             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
109303             if (indentedFlag) {
109304                 decreaseIndent();
109305             }
109306         }
109307         function emitPropertyAccessExpression(node) {
109308             emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
109309             var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos);
109310             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
109311             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
109312             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
109313             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
109314                 mayNeedDotDotForPropertyAccess(node.expression) &&
109315                 !writer.hasTrailingComment() &&
109316                 !writer.hasTrailingWhitespace();
109317             if (shouldEmitDotDot) {
109318                 writePunctuation(".");
109319             }
109320             if (node.questionDotToken) {
109321                 emit(token);
109322             }
109323             else {
109324                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
109325             }
109326             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
109327             emit(node.name);
109328             decreaseIndentIf(linesBeforeDot, linesAfterDot);
109329         }
109330         // 1..toString is a valid property access, emit a dot after the literal
109331         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
109332         function mayNeedDotDotForPropertyAccess(expression) {
109333             expression = ts.skipPartiallyEmittedExpressions(expression);
109334             if (ts.isNumericLiteral(expression)) {
109335                 // check if numeric literal is a decimal literal that was originally written with a dot
109336                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
109337                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
109338                 // if the expression doesn't have any comments that will be emitted.
109339                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
109340             }
109341             else if (ts.isAccessExpression(expression)) {
109342                 // check if constant enum value is integer
109343                 var constantValue = ts.getConstantValue(expression);
109344                 // isFinite handles cases when constantValue is undefined
109345                 return typeof constantValue === "number" && isFinite(constantValue)
109346                     && Math.floor(constantValue) === constantValue;
109347             }
109348         }
109349         function emitElementAccessExpression(node) {
109350             emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
109351             emit(node.questionDotToken);
109352             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
109353             emitExpression(node.argumentExpression);
109354             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
109355         }
109356         function emitCallExpression(node) {
109357             var indirectCall = ts.getEmitFlags(node) & 536870912 /* IndirectCall */;
109358             if (indirectCall) {
109359                 writePunctuation("(");
109360                 writeLiteral("0");
109361                 writePunctuation(",");
109362                 writeSpace();
109363             }
109364             emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
109365             if (indirectCall) {
109366                 writePunctuation(")");
109367             }
109368             emit(node.questionDotToken);
109369             emitTypeArguments(node, node.typeArguments);
109370             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma);
109371         }
109372         function emitNewExpression(node) {
109373             emitTokenWithComment(103 /* NewKeyword */, node.pos, writeKeyword, node);
109374             writeSpace();
109375             emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew);
109376             emitTypeArguments(node, node.typeArguments);
109377             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma);
109378         }
109379         function emitTaggedTemplateExpression(node) {
109380             var indirectCall = ts.getEmitFlags(node) & 536870912 /* IndirectCall */;
109381             if (indirectCall) {
109382                 writePunctuation("(");
109383                 writeLiteral("0");
109384                 writePunctuation(",");
109385                 writeSpace();
109386             }
109387             emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess);
109388             if (indirectCall) {
109389                 writePunctuation(")");
109390             }
109391             emitTypeArguments(node, node.typeArguments);
109392             writeSpace();
109393             emitExpression(node.template);
109394         }
109395         function emitTypeAssertionExpression(node) {
109396             writePunctuation("<");
109397             emit(node.type);
109398             writePunctuation(">");
109399             emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
109400         }
109401         function emitParenthesizedExpression(node) {
109402             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
109403             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
109404             emitExpression(node.expression, /*parenthesizerRules*/ undefined);
109405             writeLineSeparatorsAfter(node.expression, node);
109406             decreaseIndentIf(indented);
109407             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
109408         }
109409         function emitFunctionExpression(node) {
109410             generateNameIfNeeded(node.name);
109411             emitFunctionDeclarationOrExpression(node);
109412         }
109413         function emitArrowFunction(node) {
109414             emitDecorators(node, node.decorators);
109415             emitModifiers(node, node.modifiers);
109416             emitSignatureAndBody(node, emitArrowFunctionHead);
109417         }
109418         function emitArrowFunctionHead(node) {
109419             emitTypeParameters(node, node.typeParameters);
109420             emitParametersForArrow(node, node.parameters);
109421             emitTypeAnnotation(node.type);
109422             writeSpace();
109423             emit(node.equalsGreaterThanToken);
109424         }
109425         function emitDeleteExpression(node) {
109426             emitTokenWithComment(89 /* DeleteKeyword */, node.pos, writeKeyword, node);
109427             writeSpace();
109428             emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
109429         }
109430         function emitTypeOfExpression(node) {
109431             emitTokenWithComment(112 /* TypeOfKeyword */, node.pos, writeKeyword, node);
109432             writeSpace();
109433             emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
109434         }
109435         function emitVoidExpression(node) {
109436             emitTokenWithComment(114 /* VoidKeyword */, node.pos, writeKeyword, node);
109437             writeSpace();
109438             emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
109439         }
109440         function emitAwaitExpression(node) {
109441             emitTokenWithComment(132 /* AwaitKeyword */, node.pos, writeKeyword, node);
109442             writeSpace();
109443             emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
109444         }
109445         function emitPrefixUnaryExpression(node) {
109446             writeTokenText(node.operator, writeOperator);
109447             if (shouldEmitWhitespaceBeforeOperand(node)) {
109448                 writeSpace();
109449             }
109450             emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary);
109451         }
109452         function shouldEmitWhitespaceBeforeOperand(node) {
109453             // In some cases, we need to emit a space between the operator and the operand. One obvious case
109454             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
109455             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
109456             // are just for clarity of exposition, and not part of the source code):
109457             //
109458             //  (+(+1))
109459             //  (+(++1))
109460             //
109461             // We need to emit a space in both cases. In the first case, the absence of a space will make
109462             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
109463             // expression a prefix increment whose operand is a plus expression - (++(+x))
109464             // The same is true of minus of course.
109465             var operand = node.operand;
109466             return operand.kind === 218 /* PrefixUnaryExpression */
109467                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
109468                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
109469         }
109470         function emitPostfixUnaryExpression(node) {
109471             emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary);
109472             writeTokenText(node.operator, writeOperator);
109473         }
109474         function createEmitBinaryExpression() {
109475             return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined);
109476             function onEnter(node, state) {
109477                 if (state) {
109478                     state.stackIndex++;
109479                     state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines;
109480                     state.containerPosStack[state.stackIndex] = containerPos;
109481                     state.containerEndStack[state.stackIndex] = containerEnd;
109482                     state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd;
109483                     var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node);
109484                     var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node);
109485                     onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node);
109486                     if (emitComments_1)
109487                         emitCommentsBeforeNode(node);
109488                     if (emitSourceMaps)
109489                         emitSourceMapsBeforeNode(node);
109490                     beforeEmitNode(node);
109491                 }
109492                 else {
109493                     state = {
109494                         stackIndex: 0,
109495                         preserveSourceNewlinesStack: [undefined],
109496                         containerPosStack: [-1],
109497                         containerEndStack: [-1],
109498                         declarationListContainerEndStack: [-1],
109499                         shouldEmitCommentsStack: [false],
109500                         shouldEmitSourceMapsStack: [false],
109501                     };
109502                 }
109503                 return state;
109504             }
109505             function onLeft(next, _workArea, parent) {
109506                 return maybeEmitExpression(next, parent, "left");
109507             }
109508             function onOperator(operatorToken, _state, node) {
109509                 var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */;
109510                 var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken);
109511                 var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right);
109512                 writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
109513                 emitLeadingCommentsOfPosition(operatorToken.pos);
109514                 writeTokenNode(operatorToken, operatorToken.kind === 101 /* InKeyword */ ? writeKeyword : writeOperator);
109515                 emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
109516                 writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
109517             }
109518             function onRight(next, _workArea, parent) {
109519                 return maybeEmitExpression(next, parent, "right");
109520             }
109521             function onExit(node, state) {
109522                 var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
109523                 var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
109524                 decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
109525                 if (state.stackIndex > 0) {
109526                     var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex];
109527                     var savedContainerPos = state.containerPosStack[state.stackIndex];
109528                     var savedContainerEnd = state.containerEndStack[state.stackIndex];
109529                     var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex];
109530                     var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex];
109531                     var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex];
109532                     afterEmitNode(savedPreserveSourceNewlines);
109533                     if (shouldEmitSourceMaps_1)
109534                         emitSourceMapsAfterNode(node);
109535                     if (shouldEmitComments_1)
109536                         emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
109537                     onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node);
109538                     state.stackIndex--;
109539                 }
109540             }
109541             function maybeEmitExpression(next, parent, side) {
109542                 var parenthesizerRule = side === "left" ?
109543                     parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) :
109544                     parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind);
109545                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
109546                 if (pipelinePhase === pipelineEmitWithSubstitution) {
109547                     ts.Debug.assertIsDefined(lastSubstitution);
109548                     next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression));
109549                     pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next);
109550                     lastSubstitution = undefined;
109551                 }
109552                 if (pipelinePhase === pipelineEmitWithComments ||
109553                     pipelinePhase === pipelineEmitWithSourceMaps ||
109554                     pipelinePhase === pipelineEmitWithHint) {
109555                     if (ts.isBinaryExpression(next)) {
109556                         return next;
109557                     }
109558                 }
109559                 currentParenthesizerRule = parenthesizerRule;
109560                 pipelinePhase(1 /* Expression */, next);
109561             }
109562         }
109563         function emitConditionalExpression(node) {
109564             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
109565             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
109566             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
109567             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
109568             emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression);
109569             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
109570             emit(node.questionToken);
109571             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
109572             emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression);
109573             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
109574             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
109575             emit(node.colonToken);
109576             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
109577             emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression);
109578             decreaseIndentIf(linesBeforeColon, linesAfterColon);
109579         }
109580         function emitTemplateExpression(node) {
109581             emit(node.head);
109582             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
109583         }
109584         function emitYieldExpression(node) {
109585             emitTokenWithComment(125 /* YieldKeyword */, node.pos, writeKeyword, node);
109586             emit(node.asteriskToken);
109587             emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
109588         }
109589         function emitSpreadElement(node) {
109590             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
109591             emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
109592         }
109593         function emitClassExpression(node) {
109594             generateNameIfNeeded(node.name);
109595             emitClassDeclarationOrExpression(node);
109596         }
109597         function emitExpressionWithTypeArguments(node) {
109598             emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
109599             emitTypeArguments(node, node.typeArguments);
109600         }
109601         function emitAsExpression(node) {
109602             emitExpression(node.expression, /*parenthesizerRules*/ undefined);
109603             if (node.type) {
109604                 writeSpace();
109605                 writeKeyword("as");
109606                 writeSpace();
109607                 emit(node.type);
109608             }
109609         }
109610         function emitNonNullExpression(node) {
109611             emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
109612             writeOperator("!");
109613         }
109614         function emitMetaProperty(node) {
109615             writeToken(node.keywordToken, node.pos, writePunctuation);
109616             writePunctuation(".");
109617             emit(node.name);
109618         }
109619         //
109620         // Misc
109621         //
109622         function emitTemplateSpan(node) {
109623             emitExpression(node.expression);
109624             emit(node.literal);
109625         }
109626         //
109627         // Statements
109628         //
109629         function emitBlock(node) {
109630             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
109631         }
109632         function emitBlockStatements(node, forceSingleLine) {
109633             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
109634             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
109635             emitList(node, node.statements, format);
109636             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
109637         }
109638         function emitVariableStatement(node) {
109639             emitModifiers(node, node.modifiers);
109640             emit(node.declarationList);
109641             writeTrailingSemicolon();
109642         }
109643         function emitEmptyStatement(isEmbeddedStatement) {
109644             // While most trailing semicolons are possibly insignificant, an embedded "empty"
109645             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
109646             if (isEmbeddedStatement) {
109647                 writePunctuation(";");
109648             }
109649             else {
109650                 writeTrailingSemicolon();
109651             }
109652         }
109653         function emitExpressionStatement(node) {
109654             emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement);
109655             // Emit semicolon in non json files
109656             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
109657             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
109658                 writeTrailingSemicolon();
109659             }
109660         }
109661         function emitIfStatement(node) {
109662             var openParenPos = emitTokenWithComment(99 /* IfKeyword */, node.pos, writeKeyword, node);
109663             writeSpace();
109664             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109665             emitExpression(node.expression);
109666             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109667             emitEmbeddedStatement(node, node.thenStatement);
109668             if (node.elseStatement) {
109669                 writeLineOrSpace(node, node.thenStatement, node.elseStatement);
109670                 emitTokenWithComment(91 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
109671                 if (node.elseStatement.kind === 238 /* IfStatement */) {
109672                     writeSpace();
109673                     emit(node.elseStatement);
109674                 }
109675                 else {
109676                     emitEmbeddedStatement(node, node.elseStatement);
109677                 }
109678             }
109679         }
109680         function emitWhileClause(node, startPos) {
109681             var openParenPos = emitTokenWithComment(115 /* WhileKeyword */, startPos, writeKeyword, node);
109682             writeSpace();
109683             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109684             emitExpression(node.expression);
109685             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109686         }
109687         function emitDoStatement(node) {
109688             emitTokenWithComment(90 /* DoKeyword */, node.pos, writeKeyword, node);
109689             emitEmbeddedStatement(node, node.statement);
109690             if (ts.isBlock(node.statement) && !preserveSourceNewlines) {
109691                 writeSpace();
109692             }
109693             else {
109694                 writeLineOrSpace(node, node.statement, node.expression);
109695             }
109696             emitWhileClause(node, node.statement.end);
109697             writeTrailingSemicolon();
109698         }
109699         function emitWhileStatement(node) {
109700             emitWhileClause(node, node.pos);
109701             emitEmbeddedStatement(node, node.statement);
109702         }
109703         function emitForStatement(node) {
109704             var openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node);
109705             writeSpace();
109706             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
109707             emitForBinding(node.initializer);
109708             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
109709             emitExpressionWithLeadingSpace(node.condition);
109710             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
109711             emitExpressionWithLeadingSpace(node.incrementor);
109712             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
109713             emitEmbeddedStatement(node, node.statement);
109714         }
109715         function emitForInStatement(node) {
109716             var openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node);
109717             writeSpace();
109718             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109719             emitForBinding(node.initializer);
109720             writeSpace();
109721             emitTokenWithComment(101 /* InKeyword */, node.initializer.end, writeKeyword, node);
109722             writeSpace();
109723             emitExpression(node.expression);
109724             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109725             emitEmbeddedStatement(node, node.statement);
109726         }
109727         function emitForOfStatement(node) {
109728             var openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node);
109729             writeSpace();
109730             emitWithTrailingSpace(node.awaitModifier);
109731             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109732             emitForBinding(node.initializer);
109733             writeSpace();
109734             emitTokenWithComment(159 /* OfKeyword */, node.initializer.end, writeKeyword, node);
109735             writeSpace();
109736             emitExpression(node.expression);
109737             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109738             emitEmbeddedStatement(node, node.statement);
109739         }
109740         function emitForBinding(node) {
109741             if (node !== undefined) {
109742                 if (node.kind === 254 /* VariableDeclarationList */) {
109743                     emit(node);
109744                 }
109745                 else {
109746                     emitExpression(node);
109747                 }
109748             }
109749         }
109750         function emitContinueStatement(node) {
109751             emitTokenWithComment(86 /* ContinueKeyword */, node.pos, writeKeyword, node);
109752             emitWithLeadingSpace(node.label);
109753             writeTrailingSemicolon();
109754         }
109755         function emitBreakStatement(node) {
109756             emitTokenWithComment(81 /* BreakKeyword */, node.pos, writeKeyword, node);
109757             emitWithLeadingSpace(node.label);
109758             writeTrailingSemicolon();
109759         }
109760         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
109761             var node = ts.getParseTreeNode(contextNode);
109762             var isSimilarNode = node && node.kind === contextNode.kind;
109763             var startPos = pos;
109764             if (isSimilarNode && currentSourceFile) {
109765                 pos = ts.skipTrivia(currentSourceFile.text, pos);
109766             }
109767             if (isSimilarNode && contextNode.pos !== startPos) {
109768                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
109769                 if (needsIndent) {
109770                     increaseIndent();
109771                 }
109772                 emitLeadingCommentsOfPosition(startPos);
109773                 if (needsIndent) {
109774                     decreaseIndent();
109775                 }
109776             }
109777             pos = writeTokenText(token, writer, pos);
109778             if (isSimilarNode && contextNode.end !== pos) {
109779                 var isJsxExprContext = contextNode.kind === 287 /* JsxExpression */;
109780                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext);
109781             }
109782             return pos;
109783         }
109784         function emitReturnStatement(node) {
109785             emitTokenWithComment(105 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
109786             emitExpressionWithLeadingSpace(node.expression);
109787             writeTrailingSemicolon();
109788         }
109789         function emitWithStatement(node) {
109790             var openParenPos = emitTokenWithComment(116 /* WithKeyword */, node.pos, writeKeyword, node);
109791             writeSpace();
109792             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109793             emitExpression(node.expression);
109794             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109795             emitEmbeddedStatement(node, node.statement);
109796         }
109797         function emitSwitchStatement(node) {
109798             var openParenPos = emitTokenWithComment(107 /* SwitchKeyword */, node.pos, writeKeyword, node);
109799             writeSpace();
109800             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
109801             emitExpression(node.expression);
109802             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
109803             writeSpace();
109804             emit(node.caseBlock);
109805         }
109806         function emitLabeledStatement(node) {
109807             emit(node.label);
109808             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
109809             writeSpace();
109810             emit(node.statement);
109811         }
109812         function emitThrowStatement(node) {
109813             emitTokenWithComment(109 /* ThrowKeyword */, node.pos, writeKeyword, node);
109814             emitExpressionWithLeadingSpace(node.expression);
109815             writeTrailingSemicolon();
109816         }
109817         function emitTryStatement(node) {
109818             emitTokenWithComment(111 /* TryKeyword */, node.pos, writeKeyword, node);
109819             writeSpace();
109820             emit(node.tryBlock);
109821             if (node.catchClause) {
109822                 writeLineOrSpace(node, node.tryBlock, node.catchClause);
109823                 emit(node.catchClause);
109824             }
109825             if (node.finallyBlock) {
109826                 writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
109827                 emitTokenWithComment(96 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
109828                 writeSpace();
109829                 emit(node.finallyBlock);
109830             }
109831         }
109832         function emitDebuggerStatement(node) {
109833             writeToken(87 /* DebuggerKeyword */, node.pos, writeKeyword);
109834             writeTrailingSemicolon();
109835         }
109836         //
109837         // Declarations
109838         //
109839         function emitVariableDeclaration(node) {
109840             emit(node.name);
109841             emit(node.exclamationToken);
109842             emitTypeAnnotation(node.type);
109843             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
109844         }
109845         function emitVariableDeclarationList(node) {
109846             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
109847             writeSpace();
109848             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
109849         }
109850         function emitFunctionDeclaration(node) {
109851             emitFunctionDeclarationOrExpression(node);
109852         }
109853         function emitFunctionDeclarationOrExpression(node) {
109854             emitDecorators(node, node.decorators);
109855             emitModifiers(node, node.modifiers);
109856             writeKeyword("function");
109857             emit(node.asteriskToken);
109858             writeSpace();
109859             emitIdentifierName(node.name);
109860             emitSignatureAndBody(node, emitSignatureHead);
109861         }
109862         function emitSignatureAndBody(node, emitSignatureHead) {
109863             var body = node.body;
109864             if (body) {
109865                 if (ts.isBlock(body)) {
109866                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
109867                     if (indentedFlag) {
109868                         increaseIndent();
109869                     }
109870                     pushNameGenerationScope(node);
109871                     ts.forEach(node.parameters, generateNames);
109872                     generateNames(node.body);
109873                     emitSignatureHead(node);
109874                     emitBlockFunctionBody(body);
109875                     popNameGenerationScope(node);
109876                     if (indentedFlag) {
109877                         decreaseIndent();
109878                     }
109879                 }
109880                 else {
109881                     emitSignatureHead(node);
109882                     writeSpace();
109883                     emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction);
109884                 }
109885             }
109886             else {
109887                 emitSignatureHead(node);
109888                 writeTrailingSemicolon();
109889             }
109890         }
109891         function emitSignatureHead(node) {
109892             emitTypeParameters(node, node.typeParameters);
109893             emitParameters(node, node.parameters);
109894             emitTypeAnnotation(node.type);
109895         }
109896         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
109897             // We must emit a function body as a single-line body in the following case:
109898             // * The body has NodeEmitFlags.SingleLine specified.
109899             // We must emit a function body as a multi-line body in the following cases:
109900             // * The body is explicitly marked as multi-line.
109901             // * A non-synthesized body's start and end position are on different lines.
109902             // * Any statement in the body starts on a new line.
109903             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
109904                 return true;
109905             }
109906             if (body.multiLine) {
109907                 return false;
109908             }
109909             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
109910                 return false;
109911             }
109912             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
109913                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
109914                 return false;
109915             }
109916             var previousStatement;
109917             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
109918                 var statement = _b[_a];
109919                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
109920                     return false;
109921                 }
109922                 previousStatement = statement;
109923             }
109924             return true;
109925         }
109926         function emitBlockFunctionBody(body) {
109927             onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body);
109928             writeSpace();
109929             writePunctuation("{");
109930             increaseIndent();
109931             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
109932                 ? emitBlockFunctionBodyOnSingleLine
109933                 : emitBlockFunctionBodyWorker;
109934             if (emitBodyWithDetachedComments) {
109935                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
109936             }
109937             else {
109938                 emitBlockFunctionBody(body);
109939             }
109940             decreaseIndent();
109941             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
109942             onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body);
109943         }
109944         function emitBlockFunctionBodyOnSingleLine(body) {
109945             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
109946         }
109947         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
109948             // Emit all the prologue directives (like "use strict").
109949             var statementOffset = emitPrologueDirectives(body.statements);
109950             var pos = writer.getTextPos();
109951             emitHelpers(body);
109952             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
109953                 decreaseIndent();
109954                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
109955                 increaseIndent();
109956             }
109957             else {
109958                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset);
109959             }
109960         }
109961         function emitClassDeclaration(node) {
109962             emitClassDeclarationOrExpression(node);
109963         }
109964         function emitClassDeclarationOrExpression(node) {
109965             ts.forEach(node.members, generateMemberNames);
109966             emitDecorators(node, node.decorators);
109967             emitModifiers(node, node.modifiers);
109968             writeKeyword("class");
109969             if (node.name) {
109970                 writeSpace();
109971                 emitIdentifierName(node.name);
109972             }
109973             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
109974             if (indentedFlag) {
109975                 increaseIndent();
109976             }
109977             emitTypeParameters(node, node.typeParameters);
109978             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
109979             writeSpace();
109980             writePunctuation("{");
109981             emitList(node, node.members, 129 /* ClassMembers */);
109982             writePunctuation("}");
109983             if (indentedFlag) {
109984                 decreaseIndent();
109985             }
109986         }
109987         function emitInterfaceDeclaration(node) {
109988             emitDecorators(node, node.decorators);
109989             emitModifiers(node, node.modifiers);
109990             writeKeyword("interface");
109991             writeSpace();
109992             emit(node.name);
109993             emitTypeParameters(node, node.typeParameters);
109994             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
109995             writeSpace();
109996             writePunctuation("{");
109997             emitList(node, node.members, 129 /* InterfaceMembers */);
109998             writePunctuation("}");
109999         }
110000         function emitTypeAliasDeclaration(node) {
110001             emitDecorators(node, node.decorators);
110002             emitModifiers(node, node.modifiers);
110003             writeKeyword("type");
110004             writeSpace();
110005             emit(node.name);
110006             emitTypeParameters(node, node.typeParameters);
110007             writeSpace();
110008             writePunctuation("=");
110009             writeSpace();
110010             emit(node.type);
110011             writeTrailingSemicolon();
110012         }
110013         function emitEnumDeclaration(node) {
110014             emitModifiers(node, node.modifiers);
110015             writeKeyword("enum");
110016             writeSpace();
110017             emit(node.name);
110018             writeSpace();
110019             writePunctuation("{");
110020             emitList(node, node.members, 145 /* EnumMembers */);
110021             writePunctuation("}");
110022         }
110023         function emitModuleDeclaration(node) {
110024             emitModifiers(node, node.modifiers);
110025             if (~node.flags & 1024 /* GlobalAugmentation */) {
110026                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
110027                 writeSpace();
110028             }
110029             emit(node.name);
110030             var body = node.body;
110031             if (!body)
110032                 return writeTrailingSemicolon();
110033             while (body && ts.isModuleDeclaration(body)) {
110034                 writePunctuation(".");
110035                 emit(body.name);
110036                 body = body.body;
110037             }
110038             writeSpace();
110039             emit(body);
110040         }
110041         function emitModuleBlock(node) {
110042             pushNameGenerationScope(node);
110043             ts.forEach(node.statements, generateNames);
110044             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
110045             popNameGenerationScope(node);
110046         }
110047         function emitCaseBlock(node) {
110048             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
110049             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
110050             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
110051         }
110052         function emitImportEqualsDeclaration(node) {
110053             emitModifiers(node, node.modifiers);
110054             emitTokenWithComment(100 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
110055             writeSpace();
110056             if (node.isTypeOnly) {
110057                 emitTokenWithComment(151 /* TypeKeyword */, node.pos, writeKeyword, node);
110058                 writeSpace();
110059             }
110060             emit(node.name);
110061             writeSpace();
110062             emitTokenWithComment(63 /* EqualsToken */, node.name.end, writePunctuation, node);
110063             writeSpace();
110064             emitModuleReference(node.moduleReference);
110065             writeTrailingSemicolon();
110066         }
110067         function emitModuleReference(node) {
110068             if (node.kind === 79 /* Identifier */) {
110069                 emitExpression(node);
110070             }
110071             else {
110072                 emit(node);
110073             }
110074         }
110075         function emitImportDeclaration(node) {
110076             emitModifiers(node, node.modifiers);
110077             emitTokenWithComment(100 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
110078             writeSpace();
110079             if (node.importClause) {
110080                 emit(node.importClause);
110081                 writeSpace();
110082                 emitTokenWithComment(155 /* FromKeyword */, node.importClause.end, writeKeyword, node);
110083                 writeSpace();
110084             }
110085             emitExpression(node.moduleSpecifier);
110086             if (node.assertClause) {
110087                 emitWithLeadingSpace(node.assertClause);
110088             }
110089             writeTrailingSemicolon();
110090         }
110091         function emitImportClause(node) {
110092             if (node.isTypeOnly) {
110093                 emitTokenWithComment(151 /* TypeKeyword */, node.pos, writeKeyword, node);
110094                 writeSpace();
110095             }
110096             emit(node.name);
110097             if (node.name && node.namedBindings) {
110098                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
110099                 writeSpace();
110100             }
110101             emit(node.namedBindings);
110102         }
110103         function emitNamespaceImport(node) {
110104             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
110105             writeSpace();
110106             emitTokenWithComment(127 /* AsKeyword */, asPos, writeKeyword, node);
110107             writeSpace();
110108             emit(node.name);
110109         }
110110         function emitNamedImports(node) {
110111             emitNamedImportsOrExports(node);
110112         }
110113         function emitImportSpecifier(node) {
110114             emitImportOrExportSpecifier(node);
110115         }
110116         function emitExportAssignment(node) {
110117             var nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node);
110118             writeSpace();
110119             if (node.isExportEquals) {
110120                 emitTokenWithComment(63 /* EqualsToken */, nextPos, writeOperator, node);
110121             }
110122             else {
110123                 emitTokenWithComment(88 /* DefaultKeyword */, nextPos, writeKeyword, node);
110124             }
110125             writeSpace();
110126             emitExpression(node.expression, node.isExportEquals ?
110127                 parenthesizer.getParenthesizeRightSideOfBinaryForOperator(63 /* EqualsToken */) :
110128                 parenthesizer.parenthesizeExpressionOfExportDefault);
110129             writeTrailingSemicolon();
110130         }
110131         function emitExportDeclaration(node) {
110132             var nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node);
110133             writeSpace();
110134             if (node.isTypeOnly) {
110135                 nextPos = emitTokenWithComment(151 /* TypeKeyword */, nextPos, writeKeyword, node);
110136                 writeSpace();
110137             }
110138             if (node.exportClause) {
110139                 emit(node.exportClause);
110140             }
110141             else {
110142                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
110143             }
110144             if (node.moduleSpecifier) {
110145                 writeSpace();
110146                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
110147                 emitTokenWithComment(155 /* FromKeyword */, fromPos, writeKeyword, node);
110148                 writeSpace();
110149                 emitExpression(node.moduleSpecifier);
110150             }
110151             if (node.assertClause) {
110152                 emitWithLeadingSpace(node.assertClause);
110153             }
110154             writeTrailingSemicolon();
110155         }
110156         function emitAssertClause(node) {
110157             emitTokenWithComment(129 /* AssertKeyword */, node.pos, writeKeyword, node);
110158             writeSpace();
110159             var elements = node.elements;
110160             emitList(node, elements, 526226 /* ImportClauseEntries */);
110161         }
110162         function emitAssertEntry(node) {
110163             emit(node.name);
110164             writePunctuation(":");
110165             writeSpace();
110166             var value = node.value;
110167             /** @see {emitPropertyAssignment} */
110168             if ((ts.getEmitFlags(value) & 512 /* NoLeadingComments */) === 0) {
110169                 var commentRange = ts.getCommentRange(value);
110170                 emitTrailingCommentsOfPosition(commentRange.pos);
110171             }
110172             emit(value);
110173         }
110174         function emitNamespaceExportDeclaration(node) {
110175             var nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node);
110176             writeSpace();
110177             nextPos = emitTokenWithComment(127 /* AsKeyword */, nextPos, writeKeyword, node);
110178             writeSpace();
110179             nextPos = emitTokenWithComment(142 /* NamespaceKeyword */, nextPos, writeKeyword, node);
110180             writeSpace();
110181             emit(node.name);
110182             writeTrailingSemicolon();
110183         }
110184         function emitNamespaceExport(node) {
110185             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
110186             writeSpace();
110187             emitTokenWithComment(127 /* AsKeyword */, asPos, writeKeyword, node);
110188             writeSpace();
110189             emit(node.name);
110190         }
110191         function emitNamedExports(node) {
110192             emitNamedImportsOrExports(node);
110193         }
110194         function emitExportSpecifier(node) {
110195             emitImportOrExportSpecifier(node);
110196         }
110197         function emitNamedImportsOrExports(node) {
110198             writePunctuation("{");
110199             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
110200             writePunctuation("}");
110201         }
110202         function emitImportOrExportSpecifier(node) {
110203             if (node.isTypeOnly) {
110204                 writeKeyword("type");
110205                 writeSpace();
110206             }
110207             if (node.propertyName) {
110208                 emit(node.propertyName);
110209                 writeSpace();
110210                 emitTokenWithComment(127 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
110211                 writeSpace();
110212             }
110213             emit(node.name);
110214         }
110215         //
110216         // Module references
110217         //
110218         function emitExternalModuleReference(node) {
110219             writeKeyword("require");
110220             writePunctuation("(");
110221             emitExpression(node.expression);
110222             writePunctuation(")");
110223         }
110224         //
110225         // JSX
110226         //
110227         function emitJsxElement(node) {
110228             emit(node.openingElement);
110229             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
110230             emit(node.closingElement);
110231         }
110232         function emitJsxSelfClosingElement(node) {
110233             writePunctuation("<");
110234             emitJsxTagName(node.tagName);
110235             emitTypeArguments(node, node.typeArguments);
110236             writeSpace();
110237             emit(node.attributes);
110238             writePunctuation("/>");
110239         }
110240         function emitJsxFragment(node) {
110241             emit(node.openingFragment);
110242             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
110243             emit(node.closingFragment);
110244         }
110245         function emitJsxOpeningElementOrFragment(node) {
110246             writePunctuation("<");
110247             if (ts.isJsxOpeningElement(node)) {
110248                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
110249                 emitJsxTagName(node.tagName);
110250                 emitTypeArguments(node, node.typeArguments);
110251                 if (node.attributes.properties && node.attributes.properties.length > 0) {
110252                     writeSpace();
110253                 }
110254                 emit(node.attributes);
110255                 writeLineSeparatorsAfter(node.attributes, node);
110256                 decreaseIndentIf(indented);
110257             }
110258             writePunctuation(">");
110259         }
110260         function emitJsxText(node) {
110261             writer.writeLiteral(node.text);
110262         }
110263         function emitJsxClosingElementOrFragment(node) {
110264             writePunctuation("</");
110265             if (ts.isJsxClosingElement(node)) {
110266                 emitJsxTagName(node.tagName);
110267             }
110268             writePunctuation(">");
110269         }
110270         function emitJsxAttributes(node) {
110271             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
110272         }
110273         function emitJsxAttribute(node) {
110274             emit(node.name);
110275             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
110276         }
110277         function emitJsxSpreadAttribute(node) {
110278             writePunctuation("{...");
110279             emitExpression(node.expression);
110280             writePunctuation("}");
110281         }
110282         function hasTrailingCommentsAtPosition(pos) {
110283             var result = false;
110284             ts.forEachTrailingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
110285             return result;
110286         }
110287         function hasLeadingCommentsAtPosition(pos) {
110288             var result = false;
110289             ts.forEachLeadingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
110290             return result;
110291         }
110292         function hasCommentsAtPosition(pos) {
110293             return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos);
110294         }
110295         function emitJsxExpression(node) {
110296             var _a;
110297             if (node.expression || (!commentsDisabled && !ts.nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos))) { // preserve empty expressions if they contain comments!
110298                 var isMultiline = currentSourceFile && !ts.nodeIsSynthesized(node) && ts.getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== ts.getLineAndCharacterOfPosition(currentSourceFile, node.end).line;
110299                 if (isMultiline) {
110300                     writer.increaseIndent();
110301                 }
110302                 var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
110303                 emit(node.dotDotDotToken);
110304                 emitExpression(node.expression);
110305                 emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node);
110306                 if (isMultiline) {
110307                     writer.decreaseIndent();
110308                 }
110309             }
110310         }
110311         function emitJsxTagName(node) {
110312             if (node.kind === 79 /* Identifier */) {
110313                 emitExpression(node);
110314             }
110315             else {
110316                 emit(node);
110317             }
110318         }
110319         //
110320         // Clauses
110321         //
110322         function emitCaseClause(node) {
110323             emitTokenWithComment(82 /* CaseKeyword */, node.pos, writeKeyword, node);
110324             writeSpace();
110325             emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
110326             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
110327         }
110328         function emitDefaultClause(node) {
110329             var pos = emitTokenWithComment(88 /* DefaultKeyword */, node.pos, writeKeyword, node);
110330             emitCaseOrDefaultClauseRest(node, node.statements, pos);
110331         }
110332         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
110333             var emitAsSingleStatement = statements.length === 1 &&
110334                 (
110335                 // treat synthesized nodes as located on the same line for emit purposes
110336                 ts.nodeIsSynthesized(parentNode) ||
110337                     ts.nodeIsSynthesized(statements[0]) ||
110338                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
110339             var format = 163969 /* CaseOrDefaultClauseStatements */;
110340             if (emitAsSingleStatement) {
110341                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
110342                 writeSpace();
110343                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
110344             }
110345             else {
110346                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
110347             }
110348             emitList(parentNode, statements, format);
110349         }
110350         function emitHeritageClause(node) {
110351             writeSpace();
110352             writeTokenText(node.token, writeKeyword);
110353             writeSpace();
110354             emitList(node, node.types, 528 /* HeritageClauseTypes */);
110355         }
110356         function emitCatchClause(node) {
110357             var openParenPos = emitTokenWithComment(83 /* CatchKeyword */, node.pos, writeKeyword, node);
110358             writeSpace();
110359             if (node.variableDeclaration) {
110360                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
110361                 emit(node.variableDeclaration);
110362                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
110363                 writeSpace();
110364             }
110365             emit(node.block);
110366         }
110367         //
110368         // Property assignments
110369         //
110370         function emitPropertyAssignment(node) {
110371             emit(node.name);
110372             writePunctuation(":");
110373             writeSpace();
110374             // This is to ensure that we emit comment in the following case:
110375             //      For example:
110376             //          obj = {
110377             //              id: /*comment1*/ ()=>void
110378             //          }
110379             // "comment1" is not considered to be leading comment for node.initializer
110380             // but rather a trailing comment on the previous node.
110381             var initializer = node.initializer;
110382             if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
110383                 var commentRange = ts.getCommentRange(initializer);
110384                 emitTrailingCommentsOfPosition(commentRange.pos);
110385             }
110386             emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma);
110387         }
110388         function emitShorthandPropertyAssignment(node) {
110389             emit(node.name);
110390             if (node.objectAssignmentInitializer) {
110391                 writeSpace();
110392                 writePunctuation("=");
110393                 writeSpace();
110394                 emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma);
110395             }
110396         }
110397         function emitSpreadAssignment(node) {
110398             if (node.expression) {
110399                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
110400                 emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
110401             }
110402         }
110403         //
110404         // Enum
110405         //
110406         function emitEnumMember(node) {
110407             emit(node.name);
110408             emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
110409         }
110410         //
110411         // JSDoc
110412         //
110413         function emitJSDoc(node) {
110414             write("/**");
110415             if (node.comment) {
110416                 var text = ts.getTextOfJSDocComment(node.comment);
110417                 if (text) {
110418                     var lines = text.split(/\r\n?|\n/g);
110419                     for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
110420                         var line = lines_2[_a];
110421                         writeLine();
110422                         writeSpace();
110423                         writePunctuation("*");
110424                         writeSpace();
110425                         write(line);
110426                     }
110427                 }
110428             }
110429             if (node.tags) {
110430                 if (node.tags.length === 1 && node.tags[0].kind === 341 /* JSDocTypeTag */ && !node.comment) {
110431                     writeSpace();
110432                     emit(node.tags[0]);
110433                 }
110434                 else {
110435                     emitList(node, node.tags, 33 /* JSDocComment */);
110436                 }
110437             }
110438             writeSpace();
110439             write("*/");
110440         }
110441         function emitJSDocSimpleTypedTag(tag) {
110442             emitJSDocTagName(tag.tagName);
110443             emitJSDocTypeExpression(tag.typeExpression);
110444             emitJSDocComment(tag.comment);
110445         }
110446         function emitJSDocSeeTag(tag) {
110447             emitJSDocTagName(tag.tagName);
110448             emit(tag.name);
110449             emitJSDocComment(tag.comment);
110450         }
110451         function emitJSDocNameReference(node) {
110452             writeSpace();
110453             writePunctuation("{");
110454             emit(node.name);
110455             writePunctuation("}");
110456         }
110457         function emitJSDocHeritageTag(tag) {
110458             emitJSDocTagName(tag.tagName);
110459             writeSpace();
110460             writePunctuation("{");
110461             emit(tag.class);
110462             writePunctuation("}");
110463             emitJSDocComment(tag.comment);
110464         }
110465         function emitJSDocTemplateTag(tag) {
110466             emitJSDocTagName(tag.tagName);
110467             emitJSDocTypeExpression(tag.constraint);
110468             writeSpace();
110469             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
110470             emitJSDocComment(tag.comment);
110471         }
110472         function emitJSDocTypedefTag(tag) {
110473             emitJSDocTagName(tag.tagName);
110474             if (tag.typeExpression) {
110475                 if (tag.typeExpression.kind === 307 /* JSDocTypeExpression */) {
110476                     emitJSDocTypeExpression(tag.typeExpression);
110477                 }
110478                 else {
110479                     writeSpace();
110480                     writePunctuation("{");
110481                     write("Object");
110482                     if (tag.typeExpression.isArrayType) {
110483                         writePunctuation("[");
110484                         writePunctuation("]");
110485                     }
110486                     writePunctuation("}");
110487                 }
110488             }
110489             if (tag.fullName) {
110490                 writeSpace();
110491                 emit(tag.fullName);
110492             }
110493             emitJSDocComment(tag.comment);
110494             if (tag.typeExpression && tag.typeExpression.kind === 320 /* JSDocTypeLiteral */) {
110495                 emitJSDocTypeLiteral(tag.typeExpression);
110496             }
110497         }
110498         function emitJSDocCallbackTag(tag) {
110499             emitJSDocTagName(tag.tagName);
110500             if (tag.name) {
110501                 writeSpace();
110502                 emit(tag.name);
110503             }
110504             emitJSDocComment(tag.comment);
110505             emitJSDocSignature(tag.typeExpression);
110506         }
110507         function emitJSDocSimpleTag(tag) {
110508             emitJSDocTagName(tag.tagName);
110509             emitJSDocComment(tag.comment);
110510         }
110511         function emitJSDocTypeLiteral(lit) {
110512             emitList(lit, ts.factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
110513         }
110514         function emitJSDocSignature(sig) {
110515             if (sig.typeParameters) {
110516                 emitList(sig, ts.factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
110517             }
110518             if (sig.parameters) {
110519                 emitList(sig, ts.factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
110520             }
110521             if (sig.type) {
110522                 writeLine();
110523                 writeSpace();
110524                 writePunctuation("*");
110525                 writeSpace();
110526                 emit(sig.type);
110527             }
110528         }
110529         function emitJSDocPropertyLikeTag(param) {
110530             emitJSDocTagName(param.tagName);
110531             emitJSDocTypeExpression(param.typeExpression);
110532             writeSpace();
110533             if (param.isBracketed) {
110534                 writePunctuation("[");
110535             }
110536             emit(param.name);
110537             if (param.isBracketed) {
110538                 writePunctuation("]");
110539             }
110540             emitJSDocComment(param.comment);
110541         }
110542         function emitJSDocTagName(tagName) {
110543             writePunctuation("@");
110544             emit(tagName);
110545         }
110546         function emitJSDocComment(comment) {
110547             var text = ts.getTextOfJSDocComment(comment);
110548             if (text) {
110549                 writeSpace();
110550                 write(text);
110551             }
110552         }
110553         function emitJSDocTypeExpression(typeExpression) {
110554             if (typeExpression) {
110555                 writeSpace();
110556                 writePunctuation("{");
110557                 emit(typeExpression.type);
110558                 writePunctuation("}");
110559             }
110560         }
110561         //
110562         // Top-level nodes
110563         //
110564         function emitSourceFile(node) {
110565             writeLine();
110566             var statements = node.statements;
110567             if (emitBodyWithDetachedComments) {
110568                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
110569                 // The synthesized node will have no leading comment so some comments may be missed.
110570                 var shouldEmitDetachedComment = statements.length === 0 ||
110571                     !ts.isPrologueDirective(statements[0]) ||
110572                     ts.nodeIsSynthesized(statements[0]);
110573                 if (shouldEmitDetachedComment) {
110574                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
110575                     return;
110576                 }
110577             }
110578             emitSourceFileWorker(node);
110579         }
110580         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
110581             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
110582             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
110583                 var prepend = _b[_a];
110584                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
110585                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
110586                         var ref = _d[_c];
110587                         emit(ref);
110588                         writeLine();
110589                     }
110590                 }
110591             }
110592         }
110593         function emitTripleSlashDirectivesIfNeeded(node) {
110594             if (node.isDeclarationFile)
110595                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
110596         }
110597         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
110598             if (hasNoDefaultLib) {
110599                 var pos = writer.getTextPos();
110600                 writeComment("/// <reference no-default-lib=\"true\"/>");
110601                 if (bundleFileInfo)
110602                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
110603                 writeLine();
110604             }
110605             if (currentSourceFile && currentSourceFile.moduleName) {
110606                 writeComment("/// <amd-module name=\"".concat(currentSourceFile.moduleName, "\" />"));
110607                 writeLine();
110608             }
110609             if (currentSourceFile && currentSourceFile.amdDependencies) {
110610                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
110611                     var dep = _b[_a];
110612                     if (dep.name) {
110613                         writeComment("/// <amd-dependency name=\"".concat(dep.name, "\" path=\"").concat(dep.path, "\" />"));
110614                     }
110615                     else {
110616                         writeComment("/// <amd-dependency path=\"".concat(dep.path, "\" />"));
110617                     }
110618                     writeLine();
110619                 }
110620             }
110621             for (var _c = 0, files_2 = files; _c < files_2.length; _c++) {
110622                 var directive = files_2[_c];
110623                 var pos = writer.getTextPos();
110624                 writeComment("/// <reference path=\"".concat(directive.fileName, "\" />"));
110625                 if (bundleFileInfo)
110626                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
110627                 writeLine();
110628             }
110629             for (var _d = 0, types_24 = types; _d < types_24.length; _d++) {
110630                 var directive = types_24[_d];
110631                 var pos = writer.getTextPos();
110632                 writeComment("/// <reference types=\"".concat(directive.fileName, "\" />"));
110633                 if (bundleFileInfo)
110634                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
110635                 writeLine();
110636             }
110637             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
110638                 var directive = libs_1[_e];
110639                 var pos = writer.getTextPos();
110640                 writeComment("/// <reference lib=\"".concat(directive.fileName, "\" />"));
110641                 if (bundleFileInfo)
110642                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
110643                 writeLine();
110644             }
110645         }
110646         function emitSourceFileWorker(node) {
110647             var statements = node.statements;
110648             pushNameGenerationScope(node);
110649             ts.forEach(node.statements, generateNames);
110650             emitHelpers(node);
110651             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
110652             emitTripleSlashDirectivesIfNeeded(node);
110653             emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index);
110654             popNameGenerationScope(node);
110655         }
110656         // Transformation nodes
110657         function emitPartiallyEmittedExpression(node) {
110658             emitExpression(node.expression);
110659         }
110660         function emitCommaList(node) {
110661             emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined);
110662         }
110663         /**
110664          * Emits any prologue directives at the start of a Statement list, returning the
110665          * number of prologue directives written to the output.
110666          */
110667         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
110668             var needsToSetSourceFile = !!sourceFile;
110669             for (var i = 0; i < statements.length; i++) {
110670                 var statement = statements[i];
110671                 if (ts.isPrologueDirective(statement)) {
110672                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
110673                     if (shouldEmitPrologueDirective) {
110674                         if (needsToSetSourceFile) {
110675                             needsToSetSourceFile = false;
110676                             setSourceFile(sourceFile);
110677                         }
110678                         writeLine();
110679                         var pos = writer.getTextPos();
110680                         emit(statement);
110681                         if (recordBundleFileSection && bundleFileInfo)
110682                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
110683                         if (seenPrologueDirectives) {
110684                             seenPrologueDirectives.add(statement.expression.text);
110685                         }
110686                     }
110687                 }
110688                 else {
110689                     // return index of the first non prologue directive
110690                     return i;
110691                 }
110692             }
110693             return statements.length;
110694         }
110695         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
110696             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
110697                 var prologue = prologues_1[_a];
110698                 if (!seenPrologueDirectives.has(prologue.data)) {
110699                     writeLine();
110700                     var pos = writer.getTextPos();
110701                     emit(prologue);
110702                     if (bundleFileInfo)
110703                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
110704                     if (seenPrologueDirectives) {
110705                         seenPrologueDirectives.add(prologue.data);
110706                     }
110707                 }
110708             }
110709         }
110710         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
110711             if (ts.isSourceFile(sourceFileOrBundle)) {
110712                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
110713             }
110714             else {
110715                 var seenPrologueDirectives = new ts.Set();
110716                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
110717                     var prepend = _b[_a];
110718                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
110719                 }
110720                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
110721                     var sourceFile = _d[_c];
110722                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
110723                 }
110724                 setSourceFile(undefined);
110725             }
110726         }
110727         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
110728             var seenPrologueDirectives = new ts.Set();
110729             var prologues;
110730             for (var index = 0; index < bundle.sourceFiles.length; index++) {
110731                 var sourceFile = bundle.sourceFiles[index];
110732                 var directives = void 0;
110733                 var end = 0;
110734                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
110735                     var statement = _b[_a];
110736                     if (!ts.isPrologueDirective(statement))
110737                         break;
110738                     if (seenPrologueDirectives.has(statement.expression.text))
110739                         continue;
110740                     seenPrologueDirectives.add(statement.expression.text);
110741                     (directives || (directives = [])).push({
110742                         pos: statement.pos,
110743                         end: statement.end,
110744                         expression: {
110745                             pos: statement.expression.pos,
110746                             end: statement.expression.end,
110747                             text: statement.expression.text
110748                         }
110749                     });
110750                     end = end < statement.end ? statement.end : end;
110751                 }
110752                 if (directives)
110753                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
110754             }
110755             return prologues;
110756         }
110757         function emitShebangIfNeeded(sourceFileOrBundle) {
110758             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
110759                 var shebang = ts.getShebang(sourceFileOrBundle.text);
110760                 if (shebang) {
110761                     writeComment(shebang);
110762                     writeLine();
110763                     return true;
110764                 }
110765             }
110766             else {
110767                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
110768                     var prepend = _b[_a];
110769                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
110770                     if (emitShebangIfNeeded(prepend)) {
110771                         return true;
110772                     }
110773                 }
110774                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
110775                     var sourceFile = _d[_c];
110776                     // Emit only the first encountered shebang
110777                     if (emitShebangIfNeeded(sourceFile)) {
110778                         return true;
110779                     }
110780                 }
110781             }
110782         }
110783         //
110784         // Helpers
110785         //
110786         function emitNodeWithWriter(node, writer) {
110787             if (!node)
110788                 return;
110789             var savedWrite = write;
110790             write = writer;
110791             emit(node);
110792             write = savedWrite;
110793         }
110794         function emitModifiers(node, modifiers) {
110795             if (modifiers && modifiers.length) {
110796                 emitList(node, modifiers, 262656 /* Modifiers */);
110797                 writeSpace();
110798             }
110799         }
110800         function emitTypeAnnotation(node) {
110801             if (node) {
110802                 writePunctuation(":");
110803                 writeSpace();
110804                 emit(node);
110805             }
110806         }
110807         function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) {
110808             if (node) {
110809                 writeSpace();
110810                 emitTokenWithComment(63 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
110811                 writeSpace();
110812                 emitExpression(node, parenthesizerRule);
110813             }
110814         }
110815         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
110816             if (node) {
110817                 prefixWriter(prefix);
110818                 emit(node);
110819             }
110820         }
110821         function emitWithLeadingSpace(node) {
110822             if (node) {
110823                 writeSpace();
110824                 emit(node);
110825             }
110826         }
110827         function emitExpressionWithLeadingSpace(node, parenthesizerRule) {
110828             if (node) {
110829                 writeSpace();
110830                 emitExpression(node, parenthesizerRule);
110831             }
110832         }
110833         function emitWithTrailingSpace(node) {
110834             if (node) {
110835                 emit(node);
110836                 writeSpace();
110837             }
110838         }
110839         function emitEmbeddedStatement(parent, node) {
110840             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
110841                 writeSpace();
110842                 emit(node);
110843             }
110844             else {
110845                 writeLine();
110846                 increaseIndent();
110847                 if (ts.isEmptyStatement(node)) {
110848                     pipelineEmit(5 /* EmbeddedStatement */, node);
110849                 }
110850                 else {
110851                     emit(node);
110852                 }
110853                 decreaseIndent();
110854             }
110855         }
110856         function emitDecorators(parentNode, decorators) {
110857             emitList(parentNode, decorators, 2146305 /* Decorators */);
110858         }
110859         function emitTypeArguments(parentNode, typeArguments) {
110860             emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType);
110861         }
110862         function emitTypeParameters(parentNode, typeParameters) {
110863             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
110864                 return emitTypeArguments(parentNode, parentNode.typeArguments);
110865             }
110866             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
110867         }
110868         function emitParameters(parentNode, parameters) {
110869             emitList(parentNode, parameters, 2576 /* Parameters */);
110870         }
110871         function canEmitSimpleArrowHead(parentNode, parameters) {
110872             var parameter = ts.singleOrUndefined(parameters);
110873             return parameter
110874                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
110875                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
110876                 && !parentNode.type // arrow function may not have return type annotation
110877                 && !ts.some(parentNode.decorators) // parent may not have decorators
110878                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
110879                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
110880                 && !ts.some(parameter.decorators) // parameter may not have decorators
110881                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
110882                 && !parameter.dotDotDotToken // parameter may not be rest
110883                 && !parameter.questionToken // parameter may not be optional
110884                 && !parameter.type // parameter may not have a type annotation
110885                 && !parameter.initializer // parameter may not have an initializer
110886                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
110887         }
110888         function emitParametersForArrow(parentNode, parameters) {
110889             if (canEmitSimpleArrowHead(parentNode, parameters)) {
110890                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
110891             }
110892             else {
110893                 emitParameters(parentNode, parameters);
110894             }
110895         }
110896         function emitParametersForIndexSignature(parentNode, parameters) {
110897             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
110898         }
110899         function writeDelimiter(format) {
110900             switch (format & 60 /* DelimitersMask */) {
110901                 case 0 /* None */:
110902                     break;
110903                 case 16 /* CommaDelimited */:
110904                     writePunctuation(",");
110905                     break;
110906                 case 4 /* BarDelimited */:
110907                     writeSpace();
110908                     writePunctuation("|");
110909                     break;
110910                 case 32 /* AsteriskDelimited */:
110911                     writeSpace();
110912                     writePunctuation("*");
110913                     writeSpace();
110914                     break;
110915                 case 8 /* AmpersandDelimited */:
110916                     writeSpace();
110917                     writePunctuation("&");
110918                     break;
110919             }
110920         }
110921         function emitList(parentNode, children, format, parenthesizerRule, start, count) {
110922             emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count);
110923         }
110924         function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) {
110925             emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count);
110926         }
110927         function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) {
110928             if (start === void 0) { start = 0; }
110929             if (count === void 0) { count = children ? children.length - start : 0; }
110930             var isUndefined = children === undefined;
110931             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
110932                 return;
110933             }
110934             var isEmpty = children === undefined || start >= children.length || count === 0;
110935             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
110936                 if (onBeforeEmitNodeArray) {
110937                     onBeforeEmitNodeArray(children);
110938                 }
110939                 if (onAfterEmitNodeArray) {
110940                     onAfterEmitNodeArray(children);
110941                 }
110942                 return;
110943             }
110944             if (format & 15360 /* BracketsMask */) {
110945                 writePunctuation(getOpeningBracket(format));
110946                 if (isEmpty && children) {
110947                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
110948                 }
110949             }
110950             if (onBeforeEmitNodeArray) {
110951                 onBeforeEmitNodeArray(children);
110952             }
110953             if (isEmpty) {
110954                 // Write a line terminator if the parent node was multi-line
110955                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) {
110956                     writeLine();
110957                 }
110958                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
110959                     writeSpace();
110960                 }
110961             }
110962             else {
110963                 ts.Debug.type(children);
110964                 // Write the opening line terminator or leading whitespace.
110965                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
110966                 var shouldEmitInterveningComments = mayEmitInterveningComments;
110967                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
110968                 if (leadingLineTerminatorCount) {
110969                     writeLine(leadingLineTerminatorCount);
110970                     shouldEmitInterveningComments = false;
110971                 }
110972                 else if (format & 256 /* SpaceBetweenBraces */) {
110973                     writeSpace();
110974                 }
110975                 // Increase the indent, if requested.
110976                 if (format & 128 /* Indented */) {
110977                     increaseIndent();
110978                 }
110979                 // Emit each child.
110980                 var previousSibling = void 0;
110981                 var previousSourceFileTextKind = void 0;
110982                 var shouldDecreaseIndentAfterEmit = false;
110983                 for (var i = 0; i < count; i++) {
110984                     var child = children[start + i];
110985                     // Write the delimiter if this is not the first node.
110986                     if (format & 32 /* AsteriskDelimited */) {
110987                         // always write JSDoc in the format "\n *"
110988                         writeLine();
110989                         writeDelimiter(format);
110990                     }
110991                     else if (previousSibling) {
110992                         // i.e
110993                         //      function commentedParameters(
110994                         //          /* Parameter a */
110995                         //          a
110996                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
110997                         //          ,
110998                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) {
110999                             emitLeadingCommentsOfPosition(previousSibling.end);
111000                         }
111001                         writeDelimiter(format);
111002                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
111003                         // Write either a line terminator or whitespace to separate the elements.
111004                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
111005                         if (separatingLineTerminatorCount > 0) {
111006                             // If a synthesized node in a single-line list starts on a new
111007                             // line, we should increase the indent.
111008                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
111009                                 increaseIndent();
111010                                 shouldDecreaseIndentAfterEmit = true;
111011                             }
111012                             writeLine(separatingLineTerminatorCount);
111013                             shouldEmitInterveningComments = false;
111014                         }
111015                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
111016                             writeSpace();
111017                         }
111018                     }
111019                     // Emit this child.
111020                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
111021                     if (shouldEmitInterveningComments) {
111022                         if (emitTrailingCommentsOfPosition) {
111023                             var commentRange = ts.getCommentRange(child);
111024                             emitTrailingCommentsOfPosition(commentRange.pos);
111025                         }
111026                     }
111027                     else {
111028                         shouldEmitInterveningComments = mayEmitInterveningComments;
111029                     }
111030                     nextListElementPos = child.pos;
111031                     if (emit.length === 1) {
111032                         emit(child);
111033                     }
111034                     else {
111035                         emit(child, parenthesizerRule);
111036                     }
111037                     if (shouldDecreaseIndentAfterEmit) {
111038                         decreaseIndent();
111039                         shouldDecreaseIndentAfterEmit = false;
111040                     }
111041                     previousSibling = child;
111042                 }
111043                 // Write a trailing comma, if requested.
111044                 var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0;
111045                 var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* NoTrailingComments */);
111046                 var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* AllowTrailingComma */) && (format & 16 /* CommaDelimited */);
111047                 if (hasTrailingComma) {
111048                     if (previousSibling && !skipTrailingComments) {
111049                         emitTokenWithComment(27 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling);
111050                     }
111051                     else {
111052                         writePunctuation(",");
111053                     }
111054                 }
111055                 // Emit any trailing comment of the last element in the list
111056                 // i.e
111057                 //       var array = [...
111058                 //          2
111059                 //          /* end of element 2 */
111060                 //       ];
111061                 if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) {
111062                     emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end);
111063                 }
111064                 // Decrease the indent, if requested.
111065                 if (format & 128 /* Indented */) {
111066                     decreaseIndent();
111067                 }
111068                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
111069                 // Write the closing line terminator or closing whitespace.
111070                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
111071                 if (closingLineTerminatorCount) {
111072                     writeLine(closingLineTerminatorCount);
111073                 }
111074                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
111075                     writeSpace();
111076                 }
111077             }
111078             if (onAfterEmitNodeArray) {
111079                 onAfterEmitNodeArray(children);
111080             }
111081             if (format & 15360 /* BracketsMask */) {
111082                 if (isEmpty && children) {
111083                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
111084                 }
111085                 writePunctuation(getClosingBracket(format));
111086             }
111087         }
111088         // Writers
111089         function writeLiteral(s) {
111090             writer.writeLiteral(s);
111091         }
111092         function writeStringLiteral(s) {
111093             writer.writeStringLiteral(s);
111094         }
111095         function writeBase(s) {
111096             writer.write(s);
111097         }
111098         function writeSymbol(s, sym) {
111099             writer.writeSymbol(s, sym);
111100         }
111101         function writePunctuation(s) {
111102             writer.writePunctuation(s);
111103         }
111104         function writeTrailingSemicolon() {
111105             writer.writeTrailingSemicolon(";");
111106         }
111107         function writeKeyword(s) {
111108             writer.writeKeyword(s);
111109         }
111110         function writeOperator(s) {
111111             writer.writeOperator(s);
111112         }
111113         function writeParameter(s) {
111114             writer.writeParameter(s);
111115         }
111116         function writeComment(s) {
111117             writer.writeComment(s);
111118         }
111119         function writeSpace() {
111120             writer.writeSpace(" ");
111121         }
111122         function writeProperty(s) {
111123             writer.writeProperty(s);
111124         }
111125         function nonEscapingWrite(s) {
111126             // This should be defined in a snippet-escaping text writer.
111127             if (writer.nonEscapingWrite) {
111128                 writer.nonEscapingWrite(s);
111129             }
111130             else {
111131                 writer.write(s);
111132             }
111133         }
111134         function writeLine(count) {
111135             if (count === void 0) { count = 1; }
111136             for (var i = 0; i < count; i++) {
111137                 writer.writeLine(i > 0);
111138             }
111139         }
111140         function increaseIndent() {
111141             writer.increaseIndent();
111142         }
111143         function decreaseIndent() {
111144             writer.decreaseIndent();
111145         }
111146         function writeToken(token, pos, writer, contextNode) {
111147             return !sourceMapsDisabled
111148                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
111149                 : writeTokenText(token, writer, pos);
111150         }
111151         function writeTokenNode(node, writer) {
111152             if (onBeforeEmitToken) {
111153                 onBeforeEmitToken(node);
111154             }
111155             writer(ts.tokenToString(node.kind));
111156             if (onAfterEmitToken) {
111157                 onAfterEmitToken(node);
111158             }
111159         }
111160         function writeTokenText(token, writer, pos) {
111161             var tokenString = ts.tokenToString(token);
111162             writer(tokenString);
111163             return pos < 0 ? pos : pos + tokenString.length;
111164         }
111165         function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
111166             if (ts.getEmitFlags(parentNode) & 1 /* SingleLine */) {
111167                 writeSpace();
111168             }
111169             else if (preserveSourceNewlines) {
111170                 var lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
111171                 if (lines) {
111172                     writeLine(lines);
111173                 }
111174                 else {
111175                     writeSpace();
111176                 }
111177             }
111178             else {
111179                 writeLine();
111180             }
111181         }
111182         function writeLines(text) {
111183             var lines = text.split(/\r\n?|\n/g);
111184             var indentation = ts.guessIndentation(lines);
111185             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
111186                 var lineText = lines_3[_a];
111187                 var line = indentation ? lineText.slice(indentation) : lineText;
111188                 if (line.length) {
111189                     writeLine();
111190                     write(line);
111191                 }
111192             }
111193         }
111194         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
111195             if (lineCount) {
111196                 increaseIndent();
111197                 writeLine(lineCount);
111198             }
111199             else if (writeSpaceIfNotIndenting) {
111200                 writeSpace();
111201             }
111202         }
111203         // Helper function to decrease the indent if we previously indented.  Allows multiple
111204         // previous indent values to be considered at a time.  This also allows caller to just
111205         // call this once, passing in all their appropriate indent values, instead of needing
111206         // to call this helper function multiple times.
111207         function decreaseIndentIf(value1, value2) {
111208             if (value1) {
111209                 decreaseIndent();
111210             }
111211             if (value2) {
111212                 decreaseIndent();
111213             }
111214         }
111215         function getLeadingLineTerminatorCount(parentNode, children, format) {
111216             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
111217                 if (format & 65536 /* PreferNewLine */) {
111218                     return 1;
111219                 }
111220                 var firstChild_1 = children[0];
111221                 if (firstChild_1 === undefined) {
111222                     return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
111223                 }
111224                 if (firstChild_1.pos === nextListElementPos) {
111225                     // If this child starts at the beginning of a list item in a parent list, its leading
111226                     // line terminators have already been written as the separating line terminators of the
111227                     // parent list. Example:
111228                     //
111229                     // class Foo {
111230                     //   constructor() {}
111231                     //   public foo() {}
111232                     // }
111233                     //
111234                     // The outer list is the list of class members, with one line terminator between the
111235                     // constructor and the method. The constructor is written, the separating line terminator
111236                     // is written, and then we start emitting the method. Its modifiers ([public]) constitute an inner
111237                     // list, so we look for its leading line terminators. If we didn't know that we had already
111238                     // written a newline as part of the parent list, it would appear that we need to write a
111239                     // leading newline to start the modifiers.
111240                     return 0;
111241                 }
111242                 if (firstChild_1.kind === 11 /* JsxText */) {
111243                     // JsxText will be written with its leading whitespace, so don't add more manually.
111244                     return 0;
111245                 }
111246                 if (parentNode &&
111247                     !ts.positionIsSynthesized(parentNode.pos) &&
111248                     !ts.nodeIsSynthesized(firstChild_1) &&
111249                     (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) {
111250                     if (preserveSourceNewlines) {
111251                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
111252                     }
111253                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
111254                 }
111255                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
111256                     return 1;
111257                 }
111258             }
111259             return format & 1 /* MultiLine */ ? 1 : 0;
111260         }
111261         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
111262             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
111263                 if (previousNode === undefined || nextNode === undefined) {
111264                     return 0;
111265                 }
111266                 if (nextNode.kind === 11 /* JsxText */) {
111267                     // JsxText will be written with its leading whitespace, so don't add more manually.
111268                     return 0;
111269                 }
111270                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) {
111271                     if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) {
111272                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
111273                     }
111274                     // If `preserveSourceNewlines` is `false` we do not intend to preserve the effective lines between the
111275                     // previous and next node. Instead we naively check whether nodes are on separate lines within the
111276                     // same node parent. If so, we intend to preserve a single line terminator. This is less precise and
111277                     // expensive than checking with `preserveSourceNewlines` as above, but the goal is not to preserve the
111278                     // effective source lines between two sibling nodes.
111279                     else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) {
111280                         return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
111281                     }
111282                     // If the two nodes are not comparable, add a line terminator based on the format that can indicate
111283                     // whether new lines are preferred or not.
111284                     return format & 65536 /* PreferNewLine */ ? 1 : 0;
111285                 }
111286                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
111287                     return 1;
111288                 }
111289             }
111290             else if (ts.getStartsOnNewLine(nextNode)) {
111291                 return 1;
111292             }
111293             return format & 1 /* MultiLine */ ? 1 : 0;
111294         }
111295         function getClosingLineTerminatorCount(parentNode, children, format) {
111296             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
111297                 if (format & 65536 /* PreferNewLine */) {
111298                     return 1;
111299                 }
111300                 var lastChild = ts.lastOrUndefined(children);
111301                 if (lastChild === undefined) {
111302                     return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
111303                 }
111304                 if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
111305                     if (preserveSourceNewlines) {
111306                         var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
111307                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); });
111308                     }
111309                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
111310                 }
111311                 if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
111312                     return 1;
111313                 }
111314             }
111315             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
111316                 return 1;
111317             }
111318             return 0;
111319         }
111320         function getEffectiveLines(getLineDifference) {
111321             // If 'preserveSourceNewlines' is disabled, we should never call this function
111322             // because it could be more expensive than alternative approximations.
111323             ts.Debug.assert(!!preserveSourceNewlines);
111324             // We start by measuring the line difference from a position to its adjacent comments,
111325             // so that this is counted as a one-line difference, not two:
111326             //
111327             //   node1;
111328             //   // NODE2 COMMENT
111329             //   node2;
111330             var lines = getLineDifference(/*includeComments*/ true);
111331             if (lines === 0) {
111332                 // However, if the line difference considering comments was 0, we might have this:
111333                 //
111334                 //   node1; // NODE2 COMMENT
111335                 //   node2;
111336                 //
111337                 // in which case we should be ignoring node2's comment, so this too is counted as
111338                 // a one-line difference, not zero.
111339                 return getLineDifference(/*includeComments*/ false);
111340             }
111341             return lines;
111342         }
111343         function writeLineSeparatorsAndIndentBefore(node, parent) {
111344             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
111345             if (leadingNewlines) {
111346                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
111347             }
111348             return !!leadingNewlines;
111349         }
111350         function writeLineSeparatorsAfter(node, parent) {
111351             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
111352             if (trailingNewlines) {
111353                 writeLine(trailingNewlines);
111354             }
111355         }
111356         function synthesizedNodeStartsOnNewLine(node, format) {
111357             if (ts.nodeIsSynthesized(node)) {
111358                 var startsOnNewLine = ts.getStartsOnNewLine(node);
111359                 if (startsOnNewLine === undefined) {
111360                     return (format & 65536 /* PreferNewLine */) !== 0;
111361                 }
111362                 return startsOnNewLine;
111363             }
111364             return (format & 65536 /* PreferNewLine */) !== 0;
111365         }
111366         function getLinesBetweenNodes(parent, node1, node2) {
111367             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
111368                 return 0;
111369             }
111370             parent = skipSynthesizedParentheses(parent);
111371             node1 = skipSynthesizedParentheses(node1);
111372             node2 = skipSynthesizedParentheses(node2);
111373             // Always use a newline for synthesized code if the synthesizer desires it.
111374             if (ts.getStartsOnNewLine(node2)) {
111375                 return 1;
111376             }
111377             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
111378                 if (preserveSourceNewlines) {
111379                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
111380                 }
111381                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
111382             }
111383             return 0;
111384         }
111385         function isEmptyBlock(block) {
111386             return block.statements.length === 0
111387                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
111388         }
111389         function skipSynthesizedParentheses(node) {
111390             while (node.kind === 211 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
111391                 node = node.expression;
111392             }
111393             return node;
111394         }
111395         function getTextOfNode(node, includeTrivia) {
111396             if (ts.isGeneratedIdentifier(node)) {
111397                 return generateName(node);
111398             }
111399             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
111400                 return ts.idText(node);
111401             }
111402             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
111403                 return getTextOfNode(node.textSourceNode, includeTrivia);
111404             }
111405             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
111406                 return node.text;
111407             }
111408             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
111409         }
111410         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
111411             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
111412                 var textSourceNode = node.textSourceNode;
111413                 if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) {
111414                     var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
111415                     return jsxAttributeEscape ? "\"".concat(ts.escapeJsxAttributeString(text), "\"") :
111416                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"".concat(ts.escapeString(text), "\"") :
111417                             "\"".concat(ts.escapeNonAsciiString(text), "\"");
111418                 }
111419                 else {
111420                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
111421                 }
111422             }
111423             var flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0)
111424                 | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0)
111425                 | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0)
111426                 | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0);
111427             return ts.getLiteralText(node, currentSourceFile, flags);
111428         }
111429         /**
111430          * Push a new name generation scope.
111431          */
111432         function pushNameGenerationScope(node) {
111433             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
111434                 return;
111435             }
111436             tempFlagsStack.push(tempFlags);
111437             tempFlags = 0;
111438             reservedNamesStack.push(reservedNames);
111439         }
111440         /**
111441          * Pop the current name generation scope.
111442          */
111443         function popNameGenerationScope(node) {
111444             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
111445                 return;
111446             }
111447             tempFlags = tempFlagsStack.pop();
111448             reservedNames = reservedNamesStack.pop();
111449         }
111450         function reserveNameInNestedScopes(name) {
111451             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
111452                 reservedNames = new ts.Set();
111453             }
111454             reservedNames.add(name);
111455         }
111456         function generateNames(node) {
111457             if (!node)
111458                 return;
111459             switch (node.kind) {
111460                 case 234 /* Block */:
111461                     ts.forEach(node.statements, generateNames);
111462                     break;
111463                 case 249 /* LabeledStatement */:
111464                 case 247 /* WithStatement */:
111465                 case 239 /* DoStatement */:
111466                 case 240 /* WhileStatement */:
111467                     generateNames(node.statement);
111468                     break;
111469                 case 238 /* IfStatement */:
111470                     generateNames(node.thenStatement);
111471                     generateNames(node.elseStatement);
111472                     break;
111473                 case 241 /* ForStatement */:
111474                 case 243 /* ForOfStatement */:
111475                 case 242 /* ForInStatement */:
111476                     generateNames(node.initializer);
111477                     generateNames(node.statement);
111478                     break;
111479                 case 248 /* SwitchStatement */:
111480                     generateNames(node.caseBlock);
111481                     break;
111482                 case 262 /* CaseBlock */:
111483                     ts.forEach(node.clauses, generateNames);
111484                     break;
111485                 case 288 /* CaseClause */:
111486                 case 289 /* DefaultClause */:
111487                     ts.forEach(node.statements, generateNames);
111488                     break;
111489                 case 251 /* TryStatement */:
111490                     generateNames(node.tryBlock);
111491                     generateNames(node.catchClause);
111492                     generateNames(node.finallyBlock);
111493                     break;
111494                 case 291 /* CatchClause */:
111495                     generateNames(node.variableDeclaration);
111496                     generateNames(node.block);
111497                     break;
111498                 case 236 /* VariableStatement */:
111499                     generateNames(node.declarationList);
111500                     break;
111501                 case 254 /* VariableDeclarationList */:
111502                     ts.forEach(node.declarations, generateNames);
111503                     break;
111504                 case 253 /* VariableDeclaration */:
111505                 case 163 /* Parameter */:
111506                 case 202 /* BindingElement */:
111507                 case 256 /* ClassDeclaration */:
111508                     generateNameIfNeeded(node.name);
111509                     break;
111510                 case 255 /* FunctionDeclaration */:
111511                     generateNameIfNeeded(node.name);
111512                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
111513                         ts.forEach(node.parameters, generateNames);
111514                         generateNames(node.body);
111515                     }
111516                     break;
111517                 case 200 /* ObjectBindingPattern */:
111518                 case 201 /* ArrayBindingPattern */:
111519                     ts.forEach(node.elements, generateNames);
111520                     break;
111521                 case 265 /* ImportDeclaration */:
111522                     generateNames(node.importClause);
111523                     break;
111524                 case 266 /* ImportClause */:
111525                     generateNameIfNeeded(node.name);
111526                     generateNames(node.namedBindings);
111527                     break;
111528                 case 267 /* NamespaceImport */:
111529                     generateNameIfNeeded(node.name);
111530                     break;
111531                 case 273 /* NamespaceExport */:
111532                     generateNameIfNeeded(node.name);
111533                     break;
111534                 case 268 /* NamedImports */:
111535                     ts.forEach(node.elements, generateNames);
111536                     break;
111537                 case 269 /* ImportSpecifier */:
111538                     generateNameIfNeeded(node.propertyName || node.name);
111539                     break;
111540             }
111541         }
111542         function generateMemberNames(node) {
111543             if (!node)
111544                 return;
111545             switch (node.kind) {
111546                 case 294 /* PropertyAssignment */:
111547                 case 295 /* ShorthandPropertyAssignment */:
111548                 case 166 /* PropertyDeclaration */:
111549                 case 168 /* MethodDeclaration */:
111550                 case 171 /* GetAccessor */:
111551                 case 172 /* SetAccessor */:
111552                     generateNameIfNeeded(node.name);
111553                     break;
111554             }
111555         }
111556         function generateNameIfNeeded(name) {
111557             if (name) {
111558                 if (ts.isGeneratedIdentifier(name)) {
111559                     generateName(name);
111560                 }
111561                 else if (ts.isBindingPattern(name)) {
111562                     generateNames(name);
111563                 }
111564             }
111565         }
111566         /**
111567          * Generate the text for a generated identifier.
111568          */
111569         function generateName(name) {
111570             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
111571                 // Node names generate unique names based on their original node
111572                 // and are cached based on that node's id.
111573                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
111574             }
111575             else {
111576                 // Auto, Loop, and Unique names are cached based on their unique
111577                 // autoGenerateId.
111578                 var autoGenerateId = name.autoGenerateId;
111579                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
111580             }
111581         }
111582         function generateNameCached(node, flags) {
111583             var nodeId = ts.getNodeId(node);
111584             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
111585         }
111586         /**
111587          * Returns a value indicating whether a name is unique globally, within the current file,
111588          * or within the NameGenerator.
111589          */
111590         function isUniqueName(name) {
111591             return isFileLevelUniqueName(name)
111592                 && !generatedNames.has(name)
111593                 && !(reservedNames && reservedNames.has(name));
111594         }
111595         /**
111596          * Returns a value indicating whether a name is unique globally or within the current file.
111597          */
111598         function isFileLevelUniqueName(name) {
111599             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
111600         }
111601         /**
111602          * Returns a value indicating whether a name is unique within a container.
111603          */
111604         function isUniqueLocalName(name, container) {
111605             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
111606                 if (node.locals) {
111607                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
111608                     // We conservatively include alias symbols to cover cases where they're emitted as locals
111609                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
111610                         return false;
111611                     }
111612                 }
111613             }
111614             return true;
111615         }
111616         /**
111617          * Return the next available name in the pattern _a ... _z, _0, _1, ...
111618          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
111619          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
111620          */
111621         function makeTempVariableName(flags, reservedInNestedScopes) {
111622             if (flags && !(tempFlags & flags)) {
111623                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
111624                 if (isUniqueName(name)) {
111625                     tempFlags |= flags;
111626                     if (reservedInNestedScopes) {
111627                         reserveNameInNestedScopes(name);
111628                     }
111629                     return name;
111630                 }
111631             }
111632             while (true) {
111633                 var count = tempFlags & 268435455 /* CountMask */;
111634                 tempFlags++;
111635                 // Skip over 'i' and 'n'
111636                 if (count !== 8 && count !== 13) {
111637                     var name = count < 26
111638                         ? "_" + String.fromCharCode(97 /* a */ + count)
111639                         : "_" + (count - 26);
111640                     if (isUniqueName(name)) {
111641                         if (reservedInNestedScopes) {
111642                             reserveNameInNestedScopes(name);
111643                         }
111644                         return name;
111645                     }
111646                 }
111647             }
111648         }
111649         /**
111650          * Generate a name that is unique within the current file and doesn't conflict with any names
111651          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
111652          * where n is a positive integer. Note that names generated by makeTempVariableName and
111653          * makeUniqueName are guaranteed to never conflict.
111654          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
111655          */
111656         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
111657             if (checkFn === void 0) { checkFn = isUniqueName; }
111658             if (optimistic) {
111659                 if (checkFn(baseName)) {
111660                     if (scoped) {
111661                         reserveNameInNestedScopes(baseName);
111662                     }
111663                     else {
111664                         generatedNames.add(baseName);
111665                     }
111666                     return baseName;
111667                 }
111668             }
111669             // Find the first unique 'name_n', where n is a positive number
111670             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
111671                 baseName += "_";
111672             }
111673             var i = 1;
111674             while (true) {
111675                 var generatedName = baseName + i;
111676                 if (checkFn(generatedName)) {
111677                     if (scoped) {
111678                         reserveNameInNestedScopes(generatedName);
111679                     }
111680                     else {
111681                         generatedNames.add(generatedName);
111682                     }
111683                     return generatedName;
111684                 }
111685                 i++;
111686             }
111687         }
111688         function makeFileLevelOptimisticUniqueName(name) {
111689             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
111690         }
111691         /**
111692          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
111693          */
111694         function generateNameForModuleOrEnum(node) {
111695             var name = getTextOfNode(node.name);
111696             // Use module/enum name itself if it is unique, otherwise make a unique variation
111697             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
111698         }
111699         /**
111700          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
111701          */
111702         function generateNameForImportOrExportDeclaration(node) {
111703             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
111704             var baseName = ts.isStringLiteral(expr) ?
111705                 ts.makeIdentifierFromModuleName(expr.text) : "module";
111706             return makeUniqueName(baseName);
111707         }
111708         /**
111709          * Generates a unique name for a default export.
111710          */
111711         function generateNameForExportDefault() {
111712             return makeUniqueName("default");
111713         }
111714         /**
111715          * Generates a unique name for a class expression.
111716          */
111717         function generateNameForClassExpression() {
111718             return makeUniqueName("class");
111719         }
111720         function generateNameForMethodOrAccessor(node) {
111721             if (ts.isIdentifier(node.name)) {
111722                 return generateNameCached(node.name);
111723             }
111724             return makeTempVariableName(0 /* Auto */);
111725         }
111726         /**
111727          * Generates a unique name from a node.
111728          */
111729         function generateNameForNode(node, flags) {
111730             switch (node.kind) {
111731                 case 79 /* Identifier */:
111732                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
111733                 case 260 /* ModuleDeclaration */:
111734                 case 259 /* EnumDeclaration */:
111735                     return generateNameForModuleOrEnum(node);
111736                 case 265 /* ImportDeclaration */:
111737                 case 271 /* ExportDeclaration */:
111738                     return generateNameForImportOrExportDeclaration(node);
111739                 case 255 /* FunctionDeclaration */:
111740                 case 256 /* ClassDeclaration */:
111741                 case 270 /* ExportAssignment */:
111742                     return generateNameForExportDefault();
111743                 case 225 /* ClassExpression */:
111744                     return generateNameForClassExpression();
111745                 case 168 /* MethodDeclaration */:
111746                 case 171 /* GetAccessor */:
111747                 case 172 /* SetAccessor */:
111748                     return generateNameForMethodOrAccessor(node);
111749                 case 161 /* ComputedPropertyName */:
111750                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
111751                 default:
111752                     return makeTempVariableName(0 /* Auto */);
111753             }
111754         }
111755         /**
111756          * Generates a unique identifier for a node.
111757          */
111758         function makeName(name) {
111759             switch (name.autoGenerateFlags & 7 /* KindMask */) {
111760                 case 1 /* Auto */:
111761                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
111762                 case 2 /* Loop */:
111763                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
111764                 case 3 /* Unique */:
111765                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
111766             }
111767             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
111768         }
111769         /**
111770          * Gets the node from which a name should be generated.
111771          */
111772         function getNodeForGeneratedName(name) {
111773             var autoGenerateId = name.autoGenerateId;
111774             var node = name;
111775             var original = node.original;
111776             while (original) {
111777                 node = original;
111778                 // if "node" is a different generated name (having a different
111779                 // "autoGenerateId"), use it and stop traversing.
111780                 if (ts.isIdentifier(node)
111781                     && !!(node.autoGenerateFlags & 4 /* Node */)
111782                     && node.autoGenerateId !== autoGenerateId) {
111783                     break;
111784                 }
111785                 original = node.original;
111786             }
111787             // otherwise, return the original node for the source;
111788             return node;
111789         }
111790         // Comments
111791         function pipelineEmitWithComments(hint, node) {
111792             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
111793             var savedContainerPos = containerPos;
111794             var savedContainerEnd = containerEnd;
111795             var savedDeclarationListContainerEnd = declarationListContainerEnd;
111796             emitCommentsBeforeNode(node);
111797             pipelinePhase(hint, node);
111798             emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
111799         }
111800         function emitCommentsBeforeNode(node) {
111801             var emitFlags = ts.getEmitFlags(node);
111802             var commentRange = ts.getCommentRange(node);
111803             // Emit leading comments
111804             emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end);
111805             if (emitFlags & 2048 /* NoNestedComments */) {
111806                 commentsDisabled = true;
111807             }
111808         }
111809         function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) {
111810             var emitFlags = ts.getEmitFlags(node);
111811             var commentRange = ts.getCommentRange(node);
111812             // Emit trailing comments
111813             if (emitFlags & 2048 /* NoNestedComments */) {
111814                 commentsDisabled = false;
111815             }
111816             emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
111817         }
111818         function emitLeadingCommentsOfNode(node, emitFlags, pos, end) {
111819             enterComment();
111820             hasWrittenComment = false;
111821             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
111822             // It is expensive to walk entire tree just to set one kind of node to have no comments.
111823             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
111824             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
111825             // Save current container state on the stack.
111826             if ((pos > 0 || end > 0) && pos !== end) {
111827                 // Emit leading comments if the position is not synthesized and the node
111828                 // has not opted out from emitting leading comments.
111829                 if (!skipLeadingComments) {
111830                     emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 347 /* NotEmittedStatement */);
111831                 }
111832                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
111833                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
111834                     containerPos = pos;
111835                 }
111836                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
111837                     // As above.
111838                     containerEnd = end;
111839                     // To avoid invalid comment emit in a down-level binding pattern, we
111840                     // keep track of the last declaration list container's end
111841                     if (node.kind === 254 /* VariableDeclarationList */) {
111842                         declarationListContainerEnd = end;
111843                     }
111844                 }
111845             }
111846             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
111847             exitComment();
111848         }
111849         function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) {
111850             enterComment();
111851             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
111852             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
111853             if ((pos > 0 || end > 0) && pos !== end) {
111854                 // Restore previous container state.
111855                 containerPos = savedContainerPos;
111856                 containerEnd = savedContainerEnd;
111857                 declarationListContainerEnd = savedDeclarationListContainerEnd;
111858                 // Emit trailing comments if the position is not synthesized and the node
111859                 // has not opted out from emitting leading comments and is an emitted node.
111860                 if (!skipTrailingComments && node.kind !== 347 /* NotEmittedStatement */) {
111861                     emitTrailingComments(end);
111862                 }
111863             }
111864             exitComment();
111865         }
111866         function emitLeadingSynthesizedComment(comment) {
111867             if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
111868                 writer.writeLine();
111869             }
111870             writeSynthesizedComment(comment);
111871             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
111872                 writer.writeLine();
111873             }
111874             else {
111875                 writer.writeSpace(" ");
111876             }
111877         }
111878         function emitTrailingSynthesizedComment(comment) {
111879             if (!writer.isAtStartOfLine()) {
111880                 writer.writeSpace(" ");
111881             }
111882             writeSynthesizedComment(comment);
111883             if (comment.hasTrailingNewLine) {
111884                 writer.writeLine();
111885             }
111886         }
111887         function writeSynthesizedComment(comment) {
111888             var text = formatSynthesizedComment(comment);
111889             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
111890             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
111891         }
111892         function formatSynthesizedComment(comment) {
111893             return comment.kind === 3 /* MultiLineCommentTrivia */
111894                 ? "/*".concat(comment.text, "*/")
111895                 : "//".concat(comment.text);
111896         }
111897         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
111898             enterComment();
111899             var pos = detachedRange.pos, end = detachedRange.end;
111900             var emitFlags = ts.getEmitFlags(node);
111901             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
111902             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
111903             if (!skipLeadingComments) {
111904                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
111905             }
111906             exitComment();
111907             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
111908                 commentsDisabled = true;
111909                 emitCallback(node);
111910                 commentsDisabled = false;
111911             }
111912             else {
111913                 emitCallback(node);
111914             }
111915             enterComment();
111916             if (!skipTrailingComments) {
111917                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
111918                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
111919                     writer.writeLine();
111920                 }
111921             }
111922             exitComment();
111923         }
111924         function originalNodesHaveSameParent(nodeA, nodeB) {
111925             nodeA = ts.getOriginalNode(nodeA);
111926             // For performance, do not call `getOriginalNode` for `nodeB` if `nodeA` doesn't even
111927             // have a parent node.
111928             return nodeA.parent && nodeA.parent === ts.getOriginalNode(nodeB).parent;
111929         }
111930         function siblingNodePositionsAreComparable(previousNode, nextNode) {
111931             if (nextNode.pos < previousNode.end) {
111932                 return false;
111933             }
111934             previousNode = ts.getOriginalNode(previousNode);
111935             nextNode = ts.getOriginalNode(nextNode);
111936             var parent = previousNode.parent;
111937             if (!parent || parent !== nextNode.parent) {
111938                 return false;
111939             }
111940             var parentNodeArray = ts.getContainingNodeArray(previousNode);
111941             var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode);
111942             return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1;
111943         }
111944         function emitLeadingComments(pos, isEmittedNode) {
111945             hasWrittenComment = false;
111946             if (isEmittedNode) {
111947                 if (pos === 0 && (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.isDeclarationFile)) {
111948                     forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
111949                 }
111950                 else {
111951                     forEachLeadingCommentToEmit(pos, emitLeadingComment);
111952                 }
111953             }
111954             else if (pos === 0) {
111955                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
111956                 // unless it is a triple slash comment at the top of the file.
111957                 // For Example:
111958                 //      /// <reference-path ...>
111959                 //      declare var x;
111960                 //      /// <reference-path ...>
111961                 //      interface F {}
111962                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
111963                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
111964             }
111965         }
111966         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
111967             if (isTripleSlashComment(commentPos, commentEnd)) {
111968                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
111969             }
111970         }
111971         function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
111972             if (!isTripleSlashComment(commentPos, commentEnd)) {
111973                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
111974             }
111975         }
111976         function shouldWriteComment(text, pos) {
111977             if (printerOptions.onlyPrintJsDocStyle) {
111978                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
111979             }
111980             return true;
111981         }
111982         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
111983             if (!shouldWriteComment(currentSourceFile.text, commentPos))
111984                 return;
111985             if (!hasWrittenComment) {
111986                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
111987                 hasWrittenComment = true;
111988             }
111989             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
111990             emitPos(commentPos);
111991             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
111992             emitPos(commentEnd);
111993             if (hasTrailingNewLine) {
111994                 writer.writeLine();
111995             }
111996             else if (kind === 3 /* MultiLineCommentTrivia */) {
111997                 writer.writeSpace(" ");
111998             }
111999         }
112000         function emitLeadingCommentsOfPosition(pos) {
112001             if (commentsDisabled || pos === -1) {
112002                 return;
112003             }
112004             emitLeadingComments(pos, /*isEmittedNode*/ true);
112005         }
112006         function emitTrailingComments(pos) {
112007             forEachTrailingCommentToEmit(pos, emitTrailingComment);
112008         }
112009         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
112010             if (!shouldWriteComment(currentSourceFile.text, commentPos))
112011                 return;
112012             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
112013             if (!writer.isAtStartOfLine()) {
112014                 writer.writeSpace(" ");
112015             }
112016             emitPos(commentPos);
112017             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
112018             emitPos(commentEnd);
112019             if (hasTrailingNewLine) {
112020                 writer.writeLine();
112021             }
112022         }
112023         function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) {
112024             if (commentsDisabled) {
112025                 return;
112026             }
112027             enterComment();
112028             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition);
112029             exitComment();
112030         }
112031         function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) {
112032             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
112033             emitPos(commentPos);
112034             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
112035             emitPos(commentEnd);
112036             if (kind === 2 /* SingleLineCommentTrivia */) {
112037                 writer.writeLine(); // still write a newline for single-line comments, so closing tokens aren't written on the same line
112038             }
112039         }
112040         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
112041             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
112042             emitPos(commentPos);
112043             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
112044             emitPos(commentEnd);
112045             if (hasTrailingNewLine) {
112046                 writer.writeLine();
112047             }
112048             else {
112049                 writer.writeSpace(" ");
112050             }
112051         }
112052         function forEachLeadingCommentToEmit(pos, cb) {
112053             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
112054             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
112055                 if (hasDetachedComments(pos)) {
112056                     forEachLeadingCommentWithoutDetachedComments(cb);
112057                 }
112058                 else {
112059                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
112060                 }
112061             }
112062         }
112063         function forEachTrailingCommentToEmit(end, cb) {
112064             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
112065             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
112066                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
112067             }
112068         }
112069         function hasDetachedComments(pos) {
112070             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
112071         }
112072         function forEachLeadingCommentWithoutDetachedComments(cb) {
112073             // get the leading comments from detachedPos
112074             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
112075             if (detachedCommentsInfo.length - 1) {
112076                 detachedCommentsInfo.pop();
112077             }
112078             else {
112079                 detachedCommentsInfo = undefined;
112080             }
112081             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
112082         }
112083         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
112084             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
112085             if (currentDetachedCommentInfo) {
112086                 if (detachedCommentsInfo) {
112087                     detachedCommentsInfo.push(currentDetachedCommentInfo);
112088                 }
112089                 else {
112090                     detachedCommentsInfo = [currentDetachedCommentInfo];
112091                 }
112092             }
112093         }
112094         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
112095             if (!shouldWriteComment(currentSourceFile.text, commentPos))
112096                 return;
112097             emitPos(commentPos);
112098             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
112099             emitPos(commentEnd);
112100         }
112101         /**
112102          * Determine if the given comment is a triple-slash
112103          *
112104          * @return true if the comment is a triple-slash comment else false
112105          */
112106         function isTripleSlashComment(commentPos, commentEnd) {
112107             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
112108         }
112109         // Source Maps
112110         function getParsedSourceMap(node) {
112111             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
112112                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
112113             }
112114             return node.parsedSourceMap || undefined;
112115         }
112116         function pipelineEmitWithSourceMaps(hint, node) {
112117             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
112118             emitSourceMapsBeforeNode(node);
112119             pipelinePhase(hint, node);
112120             emitSourceMapsAfterNode(node);
112121         }
112122         function emitSourceMapsBeforeNode(node) {
112123             var emitFlags = ts.getEmitFlags(node);
112124             var sourceMapRange = ts.getSourceMapRange(node);
112125             // Emit leading sourcemap
112126             if (ts.isUnparsedNode(node)) {
112127                 ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers");
112128                 var parsed = getParsedSourceMap(node.parent);
112129                 if (parsed && sourceMapGenerator) {
112130                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
112131                 }
112132             }
112133             else {
112134                 var source = sourceMapRange.source || sourceMapSource;
112135                 if (node.kind !== 347 /* NotEmittedStatement */
112136                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
112137                     && sourceMapRange.pos >= 0) {
112138                     emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos));
112139                 }
112140                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
112141                     sourceMapsDisabled = true;
112142                 }
112143             }
112144         }
112145         function emitSourceMapsAfterNode(node) {
112146             var emitFlags = ts.getEmitFlags(node);
112147             var sourceMapRange = ts.getSourceMapRange(node);
112148             // Emit trailing sourcemap
112149             if (!ts.isUnparsedNode(node)) {
112150                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
112151                     sourceMapsDisabled = false;
112152                 }
112153                 if (node.kind !== 347 /* NotEmittedStatement */
112154                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
112155                     && sourceMapRange.end >= 0) {
112156                     emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end);
112157                 }
112158             }
112159         }
112160         /**
112161          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
112162          */
112163         function skipSourceTrivia(source, pos) {
112164             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
112165         }
112166         /**
112167          * Emits a mapping.
112168          *
112169          * If the position is synthetic (undefined or a negative value), no mapping will be
112170          * created.
112171          *
112172          * @param pos The position.
112173          */
112174         function emitPos(pos) {
112175             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
112176                 return;
112177             }
112178             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
112179             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
112180             /*nameIndex*/ undefined);
112181         }
112182         function emitSourcePos(source, pos) {
112183             if (source !== sourceMapSource) {
112184                 var savedSourceMapSource = sourceMapSource;
112185                 var savedSourceMapSourceIndex = sourceMapSourceIndex;
112186                 setSourceMapSource(source);
112187                 emitPos(pos);
112188                 resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex);
112189             }
112190             else {
112191                 emitPos(pos);
112192             }
112193         }
112194         /**
112195          * Emits a token of a node with possible leading and trailing source maps.
112196          *
112197          * @param node The node containing the token.
112198          * @param token The token to emit.
112199          * @param tokenStartPos The start pos of the token.
112200          * @param emitCallback The callback used to emit the token.
112201          */
112202         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
112203             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
112204                 return emitCallback(token, writer, tokenPos);
112205             }
112206             var emitNode = node && node.emitNode;
112207             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
112208             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
112209             var source = range && range.source || sourceMapSource;
112210             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
112211             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
112212                 emitSourcePos(source, tokenPos);
112213             }
112214             tokenPos = emitCallback(token, writer, tokenPos);
112215             if (range)
112216                 tokenPos = range.end;
112217             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
112218                 emitSourcePos(source, tokenPos);
112219             }
112220             return tokenPos;
112221         }
112222         function setSourceMapSource(source) {
112223             if (sourceMapsDisabled) {
112224                 return;
112225             }
112226             sourceMapSource = source;
112227             if (source === mostRecentlyAddedSourceMapSource) {
112228                 // Fast path for when the new source map is the most recently added, in which case
112229                 // we use its captured index without going through the source map generator.
112230                 sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex;
112231                 return;
112232             }
112233             if (isJsonSourceMapSource(source)) {
112234                 return;
112235             }
112236             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
112237             if (printerOptions.inlineSources) {
112238                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
112239             }
112240             mostRecentlyAddedSourceMapSource = source;
112241             mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex;
112242         }
112243         function resetSourceMapSource(source, sourceIndex) {
112244             sourceMapSource = source;
112245             sourceMapSourceIndex = sourceIndex;
112246         }
112247         function isJsonSourceMapSource(sourceFile) {
112248             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
112249         }
112250     }
112251     ts.createPrinter = createPrinter;
112252     function createBracketsMap() {
112253         var brackets = [];
112254         brackets[1024 /* Braces */] = ["{", "}"];
112255         brackets[2048 /* Parenthesis */] = ["(", ")"];
112256         brackets[4096 /* AngleBrackets */] = ["<", ">"];
112257         brackets[8192 /* SquareBrackets */] = ["[", "]"];
112258         return brackets;
112259     }
112260     function getOpeningBracket(format) {
112261         return brackets[format & 15360 /* BracketsMask */][0];
112262     }
112263     function getClosingBracket(format) {
112264         return brackets[format & 15360 /* BracketsMask */][1];
112265     }
112266     // Flags enum to track count of temp variables and a few dedicated names
112267     var TempFlags;
112268     (function (TempFlags) {
112269         TempFlags[TempFlags["Auto"] = 0] = "Auto";
112270         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
112271         TempFlags[TempFlags["_i"] = 268435456] = "_i";
112272     })(TempFlags || (TempFlags = {}));
112273 })(ts || (ts = {}));
112274 /* @internal */
112275 var ts;
112276 (function (ts) {
112277     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
112278         if (!host.getDirectories || !host.readDirectory) {
112279             return undefined;
112280         }
112281         var cachedReadDirectoryResult = new ts.Map();
112282         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
112283         return {
112284             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
112285             fileExists: fileExists,
112286             readFile: function (path, encoding) { return host.readFile(path, encoding); },
112287             directoryExists: host.directoryExists && directoryExists,
112288             getDirectories: getDirectories,
112289             readDirectory: readDirectory,
112290             createDirectory: host.createDirectory && createDirectory,
112291             writeFile: host.writeFile && writeFile,
112292             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
112293             addOrDeleteFile: addOrDeleteFile,
112294             clearCache: clearCache,
112295             realpath: host.realpath && realpath
112296         };
112297         function toPath(fileName) {
112298             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
112299         }
112300         function getCachedFileSystemEntries(rootDirPath) {
112301             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
112302         }
112303         function getCachedFileSystemEntriesForBaseDir(path) {
112304             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
112305         }
112306         function getBaseNameOfFileName(fileName) {
112307             return ts.getBaseFileName(ts.normalizePath(fileName));
112308         }
112309         function createCachedFileSystemEntries(rootDir, rootDirPath) {
112310             var _a;
112311             if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) {
112312                 var resultFromHost = {
112313                     files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
112314                     directories: host.getDirectories(rootDir) || []
112315                 };
112316                 cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
112317                 return resultFromHost;
112318             }
112319             // If the directory is symlink do not cache the result
112320             if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) {
112321                 cachedReadDirectoryResult.set(rootDirPath, false);
112322                 return false;
112323             }
112324             // Non existing directory
112325             return undefined;
112326         }
112327         /**
112328          * If the readDirectory result was already cached, it returns that
112329          * Otherwise gets result from host and caches it.
112330          * The host request is done under try catch block to avoid caching incorrect result
112331          */
112332         function tryReadDirectory(rootDir, rootDirPath) {
112333             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
112334             var cachedResult = getCachedFileSystemEntries(rootDirPath);
112335             if (cachedResult) {
112336                 return cachedResult;
112337             }
112338             try {
112339                 return createCachedFileSystemEntries(rootDir, rootDirPath);
112340             }
112341             catch (_e) {
112342                 // If there is exception to read directories, dont cache the result and direct the calls to host
112343                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
112344                 return undefined;
112345             }
112346         }
112347         function fileNameEqual(name1, name2) {
112348             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
112349         }
112350         function hasEntry(entries, name) {
112351             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
112352         }
112353         function updateFileSystemEntry(entries, baseName, isValid) {
112354             if (hasEntry(entries, baseName)) {
112355                 if (!isValid) {
112356                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
112357                 }
112358             }
112359             else if (isValid) {
112360                 return entries.push(baseName);
112361             }
112362         }
112363         function writeFile(fileName, data, writeByteOrderMark) {
112364             var path = toPath(fileName);
112365             var result = getCachedFileSystemEntriesForBaseDir(path);
112366             if (result) {
112367                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
112368             }
112369             return host.writeFile(fileName, data, writeByteOrderMark);
112370         }
112371         function fileExists(fileName) {
112372             var path = toPath(fileName);
112373             var result = getCachedFileSystemEntriesForBaseDir(path);
112374             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
112375                 host.fileExists(fileName);
112376         }
112377         function directoryExists(dirPath) {
112378             var path = toPath(dirPath);
112379             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
112380         }
112381         function createDirectory(dirPath) {
112382             var path = toPath(dirPath);
112383             var result = getCachedFileSystemEntriesForBaseDir(path);
112384             var baseFileName = getBaseNameOfFileName(dirPath);
112385             if (result) {
112386                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
112387             }
112388             host.createDirectory(dirPath);
112389         }
112390         function getDirectories(rootDir) {
112391             var rootDirPath = toPath(rootDir);
112392             var result = tryReadDirectory(rootDir, rootDirPath);
112393             if (result) {
112394                 return result.directories.slice();
112395             }
112396             return host.getDirectories(rootDir);
112397         }
112398         function readDirectory(rootDir, extensions, excludes, includes, depth) {
112399             var rootDirPath = toPath(rootDir);
112400             var rootResult = tryReadDirectory(rootDir, rootDirPath);
112401             var rootSymLinkResult;
112402             if (rootResult !== undefined) {
112403                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
112404             }
112405             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
112406             function getFileSystemEntries(dir) {
112407                 var path = toPath(dir);
112408                 if (path === rootDirPath) {
112409                     return rootResult || getFileSystemEntriesFromHost(dir, path);
112410                 }
112411                 var result = tryReadDirectory(dir, path);
112412                 return result !== undefined ?
112413                     result || getFileSystemEntriesFromHost(dir, path) :
112414                     ts.emptyFileSystemEntries;
112415             }
112416             function getFileSystemEntriesFromHost(dir, path) {
112417                 if (rootSymLinkResult && path === rootDirPath)
112418                     return rootSymLinkResult;
112419                 var result = {
112420                     files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray,
112421                     directories: host.getDirectories(dir) || ts.emptyArray
112422                 };
112423                 if (path === rootDirPath)
112424                     rootSymLinkResult = result;
112425                 return result;
112426             }
112427         }
112428         function realpath(s) {
112429             return host.realpath ? host.realpath(s) : s;
112430         }
112431         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
112432             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
112433             if (existingResult !== undefined) {
112434                 // Just clear the cache for now
112435                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
112436                 clearCache();
112437                 return undefined;
112438             }
112439             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
112440             if (!parentResult) {
112441                 return undefined;
112442             }
112443             // This was earlier a file (hence not in cached directory contents)
112444             // or we never cached the directory containing it
112445             if (!host.directoryExists) {
112446                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
112447                 clearCache();
112448                 return undefined;
112449             }
112450             var baseName = getBaseNameOfFileName(fileOrDirectory);
112451             var fsQueryResult = {
112452                 fileExists: host.fileExists(fileOrDirectoryPath),
112453                 directoryExists: host.directoryExists(fileOrDirectoryPath)
112454             };
112455             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
112456                 // Folder added or removed, clear the cache instead of updating the folder and its structure
112457                 clearCache();
112458             }
112459             else {
112460                 // No need to update the directory structure, just files
112461                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
112462             }
112463             return fsQueryResult;
112464         }
112465         function addOrDeleteFile(fileName, filePath, eventKind) {
112466             if (eventKind === ts.FileWatcherEventKind.Changed) {
112467                 return;
112468             }
112469             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
112470             if (parentResult) {
112471                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
112472             }
112473         }
112474         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
112475             updateFileSystemEntry(parentResult.files, baseName, fileExists);
112476         }
112477         function clearCache() {
112478             cachedReadDirectoryResult.clear();
112479         }
112480     }
112481     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
112482     var ConfigFileProgramReloadLevel;
112483     (function (ConfigFileProgramReloadLevel) {
112484         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
112485         /** Update the file name list from the disk */
112486         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
112487         /** Reload completely by re-reading contents of config file from disk and updating program */
112488         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
112489     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
112490     /**
112491      * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project
112492      */
112493     function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) {
112494         var _a;
112495         var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath);
112496         // remove project from all unrelated watchers
112497         extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) {
112498             if (!extendedConfigs.has(extendedConfigFilePath)) {
112499                 watcher.projects.delete(projectPath);
112500                 watcher.close();
112501             }
112502         });
112503         // Update the extended config files watcher
112504         extendedConfigs.forEach(function (extendedConfigFileName, extendedConfigFilePath) {
112505             var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
112506             if (existing) {
112507                 existing.projects.add(projectPath);
112508             }
112509             else {
112510                 // start watching previously unseen extended config
112511                 extendedConfigFilesMap.set(extendedConfigFilePath, {
112512                     projects: new ts.Set([projectPath]),
112513                     watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath),
112514                     close: function () {
112515                         var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
112516                         if (!existing || existing.projects.size !== 0)
112517                             return;
112518                         existing.watcher.close();
112519                         extendedConfigFilesMap.delete(extendedConfigFilePath);
112520                     },
112521                 });
112522             }
112523         });
112524     }
112525     ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher;
112526     /**
112527      * Remove the project from the extended config file watchers and close not needed watches
112528      */
112529     function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) {
112530         extendedConfigFilesMap.forEach(function (watcher) {
112531             if (watcher.projects.delete(projectPath))
112532                 watcher.close();
112533         });
112534     }
112535     ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher;
112536     /**
112537      * Clean the extendsConfigCache when extended config file has changed
112538      */
112539     function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) {
112540         if (!extendedConfigCache.delete(extendedConfigFilePath))
112541             return;
112542         extendedConfigCache.forEach(function (_a, key) {
112543             var _b;
112544             var extendedResult = _a.extendedResult;
112545             if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) {
112546                 cleanExtendedConfigCache(extendedConfigCache, key, toPath);
112547             }
112548         });
112549     }
112550     ts.cleanExtendedConfigCache = cleanExtendedConfigCache;
112551     /**
112552      * Updates watchers based on the package json files used in module resolution
112553      */
112554     function updatePackageJsonWatch(lookups, packageJsonWatches, createPackageJsonWatch) {
112555         var newMap = new ts.Map(lookups);
112556         ts.mutateMap(packageJsonWatches, newMap, {
112557             createNewValue: createPackageJsonWatch,
112558             onDeleteValue: ts.closeFileWatcher
112559         });
112560     }
112561     ts.updatePackageJsonWatch = updatePackageJsonWatch;
112562     /**
112563      * Updates the existing missing file watches with the new set of missing files after new program is created
112564      */
112565     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
112566         var missingFilePaths = program.getMissingFilePaths();
112567         // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap`
112568         var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue);
112569         // Update the missing file paths watcher
112570         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
112571             // Watch the missing files
112572             createNewValue: createMissingFileWatch,
112573             // Files that are no longer missing (e.g. because they are no longer required)
112574             // should no longer be watched.
112575             onDeleteValue: ts.closeFileWatcher
112576         });
112577     }
112578     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
112579     /**
112580      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
112581      * after new program is created because the config file was reloaded or program was created first time from the config file
112582      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
112583      * as wildcard directories wont change unless reloading config file
112584      */
112585     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
112586         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
112587             // Create new watch and recursive info
112588             createNewValue: createWildcardDirectoryWatcher,
112589             // Close existing watch thats not needed any more
112590             onDeleteValue: closeFileWatcherOf,
112591             // Close existing watch that doesnt match in the flags
112592             onExistingValue: updateWildcardDirectoryWatcher
112593         });
112594         function createWildcardDirectoryWatcher(directory, flags) {
112595             // Create new watch and recursive info
112596             return {
112597                 watcher: watchDirectory(directory, flags),
112598                 flags: flags
112599             };
112600         }
112601         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
112602             // Watcher needs to be updated if the recursive flags dont match
112603             if (existingWatcher.flags === flags) {
112604                 return;
112605             }
112606             existingWatcher.watcher.close();
112607             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
112608         }
112609     }
112610     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
112611     /* @internal */
112612     function isIgnoredFileFromWildCardWatching(_a) {
112613         var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath;
112614         var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
112615         if (!newPath) {
112616             writeLog("Project: ".concat(configFileName, " Detected ignored path: ").concat(fileOrDirectory));
112617             return true;
112618         }
112619         fileOrDirectoryPath = newPath;
112620         if (fileOrDirectoryPath === watchedDirPath)
112621             return false;
112622         // If the the added or created file or directory is not supported file name, ignore the file
112623         // But when watched directory is added/removed, we need to reload the file list
112624         if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
112625             writeLog("Project: ".concat(configFileName, " Detected file add/remove of non supported extension: ").concat(fileOrDirectory));
112626             return true;
112627         }
112628         if (ts.isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
112629             writeLog("Project: ".concat(configFileName, " Detected excluded file: ").concat(fileOrDirectory));
112630             return true;
112631         }
112632         if (!program)
112633             return false;
112634         // We want to ignore emit file check if file is not going to be emitted next to source file
112635         // In that case we follow config file inclusion rules
112636         if (ts.outFile(options) || options.outDir)
112637             return false;
112638         // File if emitted next to input needs to be ignored
112639         if (ts.fileExtensionIs(fileOrDirectoryPath, ".d.ts" /* Dts */)) {
112640             // If its declaration directory: its not ignored if not excluded by config
112641             if (options.declarationDir)
112642                 return false;
112643         }
112644         else if (!ts.fileExtensionIsOneOf(fileOrDirectoryPath, ts.supportedJSExtensionsFlat)) {
112645             return false;
112646         }
112647         // just check if sourceFile with the name exists
112648         var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath);
112649         var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
112650         var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined;
112651         if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) ||
112652             hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) {
112653             writeLog("Project: ".concat(configFileName, " Detected output file: ").concat(fileOrDirectory));
112654             return true;
112655         }
112656         return false;
112657         function hasSourceFile(file) {
112658             return realProgram ?
112659                 !!realProgram.getSourceFileByPath(file) :
112660                 builderProgram ?
112661                     builderProgram.getState().fileInfos.has(file) :
112662                     !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; });
112663         }
112664     }
112665     ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching;
112666     function isBuilderProgram(program) {
112667         return !!program.getState;
112668     }
112669     function isEmittedFileOfProgram(program, file) {
112670         if (!program) {
112671             return false;
112672         }
112673         return program.isEmittedFile(file);
112674     }
112675     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
112676     var WatchLogLevel;
112677     (function (WatchLogLevel) {
112678         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
112679         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
112680         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
112681     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
112682     function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) {
112683         ts.setSysLog(watchLogLevel === WatchLogLevel.Verbose ? log : ts.noop);
112684         var plainInvokeFactory = {
112685             watchFile: function (file, callback, pollingInterval, options) { return host.watchFile(file, callback, pollingInterval, options); },
112686             watchDirectory: function (directory, callback, flags, options) { return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options); },
112687         };
112688         var triggerInvokingFactory = watchLogLevel !== WatchLogLevel.None ?
112689             {
112690                 watchFile: createTriggerLoggingAddWatch("watchFile"),
112691                 watchDirectory: createTriggerLoggingAddWatch("watchDirectory")
112692             } :
112693             undefined;
112694         var factory = watchLogLevel === WatchLogLevel.Verbose ?
112695             {
112696                 watchFile: createFileWatcherWithLogging,
112697                 watchDirectory: createDirectoryWatcherWithLogging
112698             } :
112699             triggerInvokingFactory || plainInvokeFactory;
112700         var excludeWatcherFactory = watchLogLevel === WatchLogLevel.Verbose ?
112701             createExcludeWatcherWithLogging :
112702             ts.returnNoopFileWatcher;
112703         return {
112704             watchFile: createExcludeHandlingAddWatch("watchFile"),
112705             watchDirectory: createExcludeHandlingAddWatch("watchDirectory")
112706         };
112707         function createExcludeHandlingAddWatch(key) {
112708             return function (file, cb, flags, options, detailInfo1, detailInfo2) {
112709                 var _a;
112710                 return !ts.matchesExclude(file, key === "watchFile" ? options === null || options === void 0 ? void 0 : options.excludeFiles : options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) === null || _a === void 0 ? void 0 : _a.call(host)) || "") ?
112711                     factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) :
112712                     excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2);
112713             };
112714         }
112715         function useCaseSensitiveFileNames() {
112716             return typeof host.useCaseSensitiveFileNames === "boolean" ?
112717                 host.useCaseSensitiveFileNames :
112718                 host.useCaseSensitiveFileNames();
112719         }
112720         function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) {
112721             log("ExcludeWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)));
112722             return {
112723                 close: function () { return log("ExcludeWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo))); }
112724             };
112725         }
112726         function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
112727             log("FileWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)));
112728             var watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2);
112729             return {
112730                 close: function () {
112731                     log("FileWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)));
112732                     watcher.close();
112733                 }
112734             };
112735         }
112736         function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
112737             var watchInfo = "DirectoryWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
112738             log(watchInfo);
112739             var start = ts.timestamp();
112740             var watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2);
112741             var elapsed = ts.timestamp() - start;
112742             log("Elapsed:: ".concat(elapsed, "ms ").concat(watchInfo));
112743             return {
112744                 close: function () {
112745                     var watchInfo = "DirectoryWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
112746                     log(watchInfo);
112747                     var start = ts.timestamp();
112748                     watcher.close();
112749                     var elapsed = ts.timestamp() - start;
112750                     log("Elapsed:: ".concat(elapsed, "ms ").concat(watchInfo));
112751                 }
112752             };
112753         }
112754         function createTriggerLoggingAddWatch(key) {
112755             return function (file, cb, flags, options, detailInfo1, detailInfo2) { return plainInvokeFactory[key].call(/*thisArgs*/ undefined, file, function () {
112756                 var args = [];
112757                 for (var _i = 0; _i < arguments.length; _i++) {
112758                     args[_i] = arguments[_i];
112759                 }
112760                 var triggerredInfo = "".concat(key === "watchFile" ? "FileWatcher" : "DirectoryWatcher", ":: Triggered with ").concat(args[0], " ").concat(args[1] !== undefined ? args[1] : "", ":: ").concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
112761                 log(triggerredInfo);
112762                 var start = ts.timestamp();
112763                 cb.call.apply(cb, __spreadArray([/*thisArg*/ undefined], args, false));
112764                 var elapsed = ts.timestamp() - start;
112765                 log("Elapsed:: ".concat(elapsed, "ms ").concat(triggerredInfo));
112766             }, flags, options, detailInfo1, detailInfo2); };
112767         }
112768         function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
112769             return "WatchInfo: ".concat(file, " ").concat(flags, " ").concat(JSON.stringify(options), " ").concat(getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : "".concat(detailInfo1, " ").concat(detailInfo2));
112770         }
112771     }
112772     ts.getWatchFactory = getWatchFactory;
112773     function getFallbackOptions(options) {
112774         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
112775         return {
112776             watchFile: fallbackPolling !== undefined ?
112777                 fallbackPolling :
112778                 ts.WatchFileKind.PriorityPollingInterval
112779         };
112780     }
112781     ts.getFallbackOptions = getFallbackOptions;
112782     function closeFileWatcherOf(objWithWatcher) {
112783         objWithWatcher.watcher.close();
112784     }
112785     ts.closeFileWatcherOf = closeFileWatcherOf;
112786 })(ts || (ts = {}));
112787 var ts;
112788 (function (ts) {
112789     function findConfigFile(searchPath, fileExists, configName) {
112790         if (configName === void 0) { configName = "tsconfig.json"; }
112791         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
112792             var fileName = ts.combinePaths(ancestor, configName);
112793             return fileExists(fileName) ? fileName : undefined;
112794         });
112795     }
112796     ts.findConfigFile = findConfigFile;
112797     function resolveTripleslashReference(moduleName, containingFile) {
112798         var basePath = ts.getDirectoryPath(containingFile);
112799         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
112800         return ts.normalizePath(referencedFileName);
112801     }
112802     ts.resolveTripleslashReference = resolveTripleslashReference;
112803     /* @internal */
112804     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
112805         var commonPathComponents;
112806         var failed = ts.forEach(fileNames, function (sourceFile) {
112807             // Each file contributes into common source file path
112808             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
112809             sourcePathComponents.pop(); // The base file name is not part of the common directory path
112810             if (!commonPathComponents) {
112811                 // first file
112812                 commonPathComponents = sourcePathComponents;
112813                 return;
112814             }
112815             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
112816             for (var i = 0; i < n; i++) {
112817                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
112818                     if (i === 0) {
112819                         // Failed to find any common path component
112820                         return true;
112821                     }
112822                     // New common path found that is 0 -> i-1
112823                     commonPathComponents.length = i;
112824                     break;
112825                 }
112826             }
112827             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
112828             if (sourcePathComponents.length < commonPathComponents.length) {
112829                 commonPathComponents.length = sourcePathComponents.length;
112830             }
112831         });
112832         // A common path can not be found when paths span multiple drives on windows, for example
112833         if (failed) {
112834             return "";
112835         }
112836         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
112837             return currentDirectory;
112838         }
112839         return ts.getPathFromPathComponents(commonPathComponents);
112840     }
112841     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
112842     function createCompilerHost(options, setParentNodes) {
112843         return createCompilerHostWorker(options, setParentNodes);
112844     }
112845     ts.createCompilerHost = createCompilerHost;
112846     /*@internal*/
112847     // TODO(shkamat): update this after reworking ts build API
112848     function createCompilerHostWorker(options, setParentNodes, system) {
112849         if (system === void 0) { system = ts.sys; }
112850         var existingDirectories = new ts.Map();
112851         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
112852         var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash;
112853         function getSourceFile(fileName, languageVersion, onError) {
112854             var text;
112855             try {
112856                 ts.performance.mark("beforeIORead");
112857                 text = compilerHost.readFile(fileName);
112858                 ts.performance.mark("afterIORead");
112859                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
112860             }
112861             catch (e) {
112862                 if (onError) {
112863                     onError(e.message);
112864                 }
112865                 text = "";
112866             }
112867             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
112868         }
112869         function directoryExists(directoryPath) {
112870             if (existingDirectories.has(directoryPath)) {
112871                 return true;
112872             }
112873             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
112874                 existingDirectories.set(directoryPath, true);
112875                 return true;
112876             }
112877             return false;
112878         }
112879         function writeFile(fileName, data, writeByteOrderMark, onError) {
112880             try {
112881                 ts.performance.mark("beforeIOWrite");
112882                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
112883                 // the system.writeFile will do its own directory creation and
112884                 // the ensureDirectoriesExist call will always be redundant.
112885                 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); });
112886                 ts.performance.mark("afterIOWrite");
112887                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
112888             }
112889             catch (e) {
112890                 if (onError) {
112891                     onError(e.message);
112892                 }
112893             }
112894         }
112895         var outputFingerprints;
112896         function writeFileWorker(fileName, data, writeByteOrderMark) {
112897             if (!ts.isWatchSet(options) || !system.getModifiedTime) {
112898                 system.writeFile(fileName, data, writeByteOrderMark);
112899                 return;
112900             }
112901             if (!outputFingerprints) {
112902                 outputFingerprints = new ts.Map();
112903             }
112904             var hash = computeHash(data);
112905             var mtimeBefore = system.getModifiedTime(fileName);
112906             if (mtimeBefore) {
112907                 var fingerprint = outputFingerprints.get(fileName);
112908                 // If output has not been changed, and the file has no external modification
112909                 if (fingerprint &&
112910                     fingerprint.byteOrderMark === writeByteOrderMark &&
112911                     fingerprint.hash === hash &&
112912                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
112913                     return;
112914                 }
112915             }
112916             system.writeFile(fileName, data, writeByteOrderMark);
112917             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
112918             outputFingerprints.set(fileName, {
112919                 hash: hash,
112920                 byteOrderMark: writeByteOrderMark,
112921                 mtime: mtimeAfter
112922             });
112923         }
112924         function getDefaultLibLocation() {
112925             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
112926         }
112927         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
112928         var realpath = system.realpath && (function (path) { return system.realpath(path); });
112929         var compilerHost = {
112930             getSourceFile: getSourceFile,
112931             getDefaultLibLocation: getDefaultLibLocation,
112932             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
112933             writeFile: writeFile,
112934             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
112935             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
112936             getCanonicalFileName: getCanonicalFileName,
112937             getNewLine: function () { return newLine; },
112938             fileExists: function (fileName) { return system.fileExists(fileName); },
112939             readFile: function (fileName) { return system.readFile(fileName); },
112940             trace: function (s) { return system.write(s + newLine); },
112941             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
112942             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
112943             getDirectories: function (path) { return system.getDirectories(path); },
112944             realpath: realpath,
112945             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
112946             createDirectory: function (d) { return system.createDirectory(d); },
112947             createHash: ts.maybeBind(system, system.createHash)
112948         };
112949         return compilerHost;
112950     }
112951     ts.createCompilerHostWorker = createCompilerHostWorker;
112952     /*@internal*/
112953     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
112954         var originalReadFile = host.readFile;
112955         var originalFileExists = host.fileExists;
112956         var originalDirectoryExists = host.directoryExists;
112957         var originalCreateDirectory = host.createDirectory;
112958         var originalWriteFile = host.writeFile;
112959         var readFileCache = new ts.Map();
112960         var fileExistsCache = new ts.Map();
112961         var directoryExistsCache = new ts.Map();
112962         var sourceFileCache = new ts.Map();
112963         var readFileWithCache = function (fileName) {
112964             var key = toPath(fileName);
112965             var value = readFileCache.get(key);
112966             if (value !== undefined)
112967                 return value !== false ? value : undefined;
112968             return setReadFileCache(key, fileName);
112969         };
112970         var setReadFileCache = function (key, fileName) {
112971             var newValue = originalReadFile.call(host, fileName);
112972             readFileCache.set(key, newValue !== undefined ? newValue : false);
112973             return newValue;
112974         };
112975         host.readFile = function (fileName) {
112976             var key = toPath(fileName);
112977             var value = readFileCache.get(key);
112978             if (value !== undefined)
112979                 return value !== false ? value : undefined; // could be .d.ts from output
112980             // Cache json or buildInfo
112981             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
112982                 return originalReadFile.call(host, fileName);
112983             }
112984             return setReadFileCache(key, fileName);
112985         };
112986         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
112987             var key = toPath(fileName);
112988             var value = sourceFileCache.get(key);
112989             if (value)
112990                 return value;
112991             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
112992             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
112993                 sourceFileCache.set(key, sourceFile);
112994             }
112995             return sourceFile;
112996         } : undefined;
112997         // fileExists for any kind of extension
112998         host.fileExists = function (fileName) {
112999             var key = toPath(fileName);
113000             var value = fileExistsCache.get(key);
113001             if (value !== undefined)
113002                 return value;
113003             var newValue = originalFileExists.call(host, fileName);
113004             fileExistsCache.set(key, !!newValue);
113005             return newValue;
113006         };
113007         if (originalWriteFile) {
113008             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
113009                 var key = toPath(fileName);
113010                 fileExistsCache.delete(key);
113011                 var value = readFileCache.get(key);
113012                 if (value !== undefined && value !== data) {
113013                     readFileCache.delete(key);
113014                     sourceFileCache.delete(key);
113015                 }
113016                 else if (getSourceFileWithCache) {
113017                     var sourceFile = sourceFileCache.get(key);
113018                     if (sourceFile && sourceFile.text !== data) {
113019                         sourceFileCache.delete(key);
113020                     }
113021                 }
113022                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
113023             };
113024         }
113025         // directoryExists
113026         if (originalDirectoryExists && originalCreateDirectory) {
113027             host.directoryExists = function (directory) {
113028                 var key = toPath(directory);
113029                 var value = directoryExistsCache.get(key);
113030                 if (value !== undefined)
113031                     return value;
113032                 var newValue = originalDirectoryExists.call(host, directory);
113033                 directoryExistsCache.set(key, !!newValue);
113034                 return newValue;
113035             };
113036             host.createDirectory = function (directory) {
113037                 var key = toPath(directory);
113038                 directoryExistsCache.delete(key);
113039                 originalCreateDirectory.call(host, directory);
113040             };
113041         }
113042         return {
113043             originalReadFile: originalReadFile,
113044             originalFileExists: originalFileExists,
113045             originalDirectoryExists: originalDirectoryExists,
113046             originalCreateDirectory: originalCreateDirectory,
113047             originalWriteFile: originalWriteFile,
113048             getSourceFileWithCache: getSourceFileWithCache,
113049             readFileWithCache: readFileWithCache
113050         };
113051     }
113052     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
113053     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
113054         var diagnostics;
113055         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
113056         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
113057         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
113058         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
113059         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
113060         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
113061             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
113062         }
113063         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
113064     }
113065     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
113066     function formatDiagnostics(diagnostics, host) {
113067         var output = "";
113068         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
113069             var diagnostic = diagnostics_3[_i];
113070             output += formatDiagnostic(diagnostic, host);
113071         }
113072         return output;
113073     }
113074     ts.formatDiagnostics = formatDiagnostics;
113075     function formatDiagnostic(diagnostic, host) {
113076         var errorMessage = "".concat(ts.diagnosticCategoryName(diagnostic), " TS").concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())).concat(host.getNewLine());
113077         if (diagnostic.file) {
113078             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
113079             var fileName = diagnostic.file.fileName;
113080             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
113081             return "".concat(relativeFileName, "(").concat(line + 1, ",").concat(character + 1, "): ") + errorMessage;
113082         }
113083         return errorMessage;
113084     }
113085     ts.formatDiagnostic = formatDiagnostic;
113086     /** @internal */
113087     var ForegroundColorEscapeSequences;
113088     (function (ForegroundColorEscapeSequences) {
113089         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
113090         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
113091         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
113092         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
113093         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
113094     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
113095     var gutterStyleSequence = "\u001b[7m";
113096     var gutterSeparator = " ";
113097     var resetEscapeSequence = "\u001b[0m";
113098     var ellipsis = "...";
113099     var halfIndent = "  ";
113100     var indent = "    ";
113101     function getCategoryFormat(category) {
113102         switch (category) {
113103             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
113104             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
113105             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
113106             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
113107         }
113108     }
113109     /** @internal */
113110     function formatColorAndReset(text, formatStyle) {
113111         return formatStyle + text + resetEscapeSequence;
113112     }
113113     ts.formatColorAndReset = formatColorAndReset;
113114     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
113115         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
113116         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
113117         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
113118         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
113119         var gutterWidth = (lastLine + 1 + "").length;
113120         if (hasMoreThanFiveLines) {
113121             gutterWidth = Math.max(ellipsis.length, gutterWidth);
113122         }
113123         var context = "";
113124         for (var i = firstLine; i <= lastLine; i++) {
113125             context += host.getNewLine();
113126             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
113127             // so we'll skip ahead to the second-to-last line.
113128             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
113129                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
113130                 i = lastLine - 1;
113131             }
113132             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
113133             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
113134             var lineContent = file.text.slice(lineStart, lineEnd);
113135             lineContent = ts.trimStringEnd(lineContent); // trim from end
113136             lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces
113137             // Output the gutter and the actual contents of the line.
113138             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
113139             context += lineContent + host.getNewLine();
113140             // Output the gutter and the error span for the line using tildes.
113141             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
113142             context += squiggleColor;
113143             if (i === firstLine) {
113144                 // If we're on the last line, then limit it to the last character of the last line.
113145                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
113146                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
113147                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
113148                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
113149             }
113150             else if (i === lastLine) {
113151                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
113152             }
113153             else {
113154                 // Squiggle the entire line.
113155                 context += lineContent.replace(/./g, "~");
113156             }
113157             context += resetEscapeSequence;
113158         }
113159         return context;
113160     }
113161     /* @internal */
113162     function formatLocation(file, start, host, color) {
113163         if (color === void 0) { color = formatColorAndReset; }
113164         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
113165         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
113166         var output = "";
113167         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
113168         output += ":";
113169         output += color("".concat(firstLine + 1), ForegroundColorEscapeSequences.Yellow);
113170         output += ":";
113171         output += color("".concat(firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
113172         return output;
113173     }
113174     ts.formatLocation = formatLocation;
113175     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
113176         var output = "";
113177         for (var _i = 0, diagnostics_4 = diagnostics; _i < diagnostics_4.length; _i++) {
113178             var diagnostic = diagnostics_4[_i];
113179             if (diagnostic.file) {
113180                 var file = diagnostic.file, start = diagnostic.start;
113181                 output += formatLocation(file, start, host); // TODO: GH#18217
113182                 output += " - ";
113183             }
113184             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
113185             output += formatColorAndReset(" TS".concat(diagnostic.code, ": "), ForegroundColorEscapeSequences.Grey);
113186             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
113187             if (diagnostic.file) {
113188                 output += host.getNewLine();
113189                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
113190             }
113191             if (diagnostic.relatedInformation) {
113192                 output += host.getNewLine();
113193                 for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
113194                     var _c = _b[_a], file = _c.file, start = _c.start, length_9 = _c.length, messageText = _c.messageText;
113195                     if (file) {
113196                         output += host.getNewLine();
113197                         output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
113198                         output += formatCodeSpan(file, start, length_9, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
113199                     }
113200                     output += host.getNewLine();
113201                     output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
113202                 }
113203             }
113204             output += host.getNewLine();
113205         }
113206         return output;
113207     }
113208     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
113209     function flattenDiagnosticMessageText(diag, newLine, indent) {
113210         if (indent === void 0) { indent = 0; }
113211         if (ts.isString(diag)) {
113212             return diag;
113213         }
113214         else if (diag === undefined) {
113215             return "";
113216         }
113217         var result = "";
113218         if (indent) {
113219             result += newLine;
113220             for (var i = 0; i < indent; i++) {
113221                 result += "  ";
113222             }
113223         }
113224         result += diag.messageText;
113225         indent++;
113226         if (diag.next) {
113227             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
113228                 var kid = _a[_i];
113229                 result += flattenDiagnosticMessageText(kid, newLine, indent);
113230             }
113231         }
113232         return result;
113233     }
113234     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
113235     /* @internal */
113236     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
113237         if (names.length === 0) {
113238             return [];
113239         }
113240         var resolutions = [];
113241         var cache = new ts.Map();
113242         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
113243             var name = names_2[_i];
113244             var result = void 0;
113245             if (cache.has(name)) {
113246                 result = cache.get(name);
113247             }
113248             else {
113249                 cache.set(name, result = loader(name, containingFile, redirectedReference));
113250             }
113251             resolutions.push(result);
113252         }
113253         return resolutions;
113254     }
113255     ts.loadWithLocalCache = loadWithLocalCache;
113256     ;
113257     /* @internal */
113258     function getModeForResolutionAtIndex(file, index) {
113259         if (file.impliedNodeFormat === undefined)
113260             return undefined;
113261         // we ensure all elements of file.imports and file.moduleAugmentations have the relevant parent pointers set during program setup,
113262         // so it's safe to use them even pre-bind
113263         return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index));
113264     }
113265     ts.getModeForResolutionAtIndex = getModeForResolutionAtIndex;
113266     /* @internal */
113267     function getModeForUsageLocation(file, usage) {
113268         var _a;
113269         if (file.impliedNodeFormat === undefined)
113270             return undefined;
113271         if (file.impliedNodeFormat !== ts.ModuleKind.ESNext) {
113272             // in cjs files, import call expressions are esm format, otherwise everything is cjs
113273             return ts.isImportCall(ts.walkUpParenthesizedExpressions(usage.parent)) ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
113274         }
113275         // in esm files, import=require statements are cjs format, otherwise everything is esm
113276         // imports are only parent'd up to their containing declaration/expression, so access farther parents with care
113277         var exprParentParent = (_a = ts.walkUpParenthesizedExpressions(usage.parent)) === null || _a === void 0 ? void 0 : _a.parent;
113278         return exprParentParent && ts.isImportEqualsDeclaration(exprParentParent) ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext;
113279     }
113280     ts.getModeForUsageLocation = getModeForUsageLocation;
113281     /* @internal */
113282     function loadWithModeAwareCache(names, containingFile, containingFileName, redirectedReference, loader) {
113283         if (names.length === 0) {
113284             return [];
113285         }
113286         var resolutions = [];
113287         var cache = new ts.Map();
113288         var i = 0;
113289         for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
113290             var name = names_3[_i];
113291             var result = void 0;
113292             var mode = getModeForResolutionAtIndex(containingFile, i);
113293             i++;
113294             var cacheKey = mode !== undefined ? "".concat(mode, "|").concat(name) : name;
113295             if (cache.has(cacheKey)) {
113296                 result = cache.get(cacheKey);
113297             }
113298             else {
113299                 cache.set(cacheKey, result = loader(name, mode, containingFileName, redirectedReference));
113300             }
113301             resolutions.push(result);
113302         }
113303         return resolutions;
113304     }
113305     ts.loadWithModeAwareCache = loadWithModeAwareCache;
113306     /* @internal */
113307     function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
113308         return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, function (resolvedRef, parent) { return resolvedRef && cb(resolvedRef, parent); });
113309     }
113310     ts.forEachResolvedProjectReference = forEachResolvedProjectReference;
113311     function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
113312         var seenResolvedRefs;
113313         return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined);
113314         function worker(projectReferences, resolvedProjectReferences, parent) {
113315             // Visit project references first
113316             if (cbRef) {
113317                 var result = cbRef(projectReferences, parent);
113318                 if (result)
113319                     return result;
113320             }
113321             return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
113322                 if (resolvedRef && (seenResolvedRefs === null || seenResolvedRefs === void 0 ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
113323                     // ignore recursives
113324                     return undefined;
113325                 }
113326                 var result = cbResolvedRef(resolvedRef, parent, index);
113327                 if (result || !resolvedRef)
113328                     return result;
113329                 (seenResolvedRefs || (seenResolvedRefs = new ts.Set())).add(resolvedRef.sourceFile.path);
113330                 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
113331             });
113332         }
113333     }
113334     /* @internal */
113335     ts.inferredTypesContainingFile = "__inferred type names__.ts";
113336     /*@internal*/
113337     function isReferencedFile(reason) {
113338         switch (reason === null || reason === void 0 ? void 0 : reason.kind) {
113339             case ts.FileIncludeKind.Import:
113340             case ts.FileIncludeKind.ReferenceFile:
113341             case ts.FileIncludeKind.TypeReferenceDirective:
113342             case ts.FileIncludeKind.LibReferenceDirective:
113343                 return true;
113344             default:
113345                 return false;
113346         }
113347     }
113348     ts.isReferencedFile = isReferencedFile;
113349     /*@internal*/
113350     function isReferenceFileLocation(location) {
113351         return location.pos !== undefined;
113352     }
113353     ts.isReferenceFileLocation = isReferenceFileLocation;
113354     /*@internal*/
113355     function getReferencedFileLocation(getSourceFileByPath, ref) {
113356         var _a, _b, _c;
113357         var _d, _e, _f, _g;
113358         var file = ts.Debug.checkDefined(getSourceFileByPath(ref.file));
113359         var kind = ref.kind, index = ref.index;
113360         var pos, end, packageId;
113361         switch (kind) {
113362             case ts.FileIncludeKind.Import:
113363                 var importLiteral = getModuleNameStringLiteralAt(file, index);
113364                 packageId = (_e = (_d = file.resolvedModules) === null || _d === void 0 ? void 0 : _d.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) === null || _e === void 0 ? void 0 : _e.packageId;
113365                 if (importLiteral.pos === -1)
113366                     return { file: file, packageId: packageId, text: importLiteral.text };
113367                 pos = ts.skipTrivia(file.text, importLiteral.pos);
113368                 end = importLiteral.end;
113369                 break;
113370             case ts.FileIncludeKind.ReferenceFile:
113371                 (_a = file.referencedFiles[index], pos = _a.pos, end = _a.end);
113372                 break;
113373             case ts.FileIncludeKind.TypeReferenceDirective:
113374                 (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
113375                 packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId;
113376                 break;
113377             case ts.FileIncludeKind.LibReferenceDirective:
113378                 (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end);
113379                 break;
113380             default:
113381                 return ts.Debug.assertNever(kind);
113382         }
113383         return { file: file, pos: pos, end: end, packageId: packageId };
113384     }
113385     ts.getReferencedFileLocation = getReferencedFileLocation;
113386     /**
113387      * Determines if program structure is upto date or needs to be recreated
113388      */
113389     /* @internal */
113390     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) {
113391         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
113392         if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames()))
113393             return false;
113394         // If root file names don't match
113395         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames))
113396             return false;
113397         var seenResolvedRefs;
113398         // If project references don't match
113399         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate))
113400             return false;
113401         // If any file is not up-to-date, then the whole program is not up-to-date
113402         if (program.getSourceFiles().some(sourceFileNotUptoDate))
113403             return false;
113404         // If any of the missing file paths are now created
113405         if (program.getMissingFilePaths().some(fileExists))
113406             return false;
113407         var currentOptions = program.getCompilerOptions();
113408         // If the compilation settings do no match, then the program is not up-to-date
113409         if (!ts.compareDataObjects(currentOptions, newOptions))
113410             return false;
113411         // If everything matches but the text of config file is changed,
113412         // error locations can change for program options, so update the program
113413         if (currentOptions.configFile && newOptions.configFile)
113414             return currentOptions.configFile.text === newOptions.configFile.text;
113415         return true;
113416         function sourceFileNotUptoDate(sourceFile) {
113417             return !sourceFileVersionUptoDate(sourceFile) ||
113418                 hasInvalidatedResolution(sourceFile.path);
113419         }
113420         function sourceFileVersionUptoDate(sourceFile) {
113421             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
113422         }
113423         function projectReferenceUptoDate(oldRef, newRef, index) {
113424             return ts.projectReferenceIsEqualTo(oldRef, newRef) &&
113425                 resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
113426         }
113427         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
113428             if (oldResolvedRef) {
113429                 // Assume true
113430                 if (ts.contains(seenResolvedRefs, oldResolvedRef))
113431                     return true;
113432                 var refPath_1 = resolveProjectReferencePath(oldRef);
113433                 var newParsedCommandLine = getParsedCommandLine(refPath_1);
113434                 // Check if config file exists
113435                 if (!newParsedCommandLine)
113436                     return false;
113437                 // If change in source file
113438                 if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile)
113439                     return false;
113440                 // check file names
113441                 if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames))
113442                     return false;
113443                 // Add to seen before checking the referenced paths of this config file
113444                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
113445                 // If child project references are upto date, this project reference is uptodate
113446                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
113447                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
113448                 });
113449             }
113450             // In old program, not able to resolve project reference path,
113451             // so if config file doesnt exist, it is uptodate.
113452             var refPath = resolveProjectReferencePath(oldRef);
113453             return !getParsedCommandLine(refPath);
113454         }
113455     }
113456     ts.isProgramUptoDate = isProgramUptoDate;
113457     function getConfigFileParsingDiagnostics(configFileParseResult) {
113458         return configFileParseResult.options.configFile ? __spreadArray(__spreadArray([], configFileParseResult.options.configFile.parseDiagnostics, true), configFileParseResult.errors, true) :
113459             configFileParseResult.errors;
113460     }
113461     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
113462     /**
113463      * A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the
113464      * `options` parameter.
113465      *
113466      * @param fileName The normalized absolute path to check the format of (it need not exist on disk)
113467      * @param [packageJsonInfoCache] A cache for package file lookups - it's best to have a cache when this function is called often
113468      * @param host The ModuleResolutionHost which can perform the filesystem lookups for package json data
113469      * @param options The compiler options to perform the analysis under - relevant options are `moduleResolution` and `traceResolution`
113470      * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format
113471      */
113472     function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) {
113473         switch (ts.getEmitModuleResolutionKind(options)) {
113474             case ts.ModuleResolutionKind.Node12:
113475             case ts.ModuleResolutionKind.NodeNext:
113476                 return ts.fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".mjs" /* Mjs */]) ? ts.ModuleKind.ESNext :
113477                     ts.fileExtensionIsOneOf(fileName, [".d.cts" /* Dcts */, ".cts" /* Cts */, ".cjs" /* Cjs */]) ? ts.ModuleKind.CommonJS :
113478                         ts.fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */]) ? lookupFromPackageJson() :
113479                             undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline
113480             default:
113481                 return undefined;
113482         }
113483         function lookupFromPackageJson() {
113484             var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options);
113485             return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
113486         }
113487     }
113488     ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile;
113489     /**
113490      * Determine if source file needs to be re-created even if its text hasn't changed
113491      */
113492     function shouldProgramCreateNewSourceFiles(program, newOptions) {
113493         if (!program)
113494             return false;
113495         // If any compiler options change, we can't reuse old source file even if version match
113496         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
113497         return ts.optionsHaveChanges(program.getCompilerOptions(), newOptions, ts.sourceFileAffectingCompilerOptions);
113498     }
113499     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
113500         return {
113501             rootNames: rootNames,
113502             options: options,
113503             host: host,
113504             oldProgram: oldProgram,
113505             configFileParsingDiagnostics: configFileParsingDiagnostics
113506         };
113507     }
113508     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
113509         var _a, _b, _c, _d;
113510         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
113511         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
113512         var oldProgram = createProgramOptions.oldProgram;
113513         var processingDefaultLibFiles;
113514         var processingOtherFiles;
113515         var files;
113516         var symlinks;
113517         var commonSourceDirectory;
113518         var diagnosticsProducingTypeChecker;
113519         var noDiagnosticsTypeChecker;
113520         var classifiableNames;
113521         var ambientModuleNameToUnmodifiedFileName = new ts.Map();
113522         var fileReasons = ts.createMultiMap();
113523         var cachedBindAndCheckDiagnosticsForFile = {};
113524         var cachedDeclarationDiagnosticsForFile = {};
113525         var resolvedTypeReferenceDirectives = new ts.Map();
113526         var fileProcessingDiagnostics;
113527         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
113528         // This works as imported modules are discovered recursively in a depth first manner, specifically:
113529         // - For each root file, findSourceFile is called.
113530         // - This calls processImportedModules for each module imported in the source file.
113531         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
113532         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
113533         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
113534         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
113535         var currentNodeModulesDepth = 0;
113536         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
113537         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
113538         var modulesWithElidedImports = new ts.Map();
113539         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
113540         var sourceFilesFoundSearchingNodeModules = new ts.Map();
113541         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true);
113542         ts.performance.mark("beforeProgram");
113543         var host = createProgramOptions.host || createCompilerHost(options);
113544         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
113545         var skipDefaultLib = options.noLib;
113546         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
113547         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
113548         var programDiagnostics = ts.createDiagnosticCollection();
113549         var currentDirectory = host.getCurrentDirectory();
113550         var supportedExtensions = ts.getSupportedExtensions(options);
113551         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
113552         // Map storing if there is emit blocking diagnostics for given input
113553         var hasEmitBlockingDiagnostics = new ts.Map();
113554         var _compilerOptionsObjectLiteralSyntax;
113555         var moduleResolutionCache;
113556         var typeReferenceDirectiveResolutionCache;
113557         var actualResolveModuleNamesWorker;
113558         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
113559         if (host.resolveModuleNames) {
113560             actualResolveModuleNamesWorker = function (moduleNames, containingFile, containingFileName, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFileName, reusedNames, redirectedReference, options, containingFile).map(function (resolved) {
113561                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
113562                 if (!resolved || resolved.extension !== undefined) {
113563                     return resolved;
113564                 }
113565                 var withExtension = ts.clone(resolved);
113566                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
113567                 return withExtension;
113568             }); };
113569             moduleResolutionCache = (_a = host.getModuleResolutionCache) === null || _a === void 0 ? void 0 : _a.call(host);
113570         }
113571         else {
113572             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options);
113573             var loader_1 = function (moduleName, resolverMode, containingFileName, redirectedReference) { return ts.resolveModuleName(moduleName, containingFileName, options, host, moduleResolutionCache, redirectedReference, resolverMode).resolvedModule; }; // TODO: GH#18217
113574             actualResolveModuleNamesWorker = function (moduleNames, containingFile, containingFileName, _reusedNames, redirectedReference) { return loadWithModeAwareCache(ts.Debug.checkEachDefined(moduleNames), containingFile, containingFileName, redirectedReference, loader_1); };
113575         }
113576         var actualResolveTypeReferenceDirectiveNamesWorker;
113577         if (host.resolveTypeReferenceDirectives) {
113578             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
113579         }
113580         else {
113581             typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache());
113582             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217
113583             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
113584         }
113585         // Map from a stringified PackageId to the source file with that id.
113586         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
113587         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
113588         var packageIdToSourceFile = new ts.Map();
113589         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
113590         var sourceFileToPackageName = new ts.Map();
113591         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
113592         var redirectTargetsMap = ts.createMultiMap();
113593         var usesUriStyleNodeCoreModules = false;
113594         /**
113595          * map with
113596          * - SourceFile if present
113597          * - false if sourceFile missing for source of project reference redirect
113598          * - undefined otherwise
113599          */
113600         var filesByName = new ts.Map();
113601         var missingFilePaths;
113602         // stores 'filename -> file association' ignoring case
113603         // used to track cases when two file names differ only in casing
113604         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? new ts.Map() : undefined;
113605         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
113606         var resolvedProjectReferences;
113607         var projectReferenceRedirects;
113608         var mapFromFileToProjectReferenceRedirects;
113609         var mapFromToProjectReferenceRedirectSource;
113610         var useSourceOfProjectReferenceRedirect = !!((_b = host.useSourceOfProjectReferenceRedirect) === null || _b === void 0 ? void 0 : _b.call(host)) &&
113611             !options.disableSourceOfProjectReferenceRedirect;
113612         var _e = updateHostForUseSourceOfProjectReferenceRedirect({
113613             compilerHost: host,
113614             getSymlinkCache: getSymlinkCache,
113615             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
113616             toPath: toPath,
113617             getResolvedProjectReferences: getResolvedProjectReferences,
113618             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
113619             forEachResolvedProjectReference: forEachResolvedProjectReference
113620         }), onProgramCreateComplete = _e.onProgramCreateComplete, fileExists = _e.fileExists, directoryExists = _e.directoryExists;
113621         var readFile = host.readFile.bind(host);
113622         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
113623         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
113624         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113625         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
113626         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
113627         var structureIsReused;
113628         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
113629         structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
113630         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113631         if (structureIsReused !== 2 /* Completely */) {
113632             processingDefaultLibFiles = [];
113633             processingOtherFiles = [];
113634             if (projectReferences) {
113635                 if (!resolvedProjectReferences) {
113636                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
113637                 }
113638                 if (rootNames.length) {
113639                     resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences.forEach(function (parsedRef, index) {
113640                         if (!parsedRef)
113641                             return;
113642                         var out = ts.outFile(parsedRef.commandLine.options);
113643                         if (useSourceOfProjectReferenceRedirect) {
113644                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
113645                                 for (var _i = 0, _a = parsedRef.commandLine.fileNames; _i < _a.length; _i++) {
113646                                     var fileName = _a[_i];
113647                                     processProjectReferenceFile(fileName, { kind: ts.FileIncludeKind.SourceFromProjectReference, index: index });
113648                                 }
113649                             }
113650                         }
113651                         else {
113652                             if (out) {
113653                                 processProjectReferenceFile(ts.changeExtension(out, ".d.ts"), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
113654                             }
113655                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
113656                                 var getCommonSourceDirectory_2 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames()); });
113657                                 for (var _b = 0, _c = parsedRef.commandLine.fileNames; _b < _c.length; _b++) {
113658                                     var fileName = _c[_b];
113659                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
113660                                         processProjectReferenceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_2), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
113661                                     }
113662                                 }
113663                             }
113664                         }
113665                     });
113666                 }
113667             }
113668             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
113669             ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); });
113670             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113671             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
113672             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
113673             if (typeReferences.length) {
113674                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
113675                 // This containingFilename needs to match with the one used in managed-side
113676                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
113677                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
113678                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
113679                 for (var i = 0; i < typeReferences.length; i++) {
113680                     processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_c = resolutions[i]) === null || _c === void 0 ? void 0 : _c.packageId });
113681                 }
113682                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113683             }
113684             // Do not process the default library if:
113685             //  - The '--noLib' flag is used.
113686             //  - A 'no-default-lib' reference comment is encountered in
113687             //      processing the root files.
113688             if (rootNames.length && !skipDefaultLib) {
113689                 // If '--lib' is not specified, include default library file according to '--target'
113690                 // otherwise, using options specified in '--lib' instead of '--target' default library file
113691                 var defaultLibraryFileName = getDefaultLibraryFileName();
113692                 if (!options.lib && defaultLibraryFileName) {
113693                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile });
113694                 }
113695                 else {
113696                     ts.forEach(options.lib, function (libFileName, index) {
113697                         processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile, index: index });
113698                     });
113699                 }
113700             }
113701             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
113702                 var path = _a[0], file = _a[1];
113703                 return file === undefined ? path : undefined;
113704             }));
113705             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
113706             processingDefaultLibFiles = undefined;
113707             processingOtherFiles = undefined;
113708         }
113709         ts.Debug.assert(!!missingFilePaths);
113710         // Release any files we have acquired in the old program but are
113711         // not part of the new program.
113712         if (oldProgram && host.onReleaseOldSourceFile) {
113713             var oldSourceFiles = oldProgram.getSourceFiles();
113714             for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
113715                 var oldSourceFile = oldSourceFiles_1[_i];
113716                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
113717                 if (shouldCreateNewSourceFile || !newFile ||
113718                     // old file wasn't redirect but new file is
113719                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
113720                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
113721                 }
113722             }
113723             if (!host.getParsedCommandLine) {
113724                 oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) {
113725                     if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
113726                         host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
113727                     }
113728                 });
113729             }
113730         }
113731         // Release commandlines that new program does not use
113732         if (oldProgram && host.onReleaseParsedCommandLine) {
113733             forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) {
113734                 var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index];
113735                 var oldRefPath = resolveProjectReferencePath(oldReference);
113736                 if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) {
113737                     host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions());
113738                 }
113739             });
113740         }
113741         typeReferenceDirectiveResolutionCache = undefined;
113742         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
113743         oldProgram = undefined;
113744         var program = {
113745             getRootFileNames: function () { return rootNames; },
113746             getSourceFile: getSourceFile,
113747             getSourceFileByPath: getSourceFileByPath,
113748             getSourceFiles: function () { return files; },
113749             getMissingFilePaths: function () { return missingFilePaths; },
113750             getModuleResolutionCache: function () { return moduleResolutionCache; },
113751             getFilesByNameMap: function () { return filesByName; },
113752             getCompilerOptions: function () { return options; },
113753             getSyntacticDiagnostics: getSyntacticDiagnostics,
113754             getOptionsDiagnostics: getOptionsDiagnostics,
113755             getGlobalDiagnostics: getGlobalDiagnostics,
113756             getSemanticDiagnostics: getSemanticDiagnostics,
113757             getCachedSemanticDiagnostics: getCachedSemanticDiagnostics,
113758             getSuggestionDiagnostics: getSuggestionDiagnostics,
113759             getDeclarationDiagnostics: getDeclarationDiagnostics,
113760             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
113761             getProgramDiagnostics: getProgramDiagnostics,
113762             getTypeChecker: getTypeChecker,
113763             getClassifiableNames: getClassifiableNames,
113764             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
113765             getCommonSourceDirectory: getCommonSourceDirectory,
113766             emit: emit,
113767             getCurrentDirectory: function () { return currentDirectory; },
113768             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
113769             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
113770             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
113771             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
113772             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
113773             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
113774             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
113775             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
113776             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
113777             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
113778             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
113779             getSourceFileFromReference: getSourceFileFromReference,
113780             getLibFileFromReference: getLibFileFromReference,
113781             sourceFileToPackageName: sourceFileToPackageName,
113782             redirectTargetsMap: redirectTargetsMap,
113783             usesUriStyleNodeCoreModules: usesUriStyleNodeCoreModules,
113784             isEmittedFile: isEmittedFile,
113785             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
113786             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
113787             getProjectReferences: getProjectReferences,
113788             getResolvedProjectReferences: getResolvedProjectReferences,
113789             getProjectReferenceRedirect: getProjectReferenceRedirect,
113790             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
113791             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
113792             forEachResolvedProjectReference: forEachResolvedProjectReference,
113793             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
113794             emitBuildInfo: emitBuildInfo,
113795             fileExists: fileExists,
113796             readFile: readFile,
113797             directoryExists: directoryExists,
113798             getSymlinkCache: getSymlinkCache,
113799             realpath: (_d = host.realpath) === null || _d === void 0 ? void 0 : _d.bind(host),
113800             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
113801             getFileIncludeReasons: function () { return fileReasons; },
113802             structureIsReused: structureIsReused,
113803         };
113804         onProgramCreateComplete();
113805         // Add file processingDiagnostics
113806         fileProcessingDiagnostics === null || fileProcessingDiagnostics === void 0 ? void 0 : fileProcessingDiagnostics.forEach(function (diagnostic) {
113807             switch (diagnostic.kind) {
113808                 case 1 /* FilePreprocessingFileExplainingDiagnostic */:
113809                     return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || ts.emptyArray));
113810                 case 0 /* FilePreprocessingReferencedDiagnostic */:
113811                     var _a = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason), file = _a.file, pos = _a.pos, end = _a.end;
113812                     return programDiagnostics.add(ts.createFileDiagnostic.apply(void 0, __spreadArray([file, ts.Debug.checkDefined(pos), ts.Debug.checkDefined(end) - pos, diagnostic.diagnostic], diagnostic.args || ts.emptyArray, false)));
113813                 default:
113814                     ts.Debug.assertNever(diagnostic);
113815             }
113816         });
113817         verifyCompilerOptions();
113818         ts.performance.mark("afterProgram");
113819         ts.performance.measure("Program", "beforeProgram", "afterProgram");
113820         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113821         return program;
113822         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
113823             if (!moduleNames.length)
113824                 return ts.emptyArray;
113825             var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
113826             var redirectedReference = getRedirectReferenceForResolution(containingFile);
113827             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
113828             ts.performance.mark("beforeResolveModule");
113829             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, containingFileName, reusedNames, redirectedReference);
113830             ts.performance.mark("afterResolveModule");
113831             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
113832             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113833             return result;
113834         }
113835         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) {
113836             if (!typeDirectiveNames.length)
113837                 return [];
113838             var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
113839             var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
113840             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
113841             ts.performance.mark("beforeResolveTypeReference");
113842             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
113843             ts.performance.mark("afterResolveTypeReference");
113844             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
113845             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
113846             return result;
113847         }
113848         function getRedirectReferenceForResolution(file) {
113849             var redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
113850             if (redirect || !ts.fileExtensionIsOneOf(file.originalFileName, [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */]))
113851                 return redirect;
113852             // The originalFileName could not be actual source file name if file found was d.ts from referecned project
113853             // 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
113854             var resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path);
113855             if (resultFromDts)
113856                 return resultFromDts;
113857             // If preserveSymlinks is true, module resolution wont jump the symlink
113858             // but the resolved real path may be the .d.ts from project reference
113859             // Note:: Currently we try the real path only if the
113860             // file is from node_modules to avoid having to run real path on all file paths
113861             if (!host.realpath || !options.preserveSymlinks || !ts.stringContains(file.originalFileName, ts.nodeModulesPathPart))
113862                 return undefined;
113863             var realDeclarationPath = toPath(host.realpath(file.originalFileName));
113864             return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath);
113865         }
113866         function getRedirectReferenceForResolutionFromSourceOfProject(filePath) {
113867             var source = getSourceOfProjectReferenceRedirect(filePath);
113868             if (ts.isString(source))
113869                 return getResolvedProjectReferenceToRedirect(source);
113870             if (!source)
113871                 return undefined;
113872             // Output of .d.ts file so return resolved ref that matches the out file name
113873             return forEachResolvedProjectReference(function (resolvedRef) {
113874                 var out = ts.outFile(resolvedRef.commandLine.options);
113875                 if (!out)
113876                     return undefined;
113877                 return toPath(out) === filePath ? resolvedRef : undefined;
113878             });
113879         }
113880         function compareDefaultLibFiles(a, b) {
113881             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
113882         }
113883         function getDefaultLibFilePriority(a) {
113884             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
113885                 var basename = ts.getBaseFileName(a.fileName);
113886                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
113887                     return 0;
113888                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
113889                 var index = ts.libs.indexOf(name);
113890                 if (index !== -1)
113891                     return index + 1;
113892             }
113893             return ts.libs.length + 2;
113894         }
113895         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile, mode) {
113896             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache, mode);
113897         }
113898         function toPath(fileName) {
113899             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
113900         }
113901         function getCommonSourceDirectory() {
113902             if (commonSourceDirectory === undefined) {
113903                 var emittedFiles_1 = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
113904                 commonSourceDirectory = ts.getCommonSourceDirectory(options, function () { return ts.mapDefined(emittedFiles_1, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); }, currentDirectory, getCanonicalFileName, function (commonSourceDirectory) { return checkSourceFilesBelongToPath(emittedFiles_1, commonSourceDirectory); });
113905             }
113906             return commonSourceDirectory;
113907         }
113908         function getClassifiableNames() {
113909             var _a;
113910             if (!classifiableNames) {
113911                 // Initialize a checker so that all our files are bound.
113912                 getTypeChecker();
113913                 classifiableNames = new ts.Set();
113914                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
113915                     var sourceFile = files_3[_i];
113916                     (_a = sourceFile.classifiableNames) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return classifiableNames.add(value); });
113917                 }
113918             }
113919             return classifiableNames;
113920         }
113921         function resolveModuleNamesReusingOldState(moduleNames, file) {
113922             if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
113923                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
113924                 // the best we can do is fallback to the default logic.
113925                 return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ undefined);
113926             }
113927             var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
113928             if (oldSourceFile !== file && file.resolvedModules) {
113929                 // `file` was created for the new program.
113930                 //
113931                 // We only set `file.resolvedModules` via work from the current function,
113932                 // so it is defined iff we already called the current function on `file`.
113933                 // That call happened no later than the creation of the `file` object,
113934                 // which per above occurred during the current program creation.
113935                 // Since we assume the filesystem does not change during program creation,
113936                 // it is safe to reuse resolutions from the earlier call.
113937                 var result_13 = [];
113938                 var i = 0;
113939                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
113940                     var moduleName = moduleNames_1[_i];
113941                     var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i));
113942                     i++;
113943                     result_13.push(resolvedModule);
113944                 }
113945                 return result_13;
113946             }
113947             // At this point, we know at least one of the following hold:
113948             // - file has local declarations for ambient modules
113949             // - old program state is available
113950             // With this information, we can infer some module resolutions without performing resolution.
113951             /** An ordered list of module names for which we cannot recover the resolution. */
113952             var unknownModuleNames;
113953             /**
113954              * The indexing of elements in this list matches that of `moduleNames`.
113955              *
113956              * Before combining results, result[i] is in one of the following states:
113957              * * undefined: needs to be recomputed,
113958              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
113959              * Needs to be reset to undefined before returning,
113960              * * ResolvedModuleFull instance: can be reused.
113961              */
113962             var result;
113963             var reusedNames;
113964             /** A transient placeholder used to mark predicted resolution in the result list. */
113965             var predictedToResolveToAmbientModuleMarker = {};
113966             for (var i = 0; i < moduleNames.length; i++) {
113967                 var moduleName = moduleNames[i];
113968                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
113969                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
113970                     var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName, getModeForResolutionAtIndex(oldSourceFile, i));
113971                     if (oldResolvedModule) {
113972                         if (ts.isTraceEnabled(options, host)) {
113973                             ts.trace(host, oldResolvedModule.packageId ?
113974                                 ts.Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 :
113975                                 ts.Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), oldResolvedModule.resolvedFileName, oldResolvedModule.packageId && ts.packageIdToString(oldResolvedModule.packageId));
113976                         }
113977                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
113978                         (reusedNames || (reusedNames = [])).push(moduleName);
113979                         continue;
113980                     }
113981                 }
113982                 // We know moduleName resolves to an ambient module provided that moduleName:
113983                 // - is in the list of ambient modules locally declared in the current source file.
113984                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
113985                 //   (so the same module declaration will land in the new program)
113986                 var resolvesToAmbientModuleInNonModifiedFile = false;
113987                 if (ts.contains(file.ambientModuleNames, moduleName)) {
113988                     resolvesToAmbientModuleInNonModifiedFile = true;
113989                     if (ts.isTraceEnabled(options, host)) {
113990                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
113991                     }
113992                 }
113993                 else {
113994                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, i);
113995                 }
113996                 if (resolvesToAmbientModuleInNonModifiedFile) {
113997                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
113998                 }
113999                 else {
114000                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
114001                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
114002                 }
114003             }
114004             var resolutions = unknownModuleNames && unknownModuleNames.length
114005                 ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames)
114006                 : ts.emptyArray;
114007             // Combine results of resolutions and predicted results
114008             if (!result) {
114009                 // There were no unresolved/ambient resolutions.
114010                 ts.Debug.assert(resolutions.length === moduleNames.length);
114011                 return resolutions;
114012             }
114013             var j = 0;
114014             for (var i = 0; i < result.length; i++) {
114015                 if (result[i]) {
114016                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
114017                     // If it is the former, we can leave it as is.
114018                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
114019                         result[i] = undefined; // TODO: GH#18217
114020                     }
114021                 }
114022                 else {
114023                     result[i] = resolutions[j];
114024                     j++;
114025                 }
114026             }
114027             ts.Debug.assert(j === resolutions.length);
114028             return result;
114029             // If we change our policy of rechecking failed lookups on each program create,
114030             // we should adjust the value returned here.
114031             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, index) {
114032                 if (index >= ts.length(oldSourceFile === null || oldSourceFile === void 0 ? void 0 : oldSourceFile.imports) + ts.length(oldSourceFile === null || oldSourceFile === void 0 ? void 0 : oldSourceFile.moduleAugmentations))
114033                     return false; // mode index out of bounds, don't reuse resolution
114034                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName, oldSourceFile && getModeForResolutionAtIndex(oldSourceFile, index));
114035                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
114036                 if (resolutionToFile && resolvedFile) {
114037                     // In the old program, we resolved to an ambient module that was in the same
114038                     //   place as we expected to find an actual module file.
114039                     // We actually need to return 'false' here even though this seems like a 'true' case
114040                     //   because the normal module resolution algorithm will find this anyway.
114041                     return false;
114042                 }
114043                 // at least one of declarations should come from non-modified source file
114044                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
114045                 if (!unmodifiedFile) {
114046                     return false;
114047                 }
114048                 if (ts.isTraceEnabled(options, host)) {
114049                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
114050                 }
114051                 return true;
114052             }
114053         }
114054         function canReuseProjectReferences() {
114055             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) {
114056                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
114057                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
114058                 if (oldResolvedRef) {
114059                     // Resolved project reference has gone missing or changed
114060                     return !newResolvedRef ||
114061                         newResolvedRef.sourceFile !== oldResolvedRef.sourceFile ||
114062                         !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames);
114063                 }
114064                 else {
114065                     // A previously-unresolved reference may be resolved now
114066                     return newResolvedRef !== undefined;
114067                 }
114068             }, function (oldProjectReferences, parent) {
114069                 // If array of references is changed, we cant resue old program
114070                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
114071                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
114072             });
114073         }
114074         function tryReuseStructureFromOldProgram() {
114075             var _a;
114076             if (!oldProgram) {
114077                 return 0 /* Not */;
114078             }
114079             // check properties that can affect structure of the program or module resolution strategy
114080             // if any of these properties has changed - structure cannot be reused
114081             var oldOptions = oldProgram.getCompilerOptions();
114082             if (ts.changesAffectModuleResolution(oldOptions, options)) {
114083                 return 0 /* Not */;
114084             }
114085             // there is an old program, check if we can reuse its structure
114086             var oldRootNames = oldProgram.getRootFileNames();
114087             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
114088                 return 0 /* Not */;
114089             }
114090             // Check if any referenced project tsconfig files are different
114091             if (!canReuseProjectReferences()) {
114092                 return 0 /* Not */;
114093             }
114094             if (projectReferences) {
114095                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
114096             }
114097             // check if program source files has changed in the way that can affect structure of the program
114098             var newSourceFiles = [];
114099             var modifiedSourceFiles = [];
114100             structureIsReused = 2 /* Completely */;
114101             // If the missing file paths are now present, it can change the progam structure,
114102             // and hence cant reuse the structure.
114103             // This is same as how we dont reuse the structure if one of the file from old program is now missing
114104             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
114105                 return 0 /* Not */;
114106             }
114107             var oldSourceFiles = oldProgram.getSourceFiles();
114108             var SeenPackageName;
114109             (function (SeenPackageName) {
114110                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
114111                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
114112             })(SeenPackageName || (SeenPackageName = {}));
114113             var seenPackageNames = new ts.Map();
114114             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
114115                 var oldSourceFile = oldSourceFiles_2[_i];
114116                 var newSourceFile = host.getSourceFileByPath
114117                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, ts.getEmitScriptTarget(options), /*onError*/ undefined, shouldCreateNewSourceFile)
114118                     : host.getSourceFile(oldSourceFile.fileName, ts.getEmitScriptTarget(options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
114119                 if (!newSourceFile) {
114120                     return 0 /* Not */;
114121                 }
114122                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
114123                 var fileChanged = void 0;
114124                 if (oldSourceFile.redirectInfo) {
114125                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
114126                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
114127                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
114128                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
114129                         return 0 /* Not */;
114130                     }
114131                     fileChanged = false;
114132                     newSourceFile = oldSourceFile; // Use the redirect.
114133                 }
114134                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
114135                     // If a redirected-to source file changes, the redirect may be broken.
114136                     if (newSourceFile !== oldSourceFile) {
114137                         return 0 /* Not */;
114138                     }
114139                     fileChanged = false;
114140                 }
114141                 else {
114142                     fileChanged = newSourceFile !== oldSourceFile;
114143                 }
114144                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
114145                 newSourceFile.path = oldSourceFile.path;
114146                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
114147                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
114148                 newSourceFile.fileName = oldSourceFile.fileName;
114149                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
114150                 if (packageName !== undefined) {
114151                     // If there are 2 different source files for the same package name and at least one of them changes,
114152                     // they might become redirects. So we must rebuild the program.
114153                     var prevKind = seenPackageNames.get(packageName);
114154                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
114155                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
114156                         return 0 /* Not */;
114157                     }
114158                     seenPackageNames.set(packageName, newKind);
114159                 }
114160                 if (fileChanged) {
114161                     // The `newSourceFile` object was created for the new program.
114162                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
114163                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
114164                         structureIsReused = 1 /* SafeModules */;
114165                     }
114166                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
114167                         // value of no-default-lib has changed
114168                         // this will affect if default library is injected into the list of files
114169                         structureIsReused = 1 /* SafeModules */;
114170                     }
114171                     // check tripleslash references
114172                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
114173                         // tripleslash references has changed
114174                         structureIsReused = 1 /* SafeModules */;
114175                     }
114176                     // check imports and module augmentations
114177                     collectExternalModuleReferences(newSourceFile);
114178                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
114179                         // imports has changed
114180                         structureIsReused = 1 /* SafeModules */;
114181                     }
114182                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
114183                         // moduleAugmentations has changed
114184                         structureIsReused = 1 /* SafeModules */;
114185                     }
114186                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
114187                         // dynamicImport has changed
114188                         structureIsReused = 1 /* SafeModules */;
114189                     }
114190                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
114191                         // 'types' references has changed
114192                         structureIsReused = 1 /* SafeModules */;
114193                     }
114194                     // tentatively approve the file
114195                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
114196                 }
114197                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
114198                     // 'module/types' references could have changed
114199                     structureIsReused = 1 /* SafeModules */;
114200                     // add file to the modified list so that we will resolve it later
114201                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
114202                 }
114203                 // if file has passed all checks it should be safe to reuse it
114204                 newSourceFiles.push(newSourceFile);
114205             }
114206             if (structureIsReused !== 2 /* Completely */) {
114207                 return structureIsReused;
114208             }
114209             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
114210             for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) {
114211                 var oldFile = oldSourceFiles_3[_b];
114212                 if (!ts.contains(modifiedFiles, oldFile)) {
114213                     for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) {
114214                         var moduleName = _d[_c];
114215                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
114216                     }
114217                 }
114218             }
114219             // try to verify results of module resolution
114220             for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) {
114221                 var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile;
114222                 var moduleNames = getModuleNames(newSourceFile);
114223                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
114224                 // ensure that module resolution results are still correct
114225                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, oldSourceFile, ts.moduleResolutionIsEqualTo);
114226                 if (resolutionsChanged) {
114227                     structureIsReused = 1 /* SafeModules */;
114228                     newSourceFile.resolvedModules = ts.zipToModeAwareCache(newSourceFile, moduleNames, resolutions);
114229                 }
114230                 else {
114231                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
114232                 }
114233                 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
114234                 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
114235                 var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
114236                 // ensure that types resolutions are still correct
114237                 var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo);
114238                 if (typeReferenceResolutionsChanged) {
114239                     structureIsReused = 1 /* SafeModules */;
114240                     newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions);
114241                 }
114242                 else {
114243                     newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
114244                 }
114245             }
114246             if (structureIsReused !== 2 /* Completely */) {
114247                 return structureIsReused;
114248             }
114249             if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) {
114250                 return 1 /* SafeModules */;
114251             }
114252             missingFilePaths = oldProgram.getMissingFilePaths();
114253             // update fileName -> file mapping
114254             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
114255             for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
114256                 var newSourceFile = newSourceFiles_1[_g];
114257                 filesByName.set(newSourceFile.path, newSourceFile);
114258             }
114259             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
114260             oldFilesByNameMap.forEach(function (oldFile, path) {
114261                 if (!oldFile) {
114262                     filesByName.set(path, oldFile);
114263                     return;
114264                 }
114265                 if (oldFile.path === path) {
114266                     // Set the file as found during node modules search if it was found that way in old progra,
114267                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
114268                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
114269                     }
114270                     return;
114271                 }
114272                 filesByName.set(path, filesByName.get(oldFile.path));
114273             });
114274             files = newSourceFiles;
114275             fileReasons = oldProgram.getFileIncludeReasons();
114276             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
114277             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
114278             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
114279             redirectTargetsMap = oldProgram.redirectTargetsMap;
114280             usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules;
114281             return 2 /* Completely */;
114282         }
114283         function getEmitHost(writeFileCallback) {
114284             return {
114285                 getPrependNodes: getPrependNodes,
114286                 getCanonicalFileName: getCanonicalFileName,
114287                 getCommonSourceDirectory: program.getCommonSourceDirectory,
114288                 getCompilerOptions: program.getCompilerOptions,
114289                 getCurrentDirectory: function () { return currentDirectory; },
114290                 getNewLine: function () { return host.getNewLine(); },
114291                 getSourceFile: program.getSourceFile,
114292                 getSourceFileByPath: program.getSourceFileByPath,
114293                 getSourceFiles: program.getSourceFiles,
114294                 getLibFileFromReference: program.getLibFileFromReference,
114295                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
114296                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
114297                 getProjectReferenceRedirect: getProjectReferenceRedirect,
114298                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
114299                 getSymlinkCache: getSymlinkCache,
114300                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
114301                 isEmitBlocked: isEmitBlocked,
114302                 readFile: function (f) { return host.readFile(f); },
114303                 fileExists: function (f) {
114304                     // Use local caches
114305                     var path = toPath(f);
114306                     if (getSourceFileByPath(path))
114307                         return true;
114308                     if (ts.contains(missingFilePaths, path))
114309                         return false;
114310                     // Before falling back to the host
114311                     return host.fileExists(f);
114312                 },
114313                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
114314                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
114315                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
114316                 redirectTargetsMap: redirectTargetsMap,
114317                 getFileIncludeReasons: program.getFileIncludeReasons,
114318             };
114319         }
114320         function emitBuildInfo(writeFileCallback) {
114321             ts.Debug.assert(!ts.outFile(options));
114322             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true);
114323             ts.performance.mark("beforeEmit");
114324             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
114325             /*targetSourceFile*/ undefined, 
114326             /*transformers*/ ts.noTransformers, 
114327             /*emitOnlyDtsFiles*/ false, 
114328             /*onlyBuildInfo*/ true);
114329             ts.performance.mark("afterEmit");
114330             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
114331             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
114332             return emitResult;
114333         }
114334         function getResolvedProjectReferences() {
114335             return resolvedProjectReferences;
114336         }
114337         function getProjectReferences() {
114338             return projectReferences;
114339         }
114340         function getPrependNodes() {
114341             return createPrependNodes(projectReferences, function (_ref, index) { var _a; return (_a = resolvedProjectReferences[index]) === null || _a === void 0 ? void 0 : _a.commandLine; }, function (fileName) {
114342                 var path = toPath(fileName);
114343                 var sourceFile = getSourceFileByPath(path);
114344                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
114345             });
114346         }
114347         function isSourceFileFromExternalLibrary(file) {
114348             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
114349         }
114350         function isSourceFileDefaultLibrary(file) {
114351             if (file.hasNoDefaultLib) {
114352                 return true;
114353             }
114354             if (!options.noLib) {
114355                 return false;
114356             }
114357             // If '--lib' is not specified, include default library file according to '--target'
114358             // otherwise, using options specified in '--lib' instead of '--target' default library file
114359             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
114360             if (!options.lib) {
114361                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
114362             }
114363             else {
114364                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, pathForLibFile(libFileName)); });
114365             }
114366         }
114367         function getDiagnosticsProducingTypeChecker() {
114368             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
114369         }
114370         function dropDiagnosticsProducingTypeChecker() {
114371             diagnosticsProducingTypeChecker = undefined;
114372         }
114373         function getTypeChecker() {
114374             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
114375         }
114376         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
114377             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true);
114378             var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
114379             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
114380             return result;
114381         }
114382         function isEmitBlocked(emitFileName) {
114383             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
114384         }
114385         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
114386             if (!forceDtsEmit) {
114387                 var result = handleNoEmitOptions(program, sourceFile, writeFileCallback, cancellationToken);
114388                 if (result)
114389                     return result;
114390             }
114391             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
114392             // any cost associated with it (like type checking) are appropriate associated with
114393             // the type-checking counter.
114394             //
114395             // If the -out option is specified, we should not pass the source file to getEmitResolver.
114396             // This is because in the -out scenario all files need to be emitted, and therefore all
114397             // files need to be type checked. And the way to specify that all files need to be type
114398             // checked is to not pass the file to getEmitResolver.
114399             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(ts.outFile(options) ? undefined : sourceFile, cancellationToken);
114400             ts.performance.mark("beforeEmit");
114401             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
114402             /*onlyBuildInfo*/ false, forceDtsEmit);
114403             ts.performance.mark("afterEmit");
114404             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
114405             return emitResult;
114406         }
114407         function getSourceFile(fileName) {
114408             return getSourceFileByPath(toPath(fileName));
114409         }
114410         function getSourceFileByPath(path) {
114411             return filesByName.get(path) || undefined;
114412         }
114413         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
114414             if (sourceFile) {
114415                 return getDiagnostics(sourceFile, cancellationToken);
114416             }
114417             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
114418                 if (cancellationToken) {
114419                     cancellationToken.throwIfCancellationRequested();
114420                 }
114421                 return getDiagnostics(sourceFile, cancellationToken);
114422             }));
114423         }
114424         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
114425             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
114426         }
114427         function getSemanticDiagnostics(sourceFile, cancellationToken) {
114428             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
114429         }
114430         function getCachedSemanticDiagnostics(sourceFile) {
114431             var _a;
114432             return sourceFile
114433                 ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
114434                 : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
114435         }
114436         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
114437             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
114438         }
114439         function getProgramDiagnostics(sourceFile) {
114440             var _a;
114441             if (ts.skipTypeChecking(sourceFile, options, program)) {
114442                 return ts.emptyArray;
114443             }
114444             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
114445             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
114446                 return programDiagnosticsInFile;
114447             }
114448             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics;
114449         }
114450         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
114451             var options = program.getCompilerOptions();
114452             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
114453             if (!sourceFile || ts.outFile(options)) {
114454                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
114455             }
114456             else {
114457                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
114458             }
114459         }
114460         function getSyntacticDiagnosticsForFile(sourceFile) {
114461             // For JavaScript files, we report semantic errors for using TypeScript-only
114462             // constructs from within a JavaScript file as syntactic errors.
114463             if (ts.isSourceFileJS(sourceFile)) {
114464                 if (!sourceFile.additionalSyntacticDiagnostics) {
114465                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
114466                 }
114467                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
114468             }
114469             return sourceFile.parseDiagnostics;
114470         }
114471         function runWithCancellationToken(func) {
114472             try {
114473                 return func();
114474             }
114475             catch (e) {
114476                 if (e instanceof ts.OperationCanceledException) {
114477                     // We were canceled while performing the operation.  Because our type checker
114478                     // might be a bad state, we need to throw it away.
114479                     //
114480                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
114481                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
114482                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
114483                     // cancel when the user has made a change anyways.  And, in that case, we (the
114484                     // program instance) will get thrown away anyways.  So trying to keep one of
114485                     // these type checkers alive doesn't serve much purpose.
114486                     noDiagnosticsTypeChecker = undefined;
114487                     diagnosticsProducingTypeChecker = undefined;
114488                 }
114489                 throw e;
114490             }
114491         }
114492         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
114493             return ts.concatenate(filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile));
114494         }
114495         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
114496             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
114497         }
114498         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
114499             return runWithCancellationToken(function () {
114500                 if (ts.skipTypeChecking(sourceFile, options, program)) {
114501                     return ts.emptyArray;
114502                 }
114503                 var typeChecker = getDiagnosticsProducingTypeChecker();
114504                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
114505                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
114506                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
114507                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
114508                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */
114509                     || sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
114510                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
114511                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
114512                 return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
114513             });
114514         }
114515         function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) {
114516             var _a;
114517             var allDiagnostics = [];
114518             for (var _i = 2; _i < arguments.length; _i++) {
114519                 allDiagnostics[_i - 2] = arguments[_i];
114520             }
114521             var flatDiagnostics = ts.flatten(allDiagnostics);
114522             if (!includeBindAndCheckDiagnostics || !((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
114523                 return flatDiagnostics;
114524             }
114525             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
114526             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
114527                 var errorExpectation = _d[_c];
114528                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
114529             }
114530             return diagnostics;
114531         }
114532         /**
114533          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
114534          * Comments that match to any of those diagnostics are marked as used.
114535          */
114536         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
114537             // Diagnostics are only reported if there is no comment directive preceding them
114538             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
114539             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
114540             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
114541             return { diagnostics: diagnostics, directives: directives };
114542         }
114543         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
114544             return runWithCancellationToken(function () {
114545                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
114546             });
114547         }
114548         /**
114549          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
114550          */
114551         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
114552             var file = diagnostic.file, start = diagnostic.start;
114553             if (!file) {
114554                 return -1;
114555             }
114556             // Start out with the line just before the text
114557             var lineStarts = ts.getLineStarts(file);
114558             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
114559             while (line >= 0) {
114560                 // As soon as that line is known to have a comment directive, use that
114561                 if (directives.markUsed(line)) {
114562                     return line;
114563                 }
114564                 // Stop searching if the line is not empty and not a comment
114565                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
114566                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
114567                     return -1;
114568                 }
114569                 line--;
114570             }
114571             return -1;
114572         }
114573         function getJSSyntacticDiagnosticsForFile(sourceFile) {
114574             return runWithCancellationToken(function () {
114575                 var diagnostics = [];
114576                 walk(sourceFile, sourceFile);
114577                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
114578                 return diagnostics;
114579                 function walk(node, parent) {
114580                     // Return directly from the case if the given node doesnt want to visit each child
114581                     // Otherwise break to visit each child
114582                     switch (parent.kind) {
114583                         case 163 /* Parameter */:
114584                         case 166 /* PropertyDeclaration */:
114585                         case 168 /* MethodDeclaration */:
114586                             if (parent.questionToken === node) {
114587                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
114588                                 return "skip";
114589                             }
114590                         // falls through
114591                         case 167 /* MethodSignature */:
114592                         case 170 /* Constructor */:
114593                         case 171 /* GetAccessor */:
114594                         case 172 /* SetAccessor */:
114595                         case 212 /* FunctionExpression */:
114596                         case 255 /* FunctionDeclaration */:
114597                         case 213 /* ArrowFunction */:
114598                         case 253 /* VariableDeclaration */:
114599                             // type annotation
114600                             if (parent.type === node) {
114601                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
114602                                 return "skip";
114603                             }
114604                     }
114605                     switch (node.kind) {
114606                         case 266 /* ImportClause */:
114607                             if (node.isTypeOnly) {
114608                                 diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
114609                                 return "skip";
114610                             }
114611                             break;
114612                         case 271 /* ExportDeclaration */:
114613                             if (node.isTypeOnly) {
114614                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
114615                                 return "skip";
114616                             }
114617                             break;
114618                         case 264 /* ImportEqualsDeclaration */:
114619                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
114620                             return "skip";
114621                         case 270 /* ExportAssignment */:
114622                             if (node.isExportEquals) {
114623                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
114624                                 return "skip";
114625                             }
114626                             break;
114627                         case 290 /* HeritageClause */:
114628                             var heritageClause = node;
114629                             if (heritageClause.token === 117 /* ImplementsKeyword */) {
114630                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
114631                                 return "skip";
114632                             }
114633                             break;
114634                         case 257 /* InterfaceDeclaration */:
114635                             var interfaceKeyword = ts.tokenToString(118 /* InterfaceKeyword */);
114636                             ts.Debug.assertIsDefined(interfaceKeyword);
114637                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
114638                             return "skip";
114639                         case 260 /* ModuleDeclaration */:
114640                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(142 /* NamespaceKeyword */) : ts.tokenToString(141 /* ModuleKeyword */);
114641                             ts.Debug.assertIsDefined(moduleKeyword);
114642                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
114643                             return "skip";
114644                         case 258 /* TypeAliasDeclaration */:
114645                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
114646                             return "skip";
114647                         case 259 /* EnumDeclaration */:
114648                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(92 /* EnumKeyword */));
114649                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
114650                             return "skip";
114651                         case 229 /* NonNullExpression */:
114652                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
114653                             return "skip";
114654                         case 228 /* AsExpression */:
114655                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
114656                             return "skip";
114657                         case 210 /* TypeAssertionExpression */:
114658                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
114659                     }
114660                 }
114661                 function walkArray(nodes, parent) {
114662                     if (parent.decorators === nodes && !options.experimentalDecorators) {
114663                         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));
114664                     }
114665                     switch (parent.kind) {
114666                         case 256 /* ClassDeclaration */:
114667                         case 225 /* ClassExpression */:
114668                         case 168 /* MethodDeclaration */:
114669                         case 170 /* Constructor */:
114670                         case 171 /* GetAccessor */:
114671                         case 172 /* SetAccessor */:
114672                         case 212 /* FunctionExpression */:
114673                         case 255 /* FunctionDeclaration */:
114674                         case 213 /* ArrowFunction */:
114675                             // Check type parameters
114676                             if (nodes === parent.typeParameters) {
114677                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
114678                                 return "skip";
114679                             }
114680                         // falls through
114681                         case 236 /* VariableStatement */:
114682                             // Check modifiers
114683                             if (nodes === parent.modifiers) {
114684                                 checkModifiers(parent.modifiers, parent.kind === 236 /* VariableStatement */);
114685                                 return "skip";
114686                             }
114687                             break;
114688                         case 166 /* PropertyDeclaration */:
114689                             // Check modifiers of property declaration
114690                             if (nodes === parent.modifiers) {
114691                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
114692                                     var modifier = _a[_i];
114693                                     if (modifier.kind !== 124 /* StaticKeyword */) {
114694                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
114695                                     }
114696                                 }
114697                                 return "skip";
114698                             }
114699                             break;
114700                         case 163 /* Parameter */:
114701                             // Check modifiers of parameter declaration
114702                             if (nodes === parent.modifiers) {
114703                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
114704                                 return "skip";
114705                             }
114706                             break;
114707                         case 207 /* CallExpression */:
114708                         case 208 /* NewExpression */:
114709                         case 227 /* ExpressionWithTypeArguments */:
114710                         case 278 /* JsxSelfClosingElement */:
114711                         case 279 /* JsxOpeningElement */:
114712                         case 209 /* TaggedTemplateExpression */:
114713                             // Check type arguments
114714                             if (nodes === parent.typeArguments) {
114715                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
114716                                 return "skip";
114717                             }
114718                             break;
114719                     }
114720                 }
114721                 function checkModifiers(modifiers, isConstValid) {
114722                     for (var _i = 0, modifiers_2 = modifiers; _i < modifiers_2.length; _i++) {
114723                         var modifier = modifiers_2[_i];
114724                         switch (modifier.kind) {
114725                             case 85 /* ConstKeyword */:
114726                                 if (isConstValid) {
114727                                     continue;
114728                                 }
114729                             // to report error,
114730                             // falls through
114731                             case 123 /* PublicKeyword */:
114732                             case 121 /* PrivateKeyword */:
114733                             case 122 /* ProtectedKeyword */:
114734                             case 144 /* ReadonlyKeyword */:
114735                             case 135 /* DeclareKeyword */:
114736                             case 126 /* AbstractKeyword */:
114737                             case 158 /* OverrideKeyword */:
114738                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
114739                                 break;
114740                             // These are all legal modifiers.
114741                             case 124 /* StaticKeyword */:
114742                             case 93 /* ExportKeyword */:
114743                             case 88 /* DefaultKeyword */:
114744                         }
114745                     }
114746                 }
114747                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
114748                     var start = nodes.pos;
114749                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
114750                 }
114751                 // Since these are syntactic diagnostics, parent might not have been set
114752                 // this means the sourceFile cannot be infered from the node
114753                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
114754                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
114755                 }
114756             });
114757         }
114758         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
114759             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
114760         }
114761         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
114762             return runWithCancellationToken(function () {
114763                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
114764                 // Don't actually write any files since we're just getting diagnostics.
114765                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
114766             });
114767         }
114768         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
114769             var _a;
114770             var cachedResult = sourceFile
114771                 ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
114772                 : cache.allDiagnostics;
114773             if (cachedResult) {
114774                 return cachedResult;
114775             }
114776             var result = getDiagnostics(sourceFile, cancellationToken);
114777             if (sourceFile) {
114778                 (cache.perFile || (cache.perFile = new ts.Map())).set(sourceFile.path, result);
114779             }
114780             else {
114781                 cache.allDiagnostics = result;
114782             }
114783             return result;
114784         }
114785         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
114786             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
114787         }
114788         function getOptionsDiagnostics() {
114789             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()));
114790         }
114791         function getOptionsDiagnosticsOfConfigFile() {
114792             if (!options.configFile)
114793                 return ts.emptyArray;
114794             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
114795             forEachResolvedProjectReference(function (resolvedRef) {
114796                 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
114797             });
114798             return diagnostics;
114799         }
114800         function getGlobalDiagnostics() {
114801             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
114802         }
114803         function getConfigFileParsingDiagnostics() {
114804             return configFileParsingDiagnostics || ts.emptyArray;
114805         }
114806         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) {
114807             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined, reason);
114808         }
114809         function fileReferenceIsEqualTo(a, b) {
114810             return a.fileName === b.fileName;
114811         }
114812         function moduleNameIsEqualTo(a, b) {
114813             return a.kind === 79 /* Identifier */
114814                 ? b.kind === 79 /* Identifier */ && a.escapedText === b.escapedText
114815                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
114816         }
114817         function createSyntheticImport(text, file) {
114818             var externalHelpersModuleReference = ts.factory.createStringLiteral(text);
114819             var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined);
114820             ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
114821             ts.setParent(externalHelpersModuleReference, importDecl);
114822             ts.setParent(importDecl, file);
114823             // explicitly unset the synthesized flag on these declarations so the checker API will answer questions about them
114824             // (which is required to build the dependency graph for incremental emit)
114825             externalHelpersModuleReference.flags &= ~8 /* Synthesized */;
114826             importDecl.flags &= ~8 /* Synthesized */;
114827             return externalHelpersModuleReference;
114828         }
114829         function collectExternalModuleReferences(file) {
114830             if (file.imports) {
114831                 return;
114832             }
114833             var isJavaScriptFile = ts.isSourceFileJS(file);
114834             var isExternalModuleFile = ts.isExternalModule(file);
114835             // file.imports may not be undefined if there exists dynamic import
114836             var imports;
114837             var moduleAugmentations;
114838             var ambientModules;
114839             // If we are importing helpers, we need to add a synthetic reference to resolve the
114840             // helpers library.
114841             if ((options.isolatedModules || isExternalModuleFile)
114842                 && !file.isDeclarationFile) {
114843                 if (options.importHelpers) {
114844                     // synthesize 'import "tslib"' declaration
114845                     imports = [createSyntheticImport(ts.externalHelpersModuleNameText, file)];
114846                 }
114847                 var jsxImport = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(options, file), options);
114848                 if (jsxImport) {
114849                     // synthesize `import "base/jsx-runtime"` declaration
114850                     (imports || (imports = [])).push(createSyntheticImport(jsxImport, file));
114851                 }
114852             }
114853             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
114854                 var node = _a[_i];
114855                 collectModuleReferences(node, /*inAmbientModule*/ false);
114856             }
114857             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
114858                 collectDynamicImportOrRequireCalls(file);
114859             }
114860             file.imports = imports || ts.emptyArray;
114861             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
114862             file.ambientModuleNames = ambientModules || ts.emptyArray;
114863             return;
114864             function collectModuleReferences(node, inAmbientModule) {
114865                 if (ts.isAnyImportOrReExport(node)) {
114866                     var moduleNameExpr = ts.getExternalModuleName(node);
114867                     // TypeScript 1.0 spec (April 2014): 12.1.6
114868                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
114869                     // only through top - level external module names. Relative external module names are not permitted.
114870                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
114871                         ts.setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
114872                         imports = ts.append(imports, moduleNameExpr);
114873                         if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) {
114874                             usesUriStyleNodeCoreModules = ts.startsWith(moduleNameExpr.text, "node:");
114875                         }
114876                     }
114877                 }
114878                 else if (ts.isModuleDeclaration(node)) {
114879                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
114880                         node.name.parent = node;
114881                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
114882                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
114883                         // This will happen in two cases:
114884                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
114885                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
114886                         //   immediately nested in top level ambient module declaration .
114887                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
114888                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
114889                         }
114890                         else if (!inAmbientModule) {
114891                             if (file.isDeclarationFile) {
114892                                 // for global .d.ts files record name of ambient module
114893                                 (ambientModules || (ambientModules = [])).push(nameText);
114894                             }
114895                             // An AmbientExternalModuleDeclaration declares an external module.
114896                             // This type of declaration is permitted only in the global module.
114897                             // The StringLiteral must specify a top - level external module name.
114898                             // Relative external module names are not permitted
114899                             // NOTE: body of ambient module is always a module block, if it exists
114900                             var body = node.body;
114901                             if (body) {
114902                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
114903                                     var statement = _a[_i];
114904                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
114905                                 }
114906                             }
114907                         }
114908                     }
114909                 }
114910             }
114911             function collectDynamicImportOrRequireCalls(file) {
114912                 var r = /import|require/g;
114913                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
114914                     var node = getNodeAtPosition(file, r.lastIndex);
114915                     if (isJavaScriptFile && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
114916                         ts.setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
114917                         imports = ts.append(imports, node.arguments[0]);
114918                     }
114919                     // we have to check the argument list has length of at least 1. We will still have to process these even though we have parsing error.
114920                     else if (ts.isImportCall(node) && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
114921                         ts.setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
114922                         imports = ts.append(imports, node.arguments[0]);
114923                     }
114924                     else if (ts.isLiteralImportTypeNode(node)) {
114925                         ts.setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
114926                         imports = ts.append(imports, node.argument.literal);
114927                     }
114928                 }
114929             }
114930             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
114931             function getNodeAtPosition(sourceFile, position) {
114932                 var current = sourceFile;
114933                 var getContainingChild = function (child) {
114934                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
114935                         return child;
114936                     }
114937                 };
114938                 while (true) {
114939                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
114940                     if (!child) {
114941                         return current;
114942                     }
114943                     current = child;
114944                 }
114945             }
114946         }
114947         function getLibFileFromReference(ref) {
114948             var libName = ts.toFileNameLowerCase(ref.fileName);
114949             var libFileName = ts.libMap.get(libName);
114950             if (libFileName) {
114951                 return getSourceFile(pathForLibFile(libFileName));
114952             }
114953         }
114954         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
114955         function getSourceFileFromReference(referencingFile, ref) {
114956             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile);
114957         }
114958         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, reason) {
114959             if (ts.hasExtension(fileName)) {
114960                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
114961                 if (!options.allowNonTsExtensions && !ts.forEach(ts.flatten(supportedExtensionsWithJsonIfResolveJsonModule), function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
114962                     if (fail) {
114963                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
114964                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
114965                         }
114966                         else {
114967                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + ts.flatten(supportedExtensions).join("', '") + "'");
114968                         }
114969                     }
114970                     return undefined;
114971                 }
114972                 var sourceFile = getSourceFile(fileName);
114973                 if (fail) {
114974                     if (!sourceFile) {
114975                         var redirect = getProjectReferenceRedirect(fileName);
114976                         if (redirect) {
114977                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
114978                         }
114979                         else {
114980                             fail(ts.Diagnostics.File_0_not_found, fileName);
114981                         }
114982                     }
114983                     else if (isReferencedFile(reason) && canonicalFileName_1 === host.getCanonicalFileName(getSourceFileByPath(reason.file).fileName)) {
114984                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
114985                     }
114986                 }
114987                 return sourceFile;
114988             }
114989             else {
114990                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
114991                 if (sourceFileNoExtension)
114992                     return sourceFileNoExtension;
114993                 if (fail && options.allowNonTsExtensions) {
114994                     fail(ts.Diagnostics.File_0_not_found, fileName);
114995                     return undefined;
114996                 }
114997                 // Only try adding extensions from the first supported group (which should be .ts/.tsx/.d.ts)
114998                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions[0], function (extension) { return getSourceFile(fileName + extension); });
114999                 if (fail && !sourceFileWithAddedExtension)
115000                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + ts.flatten(supportedExtensions).join("', '") + "'");
115001                 return sourceFileWithAddedExtension;
115002             }
115003         }
115004         /** This has side effects through `findSourceFile`. */
115005         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) {
115006             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId); }, // TODO: GH#18217
115007             function (diagnostic) {
115008                 var args = [];
115009                 for (var _i = 1; _i < arguments.length; _i++) {
115010                     args[_i - 1] = arguments[_i];
115011                 }
115012                 return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, diagnostic, args);
115013             }, reason);
115014         }
115015         function processProjectReferenceFile(fileName, reason) {
115016             return processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, reason);
115017         }
115018         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) {
115019             var hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && ts.some(fileReasons.get(existingFile.path), isReferencedFile);
115020             if (hasExistingReasonToReportErrorOn) {
115021                 addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, [existingFile.fileName, fileName]);
115022             }
115023             else {
115024                 addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]);
115025             }
115026         }
115027         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
115028             var redirect = Object.create(redirectTarget);
115029             redirect.fileName = fileName;
115030             redirect.path = path;
115031             redirect.resolvedPath = resolvedPath;
115032             redirect.originalFileName = originalFileName;
115033             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
115034             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
115035             Object.defineProperties(redirect, {
115036                 id: {
115037                     get: function () { return this.redirectInfo.redirectTarget.id; },
115038                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
115039                 },
115040                 symbol: {
115041                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
115042                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
115043                 },
115044             });
115045             return redirect;
115046         }
115047         // Get source file from normalized fileName
115048         function findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
115049             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", {
115050                 fileName: fileName,
115051                 isDefaultLib: isDefaultLib || undefined,
115052                 fileIncludeKind: ts.FileIncludeKind[reason.kind],
115053             });
115054             var result = findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId);
115055             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
115056             return result;
115057         }
115058         function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
115059             var path = toPath(fileName);
115060             if (useSourceOfProjectReferenceRedirect) {
115061                 var source = getSourceOfProjectReferenceRedirect(path);
115062                 // If preserveSymlinks is true, module resolution wont jump the symlink
115063                 // but the resolved real path may be the .d.ts from project reference
115064                 // Note:: Currently we try the real path only if the
115065                 // file is from node_modules to avoid having to run real path on all file paths
115066                 if (!source &&
115067                     host.realpath &&
115068                     options.preserveSymlinks &&
115069                     ts.isDeclarationFileName(fileName) &&
115070                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
115071                     var realPath = toPath(host.realpath(fileName));
115072                     if (realPath !== path)
115073                         source = getSourceOfProjectReferenceRedirect(realPath);
115074                 }
115075                 if (source) {
115076                     var file_1 = ts.isString(source) ?
115077                         findSourceFile(source, isDefaultLib, ignoreNoDefaultLib, reason, packageId) :
115078                         undefined;
115079                     if (file_1)
115080                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
115081                     return file_1;
115082                 }
115083             }
115084             var originalFileName = fileName;
115085             if (filesByName.has(path)) {
115086                 var file_2 = filesByName.get(path);
115087                 addFileIncludeReason(file_2 || undefined, reason);
115088                 // try to check if we've already seen this file but with a different casing in path
115089                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
115090                 if (file_2 && options.forceConsistentCasingInFileNames) {
115091                     var checkedName = file_2.fileName;
115092                     var isRedirect = toPath(checkedName) !== toPath(fileName);
115093                     if (isRedirect) {
115094                         fileName = getProjectReferenceRedirect(fileName) || fileName;
115095                     }
115096                     // Check if it differs only in drive letters its ok to ignore that error:
115097                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
115098                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
115099                     if (checkedAbsolutePath !== inputAbsolutePath) {
115100                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, reason);
115101                     }
115102                 }
115103                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
115104                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
115105                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
115106                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
115107                     if (!options.noResolve) {
115108                         processReferencedFiles(file_2, isDefaultLib);
115109                         processTypeReferenceDirectives(file_2);
115110                     }
115111                     if (!options.noLib) {
115112                         processLibReferenceDirectives(file_2);
115113                     }
115114                     modulesWithElidedImports.set(file_2.path, false);
115115                     processImportedModules(file_2);
115116                 }
115117                 // See if we need to reprocess the imports due to prior skipped imports
115118                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
115119                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
115120                         modulesWithElidedImports.set(file_2.path, false);
115121                         processImportedModules(file_2);
115122                     }
115123                 }
115124                 return file_2 || undefined;
115125             }
115126             var redirectedPath;
115127             if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) {
115128                 var redirectProject = getProjectReferenceRedirectProject(fileName);
115129                 if (redirectProject) {
115130                     if (ts.outFile(redirectProject.commandLine.options)) {
115131                         // Shouldnt create many to 1 mapping file in --out scenario
115132                         return undefined;
115133                     }
115134                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
115135                     fileName = redirect;
115136                     // Once we start redirecting to a file, we can potentially come back to it
115137                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
115138                     // end up trying to add it to the program *again* because we were tracking it via its
115139                     // original (un-redirected) name. So we have to map both the original path and the redirected path
115140                     // to the source file we're about to find/create
115141                     redirectedPath = toPath(redirect);
115142                 }
115143             }
115144             // We haven't looked for this file, do so now and cache result
115145             var file = host.getSourceFile(fileName, ts.getEmitScriptTarget(options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile);
115146             if (packageId) {
115147                 var packageIdKey = ts.packageIdToString(packageId);
115148                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
115149                 if (fileFromPackageId) {
115150                     // Some other SourceFile already exists with this package name and version.
115151                     // Instead of creating a duplicate, just redirect to the existing one.
115152                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
115153                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
115154                     addFileToFilesByName(dupFile, path, redirectedPath);
115155                     addFileIncludeReason(dupFile, reason);
115156                     sourceFileToPackageName.set(path, packageId.name);
115157                     processingOtherFiles.push(dupFile);
115158                     return dupFile;
115159                 }
115160                 else if (file) {
115161                     // This is the first source file to have this packageId.
115162                     packageIdToSourceFile.set(packageIdKey, file);
115163                     sourceFileToPackageName.set(path, packageId.name);
115164                 }
115165             }
115166             addFileToFilesByName(file, path, redirectedPath);
115167             if (file) {
115168                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
115169                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
115170                 file.path = path;
115171                 file.resolvedPath = toPath(fileName);
115172                 file.originalFileName = originalFileName;
115173                 // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
115174                 // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
115175                 // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
115176                 file.impliedNodeFormat = getImpliedNodeFormatForFile(file.resolvedPath, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
115177                 addFileIncludeReason(file, reason);
115178                 if (host.useCaseSensitiveFileNames()) {
115179                     var pathLowerCase = ts.toFileNameLowerCase(path);
115180                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
115181                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
115182                     if (existingFile) {
115183                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason);
115184                     }
115185                     else {
115186                         filesByNameIgnoreCase.set(pathLowerCase, file);
115187                     }
115188                 }
115189                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
115190                 if (!options.noResolve) {
115191                     processReferencedFiles(file, isDefaultLib);
115192                     processTypeReferenceDirectives(file);
115193                 }
115194                 if (!options.noLib) {
115195                     processLibReferenceDirectives(file);
115196                 }
115197                 // always process imported modules to record module name resolutions
115198                 processImportedModules(file);
115199                 if (isDefaultLib) {
115200                     processingDefaultLibFiles.push(file);
115201                 }
115202                 else {
115203                     processingOtherFiles.push(file);
115204                 }
115205             }
115206             return file;
115207         }
115208         function addFileIncludeReason(file, reason) {
115209             if (file)
115210                 fileReasons.add(file.path, reason);
115211         }
115212         function addFileToFilesByName(file, path, redirectedPath) {
115213             if (redirectedPath) {
115214                 filesByName.set(redirectedPath, file);
115215                 filesByName.set(path, file || false);
115216             }
115217             else {
115218                 filesByName.set(path, file);
115219             }
115220         }
115221         function getProjectReferenceRedirect(fileName) {
115222             var referencedProject = getProjectReferenceRedirectProject(fileName);
115223             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
115224         }
115225         function getProjectReferenceRedirectProject(fileName) {
115226             // Ignore dts or any json files
115227             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
115228                 return undefined;
115229             }
115230             // If this file is produced by a referenced project, we need to rewrite it to
115231             // look in the output folder of the referenced project rather than the input
115232             return getResolvedProjectReferenceToRedirect(fileName);
115233         }
115234         function getProjectReferenceOutputName(referencedProject, fileName) {
115235             var out = ts.outFile(referencedProject.commandLine.options);
115236             return out ?
115237                 ts.changeExtension(out, ".d.ts" /* Dts */) :
115238                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
115239         }
115240         /**
115241          * Get the referenced project if the file is input file from that reference project
115242          */
115243         function getResolvedProjectReferenceToRedirect(fileName) {
115244             if (mapFromFileToProjectReferenceRedirects === undefined) {
115245                 mapFromFileToProjectReferenceRedirects = new ts.Map();
115246                 forEachResolvedProjectReference(function (referencedProject) {
115247                     // not input file from the referenced project, ignore
115248                     if (toPath(options.configFilePath) !== referencedProject.sourceFile.path) {
115249                         referencedProject.commandLine.fileNames.forEach(function (f) {
115250                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referencedProject.sourceFile.path);
115251                         });
115252                     }
115253                 });
115254             }
115255             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
115256             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
115257         }
115258         function forEachResolvedProjectReference(cb) {
115259             return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
115260         }
115261         function getSourceOfProjectReferenceRedirect(path) {
115262             if (!ts.isDeclarationFileName(path))
115263                 return undefined;
115264             if (mapFromToProjectReferenceRedirectSource === undefined) {
115265                 mapFromToProjectReferenceRedirectSource = new ts.Map();
115266                 forEachResolvedProjectReference(function (resolvedRef) {
115267                     var out = ts.outFile(resolvedRef.commandLine.options);
115268                     if (out) {
115269                         // Dont know which source file it means so return true?
115270                         var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
115271                         mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
115272                     }
115273                     else {
115274                         var getCommonSourceDirectory_3 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames()); });
115275                         ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
115276                             if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
115277                                 var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_3);
115278                                 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
115279                             }
115280                         });
115281                     }
115282                 });
115283             }
115284             return mapFromToProjectReferenceRedirectSource.get(path);
115285         }
115286         function isSourceOfProjectReferenceRedirect(fileName) {
115287             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
115288         }
115289         function getResolvedProjectReferenceByPath(projectReferencePath) {
115290             if (!projectReferenceRedirects) {
115291                 return undefined;
115292             }
115293             return projectReferenceRedirects.get(projectReferencePath) || undefined;
115294         }
115295         function processReferencedFiles(file, isDefaultLib) {
115296             ts.forEach(file.referencedFiles, function (ref, index) {
115297                 processSourceFile(resolveTripleslashReference(ref.fileName, file.fileName), isDefaultLib, 
115298                 /*ignoreNoDefaultLib*/ false, 
115299                 /*packageId*/ undefined, { kind: ts.FileIncludeKind.ReferenceFile, file: file.path, index: index, });
115300             });
115301         }
115302         function processTypeReferenceDirectives(file) {
115303             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
115304             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
115305             if (!typeDirectives) {
115306                 return;
115307             }
115308             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file);
115309             for (var index = 0; index < typeDirectives.length; index++) {
115310                 var ref = file.typeReferenceDirectives[index];
115311                 var resolvedTypeReferenceDirective = resolutions[index];
115312                 // store resolved type directive on the file
115313                 var fileName = ts.toFileNameLowerCase(ref.fileName);
115314                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
115315                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, });
115316             }
115317         }
115318         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
115319             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
115320             processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason);
115321             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
115322         }
115323         function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
115324             // If we already found this library as a primary reference - nothing to do
115325             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
115326             if (previousResolution && previousResolution.primary) {
115327                 return;
115328             }
115329             var saveResolution = true;
115330             if (resolvedTypeReferenceDirective) {
115331                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
115332                     currentNodeModulesDepth++;
115333                 if (resolvedTypeReferenceDirective.primary) {
115334                     // resolved from the primary path
115335                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason); // TODO: GH#18217
115336                 }
115337                 else {
115338                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
115339                     // for sameness and possibly issue an error
115340                     if (previousResolution) {
115341                         // Don't bother reading the file again if it's the same file.
115342                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
115343                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
115344                             var existingFile = getSourceFile(previousResolution.resolvedFileName);
115345                             if (otherFileText !== existingFile.text) {
115346                                 addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, 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]);
115347                             }
115348                         }
115349                         // don't overwrite previous resolution result
115350                         saveResolution = false;
115351                     }
115352                     else {
115353                         // First resolution of this library
115354                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason);
115355                     }
115356                 }
115357                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
115358                     currentNodeModulesDepth--;
115359             }
115360             else {
115361                 addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_find_type_definition_file_for_0, [typeReferenceDirective]);
115362             }
115363             if (saveResolution) {
115364                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
115365             }
115366         }
115367         function pathForLibFile(libFileName) {
115368             // Support resolving to lib.dom.d.ts -> @typescript/lib-dom, and
115369             //                      lib.dom.iterable.d.ts -> @typescript/lib-dom/iterable
115370             //                      lib.es2015.symbol.wellknown.d.ts -> @typescript/lib-es2015/symbol-wellknown
115371             var components = libFileName.split(".");
115372             var path = components[1];
115373             var i = 2;
115374             while (components[i] && components[i] !== "d") {
115375                 path += (i === 2 ? "/" : "-") + components[i];
115376                 i++;
115377             }
115378             var resolveFrom = ts.combinePaths(currentDirectory, "__lib_node_modules_lookup_".concat(libFileName, "__.ts"));
115379             var localOverrideModuleResult = ts.resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, moduleResolutionCache);
115380             if (localOverrideModuleResult === null || localOverrideModuleResult === void 0 ? void 0 : localOverrideModuleResult.resolvedModule) {
115381                 return localOverrideModuleResult.resolvedModule.resolvedFileName;
115382             }
115383             return ts.combinePaths(defaultLibraryPath, libFileName);
115384         }
115385         function processLibReferenceDirectives(file) {
115386             ts.forEach(file.libReferenceDirectives, function (libReference, index) {
115387                 var libName = ts.toFileNameLowerCase(libReference.fileName);
115388                 var libFileName = ts.libMap.get(libName);
115389                 if (libFileName) {
115390                     // we ignore any 'no-default-lib' reference set on this file.
115391                     processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, });
115392                 }
115393                 else {
115394                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
115395                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
115396                     var diagnostic = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
115397                     (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
115398                         kind: 0 /* FilePreprocessingReferencedDiagnostic */,
115399                         reason: { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, },
115400                         diagnostic: diagnostic,
115401                         args: [libName, suggestion]
115402                     });
115403                 }
115404             });
115405         }
115406         function getCanonicalFileName(fileName) {
115407             return host.getCanonicalFileName(fileName);
115408         }
115409         function processImportedModules(file) {
115410             var _a;
115411             collectExternalModuleReferences(file);
115412             if (file.imports.length || file.moduleAugmentations.length) {
115413                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
115414                 var moduleNames = getModuleNames(file);
115415                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
115416                 ts.Debug.assert(resolutions.length === moduleNames.length);
115417                 var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options;
115418                 for (var index = 0; index < moduleNames.length; index++) {
115419                     var resolution = resolutions[index];
115420                     ts.setResolvedModule(file, moduleNames[index], resolution, getModeForResolutionAtIndex(file, index));
115421                     if (!resolution) {
115422                         continue;
115423                     }
115424                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
115425                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
115426                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
115427                     var resolvedFileName = resolution.resolvedFileName;
115428                     if (isFromNodeModulesSearch) {
115429                         currentNodeModulesDepth++;
115430                     }
115431                     // add file to program only if:
115432                     // - resolution was successful
115433                     // - noResolve is falsy
115434                     // - module name comes from the list of imports
115435                     // - it's not a top level JavaScript module that exceeded the search max
115436                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
115437                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
115438                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
115439                     var shouldAddFile = resolvedFileName
115440                         && !getResolutionDiagnostic(optionsForFile, resolution)
115441                         && !optionsForFile.noResolve
115442                         && index < file.imports.length
115443                         && !elideImport
115444                         && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile))
115445                         && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */));
115446                     if (elideImport) {
115447                         modulesWithElidedImports.set(file.path, true);
115448                     }
115449                     else if (shouldAddFile) {
115450                         findSourceFile(resolvedFileName, 
115451                         /*isDefaultLib*/ false, 
115452                         /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.Import, file: file.path, index: index, }, resolution.packageId);
115453                     }
115454                     if (isFromNodeModulesSearch) {
115455                         currentNodeModulesDepth--;
115456                     }
115457                 }
115458             }
115459             else {
115460                 // no imports - drop cached module resolutions
115461                 file.resolvedModules = undefined;
115462             }
115463         }
115464         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
115465             var allFilesBelongToPath = true;
115466             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
115467             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
115468                 var sourceFile = sourceFiles_2[_i];
115469                 if (!sourceFile.isDeclarationFile) {
115470                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
115471                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
115472                         addProgramDiagnosticExplainingFile(sourceFile, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory]);
115473                         allFilesBelongToPath = false;
115474                     }
115475                 }
115476             }
115477             return allFilesBelongToPath;
115478         }
115479         function parseProjectReferenceConfigFile(ref) {
115480             if (!projectReferenceRedirects) {
115481                 projectReferenceRedirects = new ts.Map();
115482             }
115483             // The actual filename (i.e. add "/tsconfig.json" if necessary)
115484             var refPath = resolveProjectReferencePath(ref);
115485             var sourceFilePath = toPath(refPath);
115486             var fromCache = projectReferenceRedirects.get(sourceFilePath);
115487             if (fromCache !== undefined) {
115488                 return fromCache || undefined;
115489             }
115490             var commandLine;
115491             var sourceFile;
115492             if (host.getParsedCommandLine) {
115493                 commandLine = host.getParsedCommandLine(refPath);
115494                 if (!commandLine) {
115495                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
115496                     projectReferenceRedirects.set(sourceFilePath, false);
115497                     return undefined;
115498                 }
115499                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
115500                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
115501                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
115502             }
115503             else {
115504                 // An absolute path pointing to the containing directory of the config file
115505                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
115506                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
115507                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
115508                 if (sourceFile === undefined) {
115509                     projectReferenceRedirects.set(sourceFilePath, false);
115510                     return undefined;
115511                 }
115512                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
115513             }
115514             sourceFile.fileName = refPath;
115515             sourceFile.path = sourceFilePath;
115516             sourceFile.resolvedPath = sourceFilePath;
115517             sourceFile.originalFileName = refPath;
115518             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
115519             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
115520             if (commandLine.projectReferences) {
115521                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
115522             }
115523             return resolvedRef;
115524         }
115525         function verifyCompilerOptions() {
115526             var isNightly = ts.stringContains(ts.version, "-dev");
115527             if (!isNightly) {
115528                 if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) {
115529                     createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12");
115530                 }
115531                 else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) {
115532                     createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext");
115533                 }
115534                 else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) {
115535                     createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12");
115536                 }
115537                 else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
115538                     createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext");
115539                 }
115540             }
115541             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
115542                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
115543             }
115544             if (options.exactOptionalPropertyTypes && !ts.getStrictOptionValue(options, "strictNullChecks")) {
115545                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "exactOptionalPropertyTypes", "strictNullChecks");
115546             }
115547             if (options.isolatedModules) {
115548                 if (options.out) {
115549                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
115550                 }
115551                 if (options.outFile) {
115552                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
115553                 }
115554             }
115555             if (options.inlineSourceMap) {
115556                 if (options.sourceMap) {
115557                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
115558                 }
115559                 if (options.mapRoot) {
115560                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
115561                 }
115562             }
115563             if (options.composite) {
115564                 if (options.declaration === false) {
115565                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
115566                 }
115567                 if (options.incremental === false) {
115568                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
115569                 }
115570             }
115571             var outputFile = ts.outFile(options);
115572             if (options.tsBuildInfoFile) {
115573                 if (!ts.isIncrementalCompilation(options)) {
115574                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
115575                 }
115576             }
115577             else if (options.incremental && !outputFile && !options.configFilePath) {
115578                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
115579             }
115580             verifyProjectReferences();
115581             // List of collected files is complete; validate exhautiveness if this is a project with a file list
115582             if (options.composite) {
115583                 var rootPaths = new ts.Set(rootNames.map(toPath));
115584                 for (var _i = 0, files_4 = files; _i < files_4.length; _i++) {
115585                     var file = files_4[_i];
115586                     // Ignore file that is not emitted
115587                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
115588                         addProgramDiagnosticExplainingFile(file, 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 || ""]);
115589                     }
115590                 }
115591             }
115592             if (options.paths) {
115593                 for (var key in options.paths) {
115594                     if (!ts.hasProperty(options.paths, key)) {
115595                         continue;
115596                     }
115597                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
115598                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
115599                     }
115600                     if (ts.isArray(options.paths[key])) {
115601                         var len = options.paths[key].length;
115602                         if (len === 0) {
115603                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
115604                         }
115605                         for (var i = 0; i < len; i++) {
115606                             var subst = options.paths[key][i];
115607                             var typeOfSubst = typeof subst;
115608                             if (typeOfSubst === "string") {
115609                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
115610                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
115611                                 }
115612                                 if (!options.baseUrl && !ts.pathIsRelative(subst) && !ts.pathIsAbsolute(subst)) {
115613                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash);
115614                                 }
115615                             }
115616                             else {
115617                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
115618                             }
115619                         }
115620                     }
115621                     else {
115622                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
115623                     }
115624                 }
115625             }
115626             if (!options.sourceMap && !options.inlineSourceMap) {
115627                 if (options.inlineSources) {
115628                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
115629                 }
115630                 if (options.sourceRoot) {
115631                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
115632                 }
115633             }
115634             if (options.out && options.outFile) {
115635                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
115636             }
115637             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
115638                 // Error to specify --mapRoot without --sourcemap
115639                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
115640             }
115641             if (options.declarationDir) {
115642                 if (!ts.getEmitDeclarations(options)) {
115643                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
115644                 }
115645                 if (outputFile) {
115646                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
115647                 }
115648             }
115649             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
115650                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
115651             }
115652             if (options.lib && options.noLib) {
115653                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
115654             }
115655             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
115656                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
115657             }
115658             var languageVersion = ts.getEmitScriptTarget(options);
115659             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
115660             if (options.isolatedModules) {
115661                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
115662                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
115663                 }
115664                 if (options.preserveConstEnums === false) {
115665                     createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules");
115666                 }
115667                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
115668                 if (firstNonExternalModuleSourceFile) {
115669                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
115670                     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)));
115671                 }
115672             }
115673             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
115674                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
115675                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
115676                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
115677             }
115678             // Cannot specify module gen that isn't amd or system with --out
115679             if (outputFile && !options.emitDeclarationOnly) {
115680                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
115681                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
115682                 }
115683                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
115684                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
115685                     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"));
115686                 }
115687             }
115688             if (options.resolveJsonModule) {
115689                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs &&
115690                     ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 &&
115691                     ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) {
115692                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
115693                 }
115694                 // Any emit other than common js, amd, es2015 or esnext is error
115695                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
115696                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
115697                 }
115698             }
115699             // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot
115700             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
115701             if (options.outDir || // there is --outDir specified
115702                 options.rootDir || // there is --rootDir specified
115703                 options.sourceRoot || // there is --sourceRoot specified
115704                 options.mapRoot) { // there is --mapRoot specified
115705                 // Precalculate and cache the common source directory
115706                 var dir = getCommonSourceDirectory();
115707                 // 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
115708                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
115709                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
115710                 }
115711             }
115712             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
115713                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
115714             }
115715             if (options.checkJs && !ts.getAllowJSCompilerOption(options)) {
115716                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
115717             }
115718             if (options.emitDeclarationOnly) {
115719                 if (!ts.getEmitDeclarations(options)) {
115720                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
115721                 }
115722                 if (options.noEmit) {
115723                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
115724                 }
115725             }
115726             if (options.emitDecoratorMetadata &&
115727                 !options.experimentalDecorators) {
115728                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
115729             }
115730             if (options.jsxFactory) {
115731                 if (options.reactNamespace) {
115732                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
115733                 }
115734                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
115735                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
115736                 }
115737                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
115738                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
115739                 }
115740             }
115741             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
115742                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
115743             }
115744             if (options.jsxFragmentFactory) {
115745                 if (!options.jsxFactory) {
115746                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
115747                 }
115748                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
115749                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
115750                 }
115751                 if (!ts.parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
115752                     createOptionValueDiagnostic("jsxFragmentFactory", ts.Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
115753                 }
115754             }
115755             if (options.reactNamespace) {
115756                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
115757                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", ts.inverseJsxOptionMap.get("" + options.jsx));
115758                 }
115759             }
115760             if (options.jsxImportSource) {
115761                 if (options.jsx === 2 /* React */) {
115762                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", ts.inverseJsxOptionMap.get("" + options.jsx));
115763                 }
115764             }
115765             if (options.preserveValueImports && ts.getEmitModuleKind(options) < ts.ModuleKind.ES2015) {
115766                 createOptionValueDiagnostic("importsNotUsedAsValues", ts.Diagnostics.Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later);
115767             }
115768             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
115769             if (!options.noEmit && !options.suppressOutputPathCheck) {
115770                 var emitHost = getEmitHost();
115771                 var emitFilesSeen_1 = new ts.Set();
115772                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
115773                     if (!options.emitDeclarationOnly) {
115774                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
115775                     }
115776                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
115777                 });
115778             }
115779             // Verify that all the emit files are unique and don't overwrite input files
115780             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
115781                 if (emitFileName) {
115782                     var emitFilePath = toPath(emitFileName);
115783                     // Report error if the output overwrites input file
115784                     if (filesByName.has(emitFilePath)) {
115785                         var chain = void 0;
115786                         if (!options.configFilePath) {
115787                             // The program is from either an inferred project or an external project
115788                             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);
115789                         }
115790                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
115791                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
115792                     }
115793                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
115794                     // Report error if multiple files write into same file
115795                     if (emitFilesSeen.has(emitFileKey)) {
115796                         // Already seen the same emit file - report error
115797                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
115798                     }
115799                     else {
115800                         emitFilesSeen.add(emitFileKey);
115801                     }
115802                 }
115803             }
115804         }
115805         function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) {
115806             var _a;
115807             var fileIncludeReasons;
115808             var relatedInfo;
115809             var locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : undefined;
115810             if (file)
115811                 (_a = fileReasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(processReason);
115812             if (fileProcessingReason)
115813                 processReason(fileProcessingReason);
115814             // If we have location and there is only one reason file is in which is the location, dont add details for file include
115815             if (locationReason && (fileIncludeReasons === null || fileIncludeReasons === void 0 ? void 0 : fileIncludeReasons.length) === 1)
115816                 fileIncludeReasons = undefined;
115817             var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason);
115818             var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon);
115819             var redirectInfo = file && ts.explainIfFileIsRedirect(file);
115820             var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false));
115821             return location && isReferenceFileLocation(location) ?
115822                 ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) :
115823                 ts.createCompilerDiagnosticFromMessageChain(chain, relatedInfo);
115824             function processReason(reason) {
115825                 (fileIncludeReasons || (fileIncludeReasons = [])).push(ts.fileIncludeReasonToDiagnostics(program, reason));
115826                 if (!locationReason && isReferencedFile(reason)) {
115827                     // Report error at first reference file or file currently in processing and dont report in related information
115828                     locationReason = reason;
115829                 }
115830                 else if (locationReason !== reason) {
115831                     relatedInfo = ts.append(relatedInfo, fileIncludeReasonToRelatedInformation(reason));
115832                 }
115833                 // Remove fileProcessingReason if its already included in fileReasons of the program
115834                 if (reason === fileProcessingReason)
115835                     fileProcessingReason = undefined;
115836             }
115837         }
115838         function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) {
115839             (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
115840                 kind: 1 /* FilePreprocessingFileExplainingDiagnostic */,
115841                 file: file && file.path,
115842                 fileProcessingReason: fileProcessingReason,
115843                 diagnostic: diagnostic,
115844                 args: args
115845             });
115846         }
115847         function addProgramDiagnosticExplainingFile(file, diagnostic, args) {
115848             programDiagnostics.add(createDiagnosticExplainingFile(file, /*fileProcessingReason*/ undefined, diagnostic, args));
115849         }
115850         function fileIncludeReasonToRelatedInformation(reason) {
115851             if (isReferencedFile(reason)) {
115852                 var referenceLocation = getReferencedFileLocation(getSourceFileByPath, reason);
115853                 var message_2;
115854                 switch (reason.kind) {
115855                     case ts.FileIncludeKind.Import:
115856                         message_2 = ts.Diagnostics.File_is_included_via_import_here;
115857                         break;
115858                     case ts.FileIncludeKind.ReferenceFile:
115859                         message_2 = ts.Diagnostics.File_is_included_via_reference_here;
115860                         break;
115861                     case ts.FileIncludeKind.TypeReferenceDirective:
115862                         message_2 = ts.Diagnostics.File_is_included_via_type_library_reference_here;
115863                         break;
115864                     case ts.FileIncludeKind.LibReferenceDirective:
115865                         message_2 = ts.Diagnostics.File_is_included_via_library_reference_here;
115866                         break;
115867                     default:
115868                         ts.Debug.assertNever(reason);
115869                 }
115870                 return isReferenceFileLocation(referenceLocation) ? ts.createFileDiagnostic(referenceLocation.file, referenceLocation.pos, referenceLocation.end - referenceLocation.pos, message_2) : undefined;
115871             }
115872             if (!options.configFile)
115873                 return undefined;
115874             var configFileNode;
115875             var message;
115876             switch (reason.kind) {
115877                 case ts.FileIncludeKind.RootFile:
115878                     if (!options.configFile.configFileSpecs)
115879                         return undefined;
115880                     var fileName = ts.getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory);
115881                     var matchedByFiles = ts.getMatchedFileSpec(program, fileName);
115882                     if (matchedByFiles) {
115883                         configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "files", matchedByFiles);
115884                         message = ts.Diagnostics.File_is_matched_by_files_list_specified_here;
115885                         break;
115886                     }
115887                     var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName);
115888                     // Could be additional files specified as roots
115889                     if (!matchedByInclude)
115890                         return undefined;
115891                     configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude);
115892                     message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here;
115893                     break;
115894                 case ts.FileIncludeKind.SourceFromProjectReference:
115895                 case ts.FileIncludeKind.OutputFromProjectReference:
115896                     var referencedResolvedRef_1 = ts.Debug.checkDefined(resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences[reason.index]);
115897                     var referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
115898                         return resolvedRef === referencedResolvedRef_1 ? { sourceFile: (parent === null || parent === void 0 ? void 0 : parent.sourceFile) || options.configFile, index: index } : undefined;
115899                     });
115900                     if (!referenceInfo)
115901                         return undefined;
115902                     var sourceFile = referenceInfo.sourceFile, index = referenceInfo.index;
115903                     var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
115904                     return referencesSyntax && referencesSyntax.elements.length > index ?
115905                         ts.createDiagnosticForNodeInSourceFile(sourceFile, referencesSyntax.elements[index], reason.kind === ts.FileIncludeKind.OutputFromProjectReference ?
115906                             ts.Diagnostics.File_is_output_from_referenced_project_specified_here :
115907                             ts.Diagnostics.File_is_source_from_referenced_project_specified_here) :
115908                         undefined;
115909                 case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
115910                     if (!options.types)
115911                         return undefined;
115912                     configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference);
115913                     message = ts.Diagnostics.File_is_entry_point_of_type_library_specified_here;
115914                     break;
115915                 case ts.FileIncludeKind.LibFile:
115916                     if (reason.index !== undefined) {
115917                         configFileNode = getOptionsSyntaxByArrayElementValue("lib", options.lib[reason.index]);
115918                         message = ts.Diagnostics.File_is_library_specified_here;
115919                         break;
115920                     }
115921                     var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === ts.getEmitScriptTarget(options) ? key : undefined; });
115922                     configFileNode = target ? getOptionsSyntaxByValue("target", target) : undefined;
115923                     message = ts.Diagnostics.File_is_default_library_for_target_specified_here;
115924                     break;
115925                 default:
115926                     ts.Debug.assertNever(reason);
115927             }
115928             return configFileNode && ts.createDiagnosticForNodeInSourceFile(options.configFile, configFileNode, message);
115929         }
115930         function verifyProjectReferences() {
115931             var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
115932             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
115933                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
115934                 var parentFile = parent && parent.sourceFile;
115935                 if (!resolvedRef) {
115936                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
115937                     return;
115938                 }
115939                 var options = resolvedRef.commandLine.options;
115940                 if (!options.composite || options.noEmit) {
115941                     // ok to not have composite if the current program is container only
115942                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
115943                     if (inputs.length) {
115944                         if (!options.composite)
115945                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
115946                         if (options.noEmit)
115947                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
115948                     }
115949                 }
115950                 if (ref.prepend) {
115951                     var out = ts.outFile(options);
115952                     if (out) {
115953                         if (!host.fileExists(out)) {
115954                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
115955                         }
115956                     }
115957                     else {
115958                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
115959                     }
115960                 }
115961                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
115962                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
115963                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
115964                 }
115965             });
115966         }
115967         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
115968             var needCompilerDiagnostic = true;
115969             var pathsSyntax = getOptionPathsSyntax();
115970             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
115971                 var pathProp = pathsSyntax_1[_i];
115972                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
115973                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
115974                         var keyProps = _b[_a];
115975                         var initializer = keyProps.initializer;
115976                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
115977                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
115978                             needCompilerDiagnostic = false;
115979                         }
115980                     }
115981                 }
115982             }
115983             if (needCompilerDiagnostic) {
115984                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
115985             }
115986         }
115987         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
115988             var needCompilerDiagnostic = true;
115989             var pathsSyntax = getOptionPathsSyntax();
115990             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
115991                 var pathProp = pathsSyntax_2[_i];
115992                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
115993                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
115994                     needCompilerDiagnostic = false;
115995                 }
115996             }
115997             if (needCompilerDiagnostic) {
115998                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
115999             }
116000         }
116001         function getOptionsSyntaxByName(name) {
116002             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
116003             return compilerOptionsObjectLiteralSyntax && ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
116004         }
116005         function getOptionPathsSyntax() {
116006             return getOptionsSyntaxByName("paths") || ts.emptyArray;
116007         }
116008         function getOptionsSyntaxByValue(name, value) {
116009             var syntaxByName = getOptionsSyntaxByName(name);
116010             return syntaxByName && ts.firstDefined(syntaxByName, function (property) { return ts.isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : undefined; });
116011         }
116012         function getOptionsSyntaxByArrayElementValue(name, value) {
116013             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
116014             return compilerOptionsObjectLiteralSyntax && ts.getPropertyArrayElementValue(compilerOptionsObjectLiteralSyntax, name, value);
116015         }
116016         function createDiagnosticForOptionName(message, option1, option2, option3) {
116017             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
116018         }
116019         function createOptionValueDiagnostic(option1, message, arg0, arg1) {
116020             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1);
116021         }
116022         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
116023             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
116024             if (referencesSyntax && referencesSyntax.elements.length > index) {
116025                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
116026             }
116027             else {
116028                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
116029             }
116030         }
116031         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
116032             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
116033             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
116034                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
116035             if (needCompilerDiagnostic) {
116036                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
116037             }
116038         }
116039         function getCompilerOptionsObjectLiteralSyntax() {
116040             if (_compilerOptionsObjectLiteralSyntax === undefined) {
116041                 _compilerOptionsObjectLiteralSyntax = false;
116042                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
116043                 if (jsonObjectLiteral) {
116044                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
116045                         var prop = _a[_i];
116046                         if (ts.isObjectLiteralExpression(prop.initializer)) {
116047                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
116048                             break;
116049                         }
116050                     }
116051                 }
116052             }
116053             return _compilerOptionsObjectLiteralSyntax || undefined;
116054         }
116055         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
116056             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
116057             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
116058                 var prop = props_3[_i];
116059                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
116060             }
116061             return !!props.length;
116062         }
116063         function blockEmittingOfFile(emitFileName, diag) {
116064             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
116065             programDiagnostics.add(diag);
116066         }
116067         function isEmittedFile(file) {
116068             if (options.noEmit) {
116069                 return false;
116070             }
116071             // If this is source file, its not emitted file
116072             var filePath = toPath(file);
116073             if (getSourceFileByPath(filePath)) {
116074                 return false;
116075             }
116076             // If options have --outFile or --out just check that
116077             var out = ts.outFile(options);
116078             if (out) {
116079                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
116080             }
116081             // If declarationDir is specified, return if its a file in that directory
116082             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
116083                 return true;
116084             }
116085             // If --outDir, check if file is in that directory
116086             if (options.outDir) {
116087                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
116088             }
116089             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensionsFlat) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
116090                 // Otherwise just check if sourceFile with the name exists
116091                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
116092                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
116093                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
116094             }
116095             return false;
116096         }
116097         function isSameFile(file1, file2) {
116098             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
116099         }
116100         function getSymlinkCache() {
116101             if (host.getSymlinkCache) {
116102                 return host.getSymlinkCache();
116103             }
116104             if (!symlinks) {
116105                 symlinks = ts.createSymlinkCache(currentDirectory, getCanonicalFileName);
116106             }
116107             if (files && resolvedTypeReferenceDirectives && !symlinks.hasProcessedResolutions()) {
116108                 symlinks.setSymlinksFromResolutions(files, resolvedTypeReferenceDirectives);
116109             }
116110             return symlinks;
116111         }
116112     }
116113     ts.createProgram = createProgram;
116114     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
116115         var setOfDeclarationDirectories;
116116         var originalFileExists = host.compilerHost.fileExists;
116117         var originalDirectoryExists = host.compilerHost.directoryExists;
116118         var originalGetDirectories = host.compilerHost.getDirectories;
116119         var originalRealpath = host.compilerHost.realpath;
116120         if (!host.useSourceOfProjectReferenceRedirect)
116121             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
116122         host.compilerHost.fileExists = fileExists;
116123         var directoryExists;
116124         if (originalDirectoryExists) {
116125             // This implementation of directoryExists checks if the directory being requested is
116126             // directory of .d.ts file for the referenced Project.
116127             // If it is it returns true irrespective of whether that directory exists on host
116128             directoryExists = host.compilerHost.directoryExists = function (path) {
116129                 if (originalDirectoryExists.call(host.compilerHost, path)) {
116130                     handleDirectoryCouldBeSymlink(path);
116131                     return true;
116132                 }
116133                 if (!host.getResolvedProjectReferences())
116134                     return false;
116135                 if (!setOfDeclarationDirectories) {
116136                     setOfDeclarationDirectories = new ts.Set();
116137                     host.forEachResolvedProjectReference(function (ref) {
116138                         var out = ts.outFile(ref.commandLine.options);
116139                         if (out) {
116140                             setOfDeclarationDirectories.add(ts.getDirectoryPath(host.toPath(out)));
116141                         }
116142                         else {
116143                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
116144                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
116145                             if (declarationDir) {
116146                                 setOfDeclarationDirectories.add(host.toPath(declarationDir));
116147                             }
116148                         }
116149                     });
116150                 }
116151                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
116152             };
116153         }
116154         if (originalGetDirectories) {
116155             // Call getDirectories only if directory actually present on the host
116156             // This is needed to ensure that we arent getting directories that we fake about presence for
116157             host.compilerHost.getDirectories = function (path) {
116158                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
116159                     originalGetDirectories.call(host.compilerHost, path) :
116160                     [];
116161             };
116162         }
116163         // This is something we keep for life time of the host
116164         if (originalRealpath) {
116165             host.compilerHost.realpath = function (s) {
116166                 var _a;
116167                 return ((_a = host.getSymlinkCache().getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.get(host.toPath(s))) ||
116168                     originalRealpath.call(host.compilerHost, s);
116169             };
116170         }
116171         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists };
116172         function onProgramCreateComplete() {
116173             host.compilerHost.fileExists = originalFileExists;
116174             host.compilerHost.directoryExists = originalDirectoryExists;
116175             host.compilerHost.getDirectories = originalGetDirectories;
116176             // DO not revert realpath as it could be used later
116177         }
116178         // This implementation of fileExists checks if the file being requested is
116179         // .d.ts file for the referenced Project.
116180         // If it is it returns true irrespective of whether that file exists on host
116181         function fileExists(file) {
116182             if (originalFileExists.call(host.compilerHost, file))
116183                 return true;
116184             if (!host.getResolvedProjectReferences())
116185                 return false;
116186             if (!ts.isDeclarationFileName(file))
116187                 return false;
116188             // Project references go to source file instead of .d.ts file
116189             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
116190         }
116191         function fileExistsIfProjectReferenceDts(file) {
116192             var source = host.getSourceOfProjectReferenceRedirect(host.toPath(file));
116193             return source !== undefined ?
116194                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
116195                 undefined;
116196         }
116197         function directoryExistsIfProjectReferenceDeclDir(dir) {
116198             var dirPath = host.toPath(dir);
116199             var dirPathWithTrailingDirectorySeparator = "".concat(dirPath).concat(ts.directorySeparator);
116200             return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
116201                 // Any parent directory of declaration dir
116202                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
116203                 // Any directory inside declaration dir
116204                 ts.startsWith(dirPath, "".concat(declDirPath, "/")); });
116205         }
116206         function handleDirectoryCouldBeSymlink(directory) {
116207             var _a;
116208             if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory))
116209                 return;
116210             // Because we already watch node_modules, handle symlinks in there
116211             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
116212                 return;
116213             var symlinkCache = host.getSymlinkCache();
116214             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
116215             if ((_a = symlinkCache.getSymlinkedDirectories()) === null || _a === void 0 ? void 0 : _a.has(directoryPath))
116216                 return;
116217             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
116218             var realPath;
116219             if (real === directory ||
116220                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
116221                 // not symlinked
116222                 symlinkCache.setSymlinkedDirectory(directoryPath, false);
116223                 return;
116224             }
116225             symlinkCache.setSymlinkedDirectory(directory, {
116226                 real: ts.ensureTrailingDirectorySeparator(real),
116227                 realPath: realPath
116228             });
116229         }
116230         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
116231             var _a;
116232             var fileOrDirectoryExistsUsingSource = isFile ?
116233                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
116234                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
116235             // Check current directory or file
116236             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
116237             if (result !== undefined)
116238                 return result;
116239             var symlinkCache = host.getSymlinkCache();
116240             var symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
116241             if (!symlinkedDirectories)
116242                 return false;
116243             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
116244             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
116245                 return false;
116246             if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.has(fileOrDirectoryPath)))
116247                 return true;
116248             // If it contains node_modules check if its one of the symlinked path we know of
116249             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
116250                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
116251                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
116252                     return undefined;
116253                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
116254                 if (isFile && result) {
116255                     // Store the real path for the file'
116256                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
116257                     symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "".concat(symlinkedDirectory.real).concat(absolutePath.replace(new RegExp(directoryPath, "i"), "")));
116258                 }
116259                 return result;
116260             }) || false;
116261         }
116262     }
116263     /*@internal*/
116264     ts.emitSkippedWithNoDiagnostics = { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
116265     /*@internal*/
116266     function handleNoEmitOptions(program, sourceFile, writeFile, cancellationToken) {
116267         var options = program.getCompilerOptions();
116268         if (options.noEmit) {
116269             // Cache the semantic diagnostics
116270             program.getSemanticDiagnostics(sourceFile, cancellationToken);
116271             return sourceFile || ts.outFile(options) ?
116272                 ts.emitSkippedWithNoDiagnostics :
116273                 program.emitBuildInfo(writeFile, cancellationToken);
116274         }
116275         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
116276         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
116277         // get any preEmit diagnostics, not just the ones
116278         if (!options.noEmitOnError)
116279             return undefined;
116280         var diagnostics = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken), true), program.getSyntacticDiagnostics(sourceFile, cancellationToken), true), program.getGlobalDiagnostics(cancellationToken), true), program.getSemanticDiagnostics(sourceFile, cancellationToken), true);
116281         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
116282             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
116283         }
116284         if (!diagnostics.length)
116285             return undefined;
116286         var emittedFiles;
116287         if (!sourceFile && !ts.outFile(options)) {
116288             var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
116289             if (emitResult.diagnostics)
116290                 diagnostics = __spreadArray(__spreadArray([], diagnostics, true), emitResult.diagnostics, true);
116291             emittedFiles = emitResult.emittedFiles;
116292         }
116293         return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
116294     }
116295     ts.handleNoEmitOptions = handleNoEmitOptions;
116296     /*@internal*/
116297     function filterSemanticDiagnostics(diagnostic, option) {
116298         return ts.filter(diagnostic, function (d) { return !d.skippedOn || !option[d.skippedOn]; });
116299     }
116300     ts.filterSemanticDiagnostics = filterSemanticDiagnostics;
116301     /* @internal */
116302     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
116303         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
116304         return {
116305             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
116306             readDirectory: function (root, extensions, excludes, includes, depth) {
116307                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
116308                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
116309             },
116310             readFile: function (f) { return directoryStructureHost.readFile(f); },
116311             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
116312             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
116313             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
116314             trace: host.trace ? function (s) { return host.trace(s); } : undefined
116315         };
116316     }
116317     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
116318     /* @internal */
116319     function createPrependNodes(projectReferences, getCommandLine, readFile) {
116320         if (!projectReferences)
116321             return ts.emptyArray;
116322         var nodes;
116323         for (var i = 0; i < projectReferences.length; i++) {
116324             var ref = projectReferences[i];
116325             var resolvedRefOpts = getCommandLine(ref, i);
116326             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
116327                 var out = ts.outFile(resolvedRefOpts.options);
116328                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
116329                 if (!out)
116330                     continue;
116331                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
116332                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
116333                 (nodes || (nodes = [])).push(node);
116334             }
116335         }
116336         return nodes || ts.emptyArray;
116337     }
116338     ts.createPrependNodes = createPrependNodes;
116339     function resolveProjectReferencePath(hostOrRef, ref) {
116340         var passedInRef = ref ? ref : hostOrRef;
116341         return ts.resolveConfigFileProjectName(passedInRef.path);
116342     }
116343     ts.resolveProjectReferencePath = resolveProjectReferencePath;
116344     /* @internal */
116345     /**
116346      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
116347      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
116348      * This returns a diagnostic even if the module will be an untyped module.
116349      */
116350     function getResolutionDiagnostic(options, _a) {
116351         var extension = _a.extension;
116352         switch (extension) {
116353             case ".ts" /* Ts */:
116354             case ".d.ts" /* Dts */:
116355                 // These are always allowed.
116356                 return undefined;
116357             case ".tsx" /* Tsx */:
116358                 return needJsx();
116359             case ".jsx" /* Jsx */:
116360                 return needJsx() || needAllowJs();
116361             case ".js" /* Js */:
116362                 return needAllowJs();
116363             case ".json" /* Json */:
116364                 return needResolveJsonModule();
116365         }
116366         function needJsx() {
116367             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
116368         }
116369         function needAllowJs() {
116370             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;
116371         }
116372         function needResolveJsonModule() {
116373             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
116374         }
116375     }
116376     ts.getResolutionDiagnostic = getResolutionDiagnostic;
116377     function getModuleNames(_a) {
116378         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
116379         var res = imports.map(function (i) { return i.text; });
116380         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
116381             var aug = moduleAugmentations_1[_i];
116382             if (aug.kind === 10 /* StringLiteral */) {
116383                 res.push(aug.text);
116384             }
116385             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
116386         }
116387         return res;
116388     }
116389     /* @internal */
116390     function getModuleNameStringLiteralAt(_a, index) {
116391         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
116392         if (index < imports.length)
116393             return imports[index];
116394         var augIndex = imports.length;
116395         for (var _i = 0, moduleAugmentations_2 = moduleAugmentations; _i < moduleAugmentations_2.length; _i++) {
116396             var aug = moduleAugmentations_2[_i];
116397             if (aug.kind === 10 /* StringLiteral */) {
116398                 if (index === augIndex)
116399                     return aug;
116400                 augIndex++;
116401             }
116402             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
116403         }
116404         ts.Debug.fail("should never ask for module name at index higher than possible module name");
116405     }
116406     ts.getModuleNameStringLiteralAt = getModuleNameStringLiteralAt;
116407 })(ts || (ts = {}));
116408 /*@internal*/
116409 var ts;
116410 (function (ts) {
116411     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
116412         var outputFiles = [];
116413         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
116414         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
116415         function writeFile(fileName, text, writeByteOrderMark) {
116416             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
116417         }
116418     }
116419     ts.getFileEmitOutput = getFileEmitOutput;
116420     var BuilderState;
116421     (function (BuilderState) {
116422         var manyToManyPathMapCount = 0;
116423         function createManyToManyPathMap() {
116424             function create(forward, reverse, deleted) {
116425                 var version = 0;
116426                 var map = {
116427                     id: manyToManyPathMapCount++,
116428                     version: function () { return version; },
116429                     clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); },
116430                     forEach: function (fn) { return forward.forEach(fn); },
116431                     getKeys: function (v) { return reverse.get(v); },
116432                     getValues: function (k) { return forward.get(k); },
116433                     hasKey: function (k) { return forward.has(k); },
116434                     keys: function () { return forward.keys(); },
116435                     deletedKeys: function () { return deleted; },
116436                     deleteKey: function (k) {
116437                         (deleted || (deleted = new ts.Set())).add(k);
116438                         var set = forward.get(k);
116439                         if (!set) {
116440                             return false;
116441                         }
116442                         set.forEach(function (v) { return deleteFromMultimap(reverse, v, k); });
116443                         forward.delete(k);
116444                         version++;
116445                         return true;
116446                     },
116447                     set: function (k, vSet) {
116448                         var changed = !!(deleted === null || deleted === void 0 ? void 0 : deleted.delete(k));
116449                         var existingVSet = forward.get(k);
116450                         forward.set(k, vSet);
116451                         existingVSet === null || existingVSet === void 0 ? void 0 : existingVSet.forEach(function (v) {
116452                             if (!vSet.has(v)) {
116453                                 changed = true;
116454                                 deleteFromMultimap(reverse, v, k);
116455                             }
116456                         });
116457                         vSet.forEach(function (v) {
116458                             if (!(existingVSet === null || existingVSet === void 0 ? void 0 : existingVSet.has(v))) {
116459                                 changed = true;
116460                                 addToMultimap(reverse, v, k);
116461                             }
116462                         });
116463                         if (changed) {
116464                             version++;
116465                         }
116466                         return map;
116467                     },
116468                 };
116469                 return map;
116470             }
116471             return create(new ts.Map(), new ts.Map(), /*deleted*/ undefined);
116472         }
116473         BuilderState.createManyToManyPathMap = createManyToManyPathMap;
116474         function addToMultimap(map, k, v) {
116475             var set = map.get(k);
116476             if (!set) {
116477                 set = new ts.Set();
116478                 map.set(k, set);
116479             }
116480             set.add(v);
116481         }
116482         function deleteFromMultimap(map, k, v, removeEmpty) {
116483             if (removeEmpty === void 0) { removeEmpty = true; }
116484             var set = map.get(k);
116485             if (set === null || set === void 0 ? void 0 : set.delete(v)) {
116486                 if (removeEmpty && !set.size) {
116487                     map.delete(k);
116488                 }
116489                 return true;
116490             }
116491             return false;
116492         }
116493         function getReferencedFilesFromImportedModuleSymbol(symbol) {
116494             return ts.mapDefined(symbol.declarations, function (declaration) { var _a; return (_a = ts.getSourceFileOfNode(declaration)) === null || _a === void 0 ? void 0 : _a.resolvedPath; });
116495         }
116496         /**
116497          * Get the module source file and all augmenting files from the import name node from file
116498          */
116499         function getReferencedFilesFromImportLiteral(checker, importName) {
116500             var symbol = checker.getSymbolAtLocation(importName);
116501             return symbol && getReferencedFilesFromImportedModuleSymbol(symbol);
116502         }
116503         /**
116504          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
116505          */
116506         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
116507             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
116508         }
116509         /**
116510          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
116511          */
116512         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
116513             var referencedFiles;
116514             // We need to use a set here since the code can contain the same import twice,
116515             // but that will only be one dependency.
116516             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
116517             if (sourceFile.imports && sourceFile.imports.length > 0) {
116518                 var checker = program.getTypeChecker();
116519                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
116520                     var importName = _a[_i];
116521                     var declarationSourceFilePaths = getReferencedFilesFromImportLiteral(checker, importName);
116522                     declarationSourceFilePaths === null || declarationSourceFilePaths === void 0 ? void 0 : declarationSourceFilePaths.forEach(addReferencedFile);
116523                 }
116524             }
116525             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
116526             // Handle triple slash references
116527             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
116528                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
116529                     var referencedFile = _c[_b];
116530                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
116531                     addReferencedFile(referencedPath);
116532                 }
116533             }
116534             // Handle type reference directives
116535             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
116536                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
116537                     if (!resolvedTypeReferenceDirective) {
116538                         return;
116539                     }
116540                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
116541                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
116542                     addReferencedFile(typeFilePath);
116543                 });
116544             }
116545             // Add module augmentation as references
116546             if (sourceFile.moduleAugmentations.length) {
116547                 var checker = program.getTypeChecker();
116548                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
116549                     var moduleName = _e[_d];
116550                     if (!ts.isStringLiteral(moduleName))
116551                         continue;
116552                     var symbol = checker.getSymbolAtLocation(moduleName);
116553                     if (!symbol)
116554                         continue;
116555                     // Add any file other than our own as reference
116556                     addReferenceFromAmbientModule(symbol);
116557                 }
116558             }
116559             // From ambient modules
116560             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
116561                 var ambientModule = _g[_f];
116562                 if (ambientModule.declarations && ambientModule.declarations.length > 1) {
116563                     addReferenceFromAmbientModule(ambientModule);
116564                 }
116565             }
116566             return referencedFiles;
116567             function addReferenceFromAmbientModule(symbol) {
116568                 if (!symbol.declarations) {
116569                     return;
116570                 }
116571                 // Add any file other than our own as reference
116572                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
116573                     var declaration = _a[_i];
116574                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
116575                     if (declarationSourceFile &&
116576                         declarationSourceFile !== sourceFile) {
116577                         addReferencedFile(declarationSourceFile.resolvedPath);
116578                     }
116579                 }
116580             }
116581             function addReferencedFile(referencedPath) {
116582                 (referencedFiles || (referencedFiles = new ts.Set())).add(referencedPath);
116583             }
116584         }
116585         /**
116586          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
116587          */
116588         function canReuseOldState(newReferencedMap, oldState) {
116589             return oldState && !oldState.referencedMap === !newReferencedMap;
116590         }
116591         BuilderState.canReuseOldState = canReuseOldState;
116592         /**
116593          * Creates the state of file references and signature for the new program from oldState if it is safe
116594          */
116595         function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) {
116596             var fileInfos = new ts.Map();
116597             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined;
116598             var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined;
116599             var hasCalledUpdateShapeSignature = new ts.Set();
116600             var useOldState = canReuseOldState(referencedMap, oldState);
116601             // Ensure source files have parent pointers set
116602             newProgram.getTypeChecker();
116603             // Create the reference map, and set the file infos
116604             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
116605                 var sourceFile = _a[_i];
116606                 var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
116607                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
116608                 if (referencedMap) {
116609                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
116610                     if (newReferences) {
116611                         referencedMap.set(sourceFile.resolvedPath, newReferences);
116612                     }
116613                     // Copy old visible to outside files map
116614                     if (useOldState) {
116615                         var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath);
116616                         if (exportedModules) {
116617                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
116618                         }
116619                     }
116620                 }
116621                 fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat });
116622             }
116623             return {
116624                 fileInfos: fileInfos,
116625                 referencedMap: referencedMap,
116626                 exportedModulesMap: exportedModulesMap,
116627                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature,
116628                 useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState
116629             };
116630         }
116631         BuilderState.create = create;
116632         /**
116633          * Releases needed properties
116634          */
116635         function releaseCache(state) {
116636             state.allFilesExcludingDefaultLibraryFile = undefined;
116637             state.allFileNames = undefined;
116638         }
116639         BuilderState.releaseCache = releaseCache;
116640         /**
116641          * Creates a clone of the state
116642          */
116643         function clone(state) {
116644             var _a, _b;
116645             // Dont need to backup allFiles info since its cache anyway
116646             return {
116647                 fileInfos: new ts.Map(state.fileInfos),
116648                 referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(),
116649                 exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(),
116650                 hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature),
116651                 useFileVersionAsSignature: state.useFileVersionAsSignature,
116652             };
116653         }
116654         BuilderState.clone = clone;
116655         /**
116656          * Gets the files affected by the path from the program
116657          */
116658         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
116659             // Since the operation could be cancelled, the signatures are always stored in the cache
116660             // They will be committed once it is safe to use them
116661             // eg when calling this api from tsserver, if there is no cancellation of the operation
116662             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
116663             var signatureCache = cacheToUpdateSignature || new ts.Map();
116664             var sourceFile = programOfThisState.getSourceFileByPath(path);
116665             if (!sourceFile) {
116666                 return ts.emptyArray;
116667             }
116668             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
116669                 return [sourceFile];
116670             }
116671             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
116672             if (!cacheToUpdateSignature) {
116673                 // Commit all the signatures in the signature cache
116674                 updateSignaturesFromCache(state, signatureCache);
116675             }
116676             return result;
116677         }
116678         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
116679         /**
116680          * Updates the signatures from the cache into state's fileinfo signatures
116681          * This should be called whenever it is safe to commit the state of the builder
116682          */
116683         function updateSignaturesFromCache(state, signatureCache) {
116684             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
116685         }
116686         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
116687         function updateSignatureOfFile(state, signature, path) {
116688             state.fileInfos.get(path).signature = signature;
116689             state.hasCalledUpdateShapeSignature.add(path);
116690         }
116691         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
116692         /**
116693          * Returns if the shape of the signature has changed since last emit
116694          */
116695         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) {
116696             if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; }
116697             ts.Debug.assert(!!sourceFile);
116698             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
116699             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
116700             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
116701                 return false;
116702             }
116703             var info = state.fileInfos.get(sourceFile.resolvedPath);
116704             if (!info)
116705                 return ts.Debug.fail();
116706             var prevSignature = info.signature;
116707             var latestSignature;
116708             if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) {
116709                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
116710                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
116711                 /*customTransformers*/ undefined, 
116712                 /*forceDtsEmit*/ true);
116713                 var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles);
116714                 if (firstDts_1) {
116715                     ts.Debug.assert(ts.fileExtensionIsOneOf(firstDts_1.name, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); });
116716                     latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text);
116717                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
116718                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
116719                     }
116720                 }
116721             }
116722             // Default is to use file version as signature
116723             if (latestSignature === undefined) {
116724                 latestSignature = sourceFile.version;
116725                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
116726                     // All the references in this file are exported
116727                     var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined;
116728                     if (references) {
116729                         exportedModulesMapCache.set(sourceFile.resolvedPath, references);
116730                     }
116731                     else {
116732                         exportedModulesMapCache.deleteKey(sourceFile.resolvedPath);
116733                     }
116734                 }
116735             }
116736             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
116737             return latestSignature !== prevSignature;
116738         }
116739         BuilderState.updateShapeSignature = updateShapeSignature;
116740         /**
116741          * Coverts the declaration emit result into exported modules map
116742          */
116743         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
116744             if (!exportedModulesFromDeclarationEmit) {
116745                 exportedModulesMapCache.deleteKey(sourceFile.resolvedPath);
116746                 return;
116747             }
116748             var exportedModules;
116749             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); });
116750             if (exportedModules) {
116751                 exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules);
116752             }
116753             else {
116754                 exportedModulesMapCache.deleteKey(sourceFile.resolvedPath);
116755             }
116756             function addExportedModule(exportedModulePaths) {
116757                 if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) {
116758                     if (!exportedModules) {
116759                         exportedModules = new ts.Set();
116760                     }
116761                     exportedModulePaths.forEach(function (path) { return exportedModules.add(path); });
116762                 }
116763             }
116764         }
116765         /**
116766          * Updates the exported modules from cache into state's exported modules map
116767          * This should be called whenever it is safe to commit the state of the builder
116768          */
116769         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
116770             var _a;
116771             if (exportedModulesMapCache) {
116772                 ts.Debug.assert(!!state.exportedModulesMap);
116773                 var cacheId = exportedModulesMapCache.id;
116774                 var cacheVersion = exportedModulesMapCache.version();
116775                 if (state.previousCache) {
116776                     if (state.previousCache.id === cacheId && state.previousCache.version === cacheVersion) {
116777                         // If this is the same cache at the same version as last time this BuilderState
116778                         // was updated, there's no need to update again
116779                         return;
116780                     }
116781                     state.previousCache.id = cacheId;
116782                     state.previousCache.version = cacheVersion;
116783                 }
116784                 else {
116785                     state.previousCache = { id: cacheId, version: cacheVersion };
116786                 }
116787                 (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); });
116788                 exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); });
116789             }
116790         }
116791         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
116792         /**
116793          * Get all the dependencies of the sourceFile
116794          */
116795         function getAllDependencies(state, programOfThisState, sourceFile) {
116796             var compilerOptions = programOfThisState.getCompilerOptions();
116797             // With --out or --outFile all outputs go into single file, all files depend on each other
116798             if (ts.outFile(compilerOptions)) {
116799                 return getAllFileNames(state, programOfThisState);
116800             }
116801             // If this is non module emit, or its a global file, it depends on all the source files
116802             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
116803                 return getAllFileNames(state, programOfThisState);
116804             }
116805             // Get the references, traversing deep from the referenceMap
116806             var seenMap = new ts.Set();
116807             var queue = [sourceFile.resolvedPath];
116808             while (queue.length) {
116809                 var path = queue.pop();
116810                 if (!seenMap.has(path)) {
116811                     seenMap.add(path);
116812                     var references = state.referencedMap.getValues(path);
116813                     if (references) {
116814                         var iterator = references.keys();
116815                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
116816                             queue.push(iterResult.value);
116817                         }
116818                     }
116819                 }
116820             }
116821             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; }));
116822         }
116823         BuilderState.getAllDependencies = getAllDependencies;
116824         /**
116825          * Gets the names of all files from the program
116826          */
116827         function getAllFileNames(state, programOfThisState) {
116828             if (!state.allFileNames) {
116829                 var sourceFiles = programOfThisState.getSourceFiles();
116830                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
116831             }
116832             return state.allFileNames;
116833         }
116834         /**
116835          * Gets the files referenced by the the file path
116836          */
116837         function getReferencedByPaths(state, referencedFilePath) {
116838             var keys = state.referencedMap.getKeys(referencedFilePath);
116839             return keys ? ts.arrayFrom(keys.keys()) : [];
116840         }
116841         BuilderState.getReferencedByPaths = getReferencedByPaths;
116842         /**
116843          * For script files that contains only ambient external modules, although they are not actually external module files,
116844          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
116845          * there are no point to rebuild all script files if these special files have changed. However, if any statement
116846          * in the file is not ambient external module, we treat it as a regular script file.
116847          */
116848         function containsOnlyAmbientModules(sourceFile) {
116849             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
116850                 var statement = _a[_i];
116851                 if (!ts.isModuleWithStringLiteralName(statement)) {
116852                     return false;
116853                 }
116854             }
116855             return true;
116856         }
116857         /**
116858          * Return true if file contains anything that augments to global scope we need to build them as if
116859          * they are global files as well as module
116860          */
116861         function containsGlobalScopeAugmentation(sourceFile) {
116862             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
116863         }
116864         /**
116865          * Return true if the file will invalidate all files because it affectes global scope
116866          */
116867         function isFileAffectingGlobalScope(sourceFile) {
116868             return containsGlobalScopeAugmentation(sourceFile) ||
116869                 !ts.isExternalOrCommonJsModule(sourceFile) && !ts.isJsonSourceFile(sourceFile) && !containsOnlyAmbientModules(sourceFile);
116870         }
116871         /**
116872          * Gets all files of the program excluding the default library file
116873          */
116874         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
116875             // Use cached result
116876             if (state.allFilesExcludingDefaultLibraryFile) {
116877                 return state.allFilesExcludingDefaultLibraryFile;
116878             }
116879             var result;
116880             if (firstSourceFile)
116881                 addSourceFile(firstSourceFile);
116882             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
116883                 var sourceFile = _a[_i];
116884                 if (sourceFile !== firstSourceFile) {
116885                     addSourceFile(sourceFile);
116886                 }
116887             }
116888             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
116889             return state.allFilesExcludingDefaultLibraryFile;
116890             function addSourceFile(sourceFile) {
116891                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
116892                     (result || (result = [])).push(sourceFile);
116893                 }
116894             }
116895         }
116896         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
116897         /**
116898          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
116899          */
116900         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
116901             var compilerOptions = programOfThisState.getCompilerOptions();
116902             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
116903             // so returning the file itself is good enough.
116904             if (compilerOptions && ts.outFile(compilerOptions)) {
116905                 return [sourceFileWithUpdatedShape];
116906             }
116907             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
116908         }
116909         /**
116910          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
116911          */
116912         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
116913             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
116914                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
116915             }
116916             var compilerOptions = programOfThisState.getCompilerOptions();
116917             if (compilerOptions && (compilerOptions.isolatedModules || ts.outFile(compilerOptions))) {
116918                 return [sourceFileWithUpdatedShape];
116919             }
116920             // Now we need to if each file in the referencedBy list has a shape change as well.
116921             // Because if so, its own referencedBy files need to be saved as well to make the
116922             // emitting result consistent with files on disk.
116923             var seenFileNamesMap = new ts.Map();
116924             // Start with the paths this file was referenced by
116925             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
116926             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
116927             while (queue.length > 0) {
116928                 var currentPath = queue.pop();
116929                 if (!seenFileNamesMap.has(currentPath)) {
116930                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
116931                     seenFileNamesMap.set(currentPath, currentSourceFile);
116932                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) {
116933                         queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
116934                     }
116935                 }
116936             }
116937             // Return array of values that needs emit
116938             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
116939         }
116940     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
116941 })(ts || (ts = {}));
116942 /*@internal*/
116943 var ts;
116944 (function (ts) {
116945     var BuilderFileEmit;
116946     (function (BuilderFileEmit) {
116947         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
116948         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
116949     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
116950     function hasSameKeys(map1, map2) {
116951         // Has same size and every key is present in both maps
116952         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
116953     }
116954     /**
116955      * Create the state so that we can iterate on changedFiles/affected files
116956      */
116957     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) {
116958         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature);
116959         state.program = newProgram;
116960         var compilerOptions = newProgram.getCompilerOptions();
116961         state.compilerOptions = compilerOptions;
116962         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
116963         if (!ts.outFile(compilerOptions)) {
116964             state.semanticDiagnosticsPerFile = new ts.Map();
116965         }
116966         state.changedFilesSet = new ts.Set();
116967         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
116968         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
116969         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
116970             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
116971         if (useOldState) {
116972             // Verify the sanity of old state
116973             if (!oldState.currentChangedFilePath) {
116974                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
116975                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
116976             }
116977             var changedFilesSet = oldState.changedFilesSet;
116978             if (canCopySemanticDiagnostics) {
116979                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
116980             }
116981             // Copy old state's changed files set
116982             changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); });
116983             if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) {
116984                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
116985                 state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind);
116986                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
116987                 state.seenAffectedFiles = new ts.Set();
116988             }
116989         }
116990         // Update changed files and copy semantic diagnostics if we can
116991         var referencedMap = state.referencedMap;
116992         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
116993         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
116994         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
116995         state.fileInfos.forEach(function (info, sourceFilePath) {
116996             var oldInfo;
116997             var newReferences;
116998             // if not using old state, every file is changed
116999             if (!useOldState ||
117000                 // File wasn't present in old state
117001                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
117002                 // versions dont match
117003                 oldInfo.version !== info.version ||
117004                 // Referenced files changed
117005                 !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) ||
117006                 // Referenced file was deleted in the new program
117007                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
117008                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
117009                 state.changedFilesSet.add(sourceFilePath);
117010             }
117011             else if (canCopySemanticDiagnostics) {
117012                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
117013                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics)
117014                     return;
117015                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics)
117016                     return;
117017                 // Unchanged file copy diagnostics
117018                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
117019                 if (diagnostics) {
117020                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
117021                     if (!state.semanticDiagnosticsFromOldState) {
117022                         state.semanticDiagnosticsFromOldState = new ts.Set();
117023                     }
117024                     state.semanticDiagnosticsFromOldState.add(sourceFilePath);
117025                 }
117026             }
117027         });
117028         // If the global file is removed, add all files as changed
117029         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
117030             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
117031                 .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); });
117032         }
117033         else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
117034             // Add all files to affectedFilesPendingEmit since emit changed
117035             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
117036             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
117037             state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set();
117038         }
117039         if (useOldState) {
117040             // Any time the interpretation of a source file changes, mark it as changed
117041             ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) {
117042                 if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) {
117043                     state.changedFilesSet.add(sourceFilePath);
117044                 }
117045             });
117046         }
117047         state.buildInfoEmitPending = !!state.changedFilesSet.size;
117048         return state;
117049     }
117050     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
117051         if (!diagnostics.length)
117052             return ts.emptyArray;
117053         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
117054         return diagnostics.map(function (diagnostic) {
117055             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
117056             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
117057             result.reportsDeprecated = diagnostic.reportDeprecated;
117058             result.source = diagnostic.source;
117059             result.skippedOn = diagnostic.skippedOn;
117060             var relatedInformation = diagnostic.relatedInformation;
117061             result.relatedInformation = relatedInformation ?
117062                 relatedInformation.length ?
117063                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
117064                     [] :
117065                 undefined;
117066             return result;
117067         });
117068         function toPath(path) {
117069             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
117070         }
117071     }
117072     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
117073         var file = diagnostic.file;
117074         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
117075     }
117076     /**
117077      * Releases program and other related not needed properties
117078      */
117079     function releaseCache(state) {
117080         ts.BuilderState.releaseCache(state);
117081         state.program = undefined;
117082     }
117083     /**
117084      * Creates a clone of the state
117085      */
117086     function cloneBuilderProgramState(state) {
117087         var _a;
117088         var newState = ts.BuilderState.clone(state);
117089         newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile);
117090         newState.changedFilesSet = new ts.Set(state.changedFilesSet);
117091         newState.affectedFiles = state.affectedFiles;
117092         newState.affectedFilesIndex = state.affectedFilesIndex;
117093         newState.currentChangedFilePath = state.currentChangedFilePath;
117094         newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures);
117095         newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone();
117096         newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles);
117097         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
117098         newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState);
117099         newState.program = state.program;
117100         newState.compilerOptions = state.compilerOptions;
117101         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
117102         newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
117103         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
117104         newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles);
117105         newState.programEmitComplete = state.programEmitComplete;
117106         return newState;
117107     }
117108     /**
117109      * Verifies that source file is ok to be used in calls that arent handled by next
117110      */
117111     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
117112         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
117113     }
117114     /**
117115      * This function returns the next affected file to be processed.
117116      * Note that until doneAffected is called it would keep reporting same result
117117      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
117118      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
117119      */
117120     function getNextAffectedFile(state, cancellationToken, computeHash) {
117121         while (true) {
117122             var affectedFiles = state.affectedFiles;
117123             if (affectedFiles) {
117124                 var seenAffectedFiles = state.seenAffectedFiles;
117125                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
117126                 while (affectedFilesIndex < affectedFiles.length) {
117127                     var affectedFile = affectedFiles[affectedFilesIndex];
117128                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
117129                         // Set the next affected file as seen and remove the cached semantic diagnostics
117130                         state.affectedFilesIndex = affectedFilesIndex;
117131                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
117132                         return affectedFile;
117133                     }
117134                     affectedFilesIndex++;
117135                 }
117136                 // Remove the changed file from the change set
117137                 state.changedFilesSet.delete(state.currentChangedFilePath);
117138                 state.currentChangedFilePath = undefined;
117139                 // Commit the changes in file signature
117140                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
117141                 state.currentAffectedFilesSignatures.clear();
117142                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
117143                 state.affectedFiles = undefined;
117144             }
117145             // Get next changed file
117146             var nextKey = state.changedFilesSet.keys().next();
117147             if (nextKey.done) {
117148                 // Done
117149                 return undefined;
117150             }
117151             // With --out or --outFile all outputs go into single file
117152             // so operations are performed directly on program, return program
117153             var program = ts.Debug.checkDefined(state.program);
117154             var compilerOptions = program.getCompilerOptions();
117155             if (ts.outFile(compilerOptions)) {
117156                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
117157                 return program;
117158             }
117159             // Get next batch of affected files
117160             if (!state.currentAffectedFilesSignatures)
117161                 state.currentAffectedFilesSignatures = new ts.Map();
117162             if (state.exportedModulesMap) {
117163                 state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap());
117164             }
117165             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
117166             state.currentChangedFilePath = nextKey.value;
117167             state.affectedFilesIndex = 0;
117168             if (!state.seenAffectedFiles)
117169                 state.seenAffectedFiles = new ts.Set();
117170         }
117171     }
117172     /**
117173      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
117174      */
117175     function getNextAffectedFilePendingEmit(state) {
117176         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
117177         if (affectedFilesPendingEmit) {
117178             var seenEmittedFiles = (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map()));
117179             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
117180                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
117181                 if (affectedFile) {
117182                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
117183                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
117184                     if (seenKind === undefined || seenKind < emitKind) {
117185                         // emit this file
117186                         state.affectedFilesPendingEmitIndex = i;
117187                         return { affectedFile: affectedFile, emitKind: emitKind };
117188                     }
117189                 }
117190             }
117191             state.affectedFilesPendingEmit = undefined;
117192             state.affectedFilesPendingEmitKind = undefined;
117193             state.affectedFilesPendingEmitIndex = undefined;
117194         }
117195         return undefined;
117196     }
117197     /**
117198      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
117199      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
117200      */
117201     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
117202         var _a;
117203         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
117204         // If affected files is everything except default library, then nothing more to do
117205         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
117206             if (!state.cleanedDiagnosticsOfLibFiles) {
117207                 state.cleanedDiagnosticsOfLibFiles = true;
117208                 var program_1 = ts.Debug.checkDefined(state.program);
117209                 var options_2 = program_1.getCompilerOptions();
117210                 ts.forEach(program_1.getSourceFiles(), function (f) {
117211                     return program_1.isSourceFileDefaultLibrary(f) &&
117212                         !ts.skipTypeChecking(f, options_2, program_1) &&
117213                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
117214                 });
117215             }
117216             // When a change affects the global scope, all files are considered to be affected without updating their signature
117217             // That means when affected file is handled, its signature can be out of date
117218             // To avoid this, ensure that we update the signature for any affected file in this scenario.
117219             ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
117220             return;
117221         }
117222         else {
117223             ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName));
117224         }
117225         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
117226             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
117227         }
117228     }
117229     /**
117230      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
117231      * Also we need to make sure signature is updated for these files
117232      */
117233     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
117234         removeSemanticDiagnosticsOf(state, path);
117235         if (!state.changedFilesSet.has(path)) {
117236             var program = ts.Debug.checkDefined(state.program);
117237             var sourceFile = program.getSourceFileByPath(path);
117238             if (sourceFile) {
117239                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
117240                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
117241                 // This ensures that we dont later during incremental builds considering wrong signature.
117242                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
117243                 // But we avoid expensive full shape computation, as using file version as shape is enough for correctness.
117244                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, 
117245                 /* useFileVersionAsSignature */ true);
117246                 // If not dts emit, nothing more to do
117247                 if (ts.getEmitDeclarations(state.compilerOptions)) {
117248                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
117249                 }
117250             }
117251         }
117252     }
117253     /**
117254      * Removes semantic diagnostics for path and
117255      * returns true if there are no more semantic diagnostics from the old state
117256      */
117257     function removeSemanticDiagnosticsOf(state, path) {
117258         if (!state.semanticDiagnosticsFromOldState) {
117259             return true;
117260         }
117261         state.semanticDiagnosticsFromOldState.delete(path);
117262         state.semanticDiagnosticsPerFile.delete(path);
117263         return !state.semanticDiagnosticsFromOldState.size;
117264     }
117265     function isChangedSignature(state, path) {
117266         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
117267         var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
117268         return newSignature !== oldSignature;
117269     }
117270     /**
117271      * Iterate on referencing modules that export entities from affected file
117272      */
117273     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
117274         var _a, _b;
117275         // If there was change in signature (dts output) for the changed file,
117276         // then only we need to handle pending file emit
117277         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
117278             return;
117279         }
117280         if (!isChangedSignature(state, affectedFile.resolvedPath))
117281             return;
117282         // Since isolated modules dont change js files, files affected by change in signature is itself
117283         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
117284         if (state.compilerOptions.isolatedModules) {
117285             var seenFileNamesMap = new ts.Map();
117286             seenFileNamesMap.set(affectedFile.resolvedPath, true);
117287             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
117288             while (queue.length > 0) {
117289                 var currentPath = queue.pop();
117290                 if (!seenFileNamesMap.has(currentPath)) {
117291                     seenFileNamesMap.set(currentPath, true);
117292                     fn(state, currentPath);
117293                     if (isChangedSignature(state, currentPath)) {
117294                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
117295                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
117296                     }
117297                 }
117298             }
117299         }
117300         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
117301         var seenFileAndExportsOfFile = new ts.Set();
117302         // Go through exported modules from cache first
117303         // If exported modules has path, all files referencing file exported from are affected
117304         (_a = state.currentAffectedFilesExportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) {
117305             return forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
117306         });
117307         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
117308         (_b = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.forEach(function (exportedFromPath) {
117309             var _a;
117310             // If the cache had an updated value, skip
117311             return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) &&
117312                 !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) &&
117313                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
117314         });
117315     }
117316     /**
117317      * Iterate on files referencing referencedPath
117318      */
117319     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
117320         var _a;
117321         (_a = state.referencedMap.getKeys(referencedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (filePath) {
117322             return forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
117323         });
117324     }
117325     /**
117326      * fn on file and iterate on anything that exports this file
117327      */
117328     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
117329         var _a, _b, _c;
117330         if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
117331             return;
117332         }
117333         fn(state, filePath);
117334         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
117335         // Go through exported modules from cache first
117336         // If exported modules has path, all files referencing file exported from are affected
117337         (_a = state.currentAffectedFilesExportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) {
117338             return forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
117339         });
117340         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
117341         (_b = state.exportedModulesMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (exportedFromPath) {
117342             var _a;
117343             // If the cache had an updated value, skip
117344             return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) &&
117345                 !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) &&
117346                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
117347         });
117348         // Remove diagnostics of files that import this file (without going to exports of referencing files)
117349         (_c = state.referencedMap.getKeys(filePath)) === null || _c === void 0 ? void 0 : _c.forEach(function (referencingFilePath) {
117350             return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
117351                 fn(state, referencingFilePath);
117352         } // Dont add to seen since this is not yet done with the export removal
117353         );
117354     }
117355     /**
117356      * This is called after completing operation on the next affected file.
117357      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
117358      */
117359     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
117360         if (isBuildInfoEmit) {
117361             state.buildInfoEmitPending = false;
117362         }
117363         else if (affected === state.program) {
117364             state.changedFilesSet.clear();
117365             state.programEmitComplete = true;
117366         }
117367         else {
117368             state.seenAffectedFiles.add(affected.resolvedPath);
117369             if (emitKind !== undefined) {
117370                 (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind);
117371             }
117372             if (isPendingEmit) {
117373                 state.affectedFilesPendingEmitIndex++;
117374                 state.buildInfoEmitPending = true;
117375             }
117376             else {
117377                 state.affectedFilesIndex++;
117378             }
117379         }
117380     }
117381     /**
117382      * Returns the result with affected file
117383      */
117384     function toAffectedFileResult(state, result, affected) {
117385         doneWithAffectedFile(state, affected);
117386         return { result: result, affected: affected };
117387     }
117388     /**
117389      * Returns the result with affected file
117390      */
117391     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
117392         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
117393         return { result: result, affected: affected };
117394     }
117395     /**
117396      * Gets semantic diagnostics for the file which are
117397      * bindAndCheckDiagnostics (from cache) and program diagnostics
117398      */
117399     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
117400         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
117401     }
117402     /**
117403      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
117404      * 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
117405      */
117406     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
117407         var path = sourceFile.resolvedPath;
117408         if (state.semanticDiagnosticsPerFile) {
117409             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
117410             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
117411             if (cachedDiagnostics) {
117412                 return ts.filterSemanticDiagnostics(cachedDiagnostics, state.compilerOptions);
117413             }
117414         }
117415         // Diagnostics werent cached, get them from program, and cache the result
117416         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
117417         if (state.semanticDiagnosticsPerFile) {
117418             state.semanticDiagnosticsPerFile.set(path, diagnostics);
117419         }
117420         return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions);
117421     }
117422     /**
117423      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
117424      */
117425     function getProgramBuildInfo(state, getCanonicalFileName) {
117426         if (ts.outFile(state.compilerOptions))
117427             return undefined;
117428         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
117429         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
117430         var fileNames = [];
117431         var fileNameToFileId = new ts.Map();
117432         var fileIdsList;
117433         var fileNamesToFileIdListId;
117434         var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) {
117435             var key = _a[0], value = _a[1];
117436             // Ensure fileId
117437             var fileId = toFileId(key);
117438             ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key));
117439             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
117440             var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature;
117441             return value.version === actualSignature ?
117442                 value.affectsGlobalScope ?
117443                     { version: value.version, signature: undefined, affectsGlobalScope: true, impliedFormat: value.impliedFormat } :
117444                     value.version :
117445                 actualSignature !== undefined ?
117446                     signature === undefined ?
117447                         value :
117448                         { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } :
117449                     { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat };
117450         });
117451         var referencedMap;
117452         if (state.referencedMap) {
117453             referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [
117454                 toFileId(key),
117455                 toFileIdListId(state.referencedMap.getValues(key))
117456             ]; });
117457         }
117458         var exportedModulesMap;
117459         if (state.exportedModulesMap) {
117460             exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) {
117461                 var _a;
117462                 if (state.currentAffectedFilesExportedModulesMap) {
117463                     if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) {
117464                         return undefined;
117465                     }
117466                     var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key);
117467                     if (newValue) {
117468                         return [toFileId(key), toFileIdListId(newValue)];
117469                     }
117470                 }
117471                 // Not in temporary cache, use existing value
117472                 return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))];
117473             });
117474         }
117475         var semanticDiagnosticsPerFile;
117476         if (state.semanticDiagnosticsPerFile) {
117477             for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
117478                 var key = _a[_i];
117479                 var value = state.semanticDiagnosticsPerFile.get(key);
117480                 (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ?
117481                     [
117482                         toFileId(key),
117483                         state.hasReusableDiagnostic ?
117484                             value :
117485                             convertToReusableDiagnostics(value, relativeToBuildInfo)
117486                     ] :
117487                     toFileId(key));
117488             }
117489         }
117490         var affectedFilesPendingEmit;
117491         if (state.affectedFilesPendingEmit) {
117492             var seenFiles = new ts.Set();
117493             for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
117494                 var path = _c[_b];
117495                 if (ts.tryAddToSet(seenFiles, path)) {
117496                     (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]);
117497                 }
117498             }
117499         }
117500         return {
117501             fileNames: fileNames,
117502             fileInfos: fileInfos,
117503             options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath),
117504             fileIdsList: fileIdsList,
117505             referencedMap: referencedMap,
117506             exportedModulesMap: exportedModulesMap,
117507             semanticDiagnosticsPerFile: semanticDiagnosticsPerFile,
117508             affectedFilesPendingEmit: affectedFilesPendingEmit,
117509         };
117510         function relativeToBuildInfoEnsuringAbsolutePath(path) {
117511             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
117512         }
117513         function relativeToBuildInfo(path) {
117514             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
117515         }
117516         function toFileId(path) {
117517             var fileId = fileNameToFileId.get(path);
117518             if (fileId === undefined) {
117519                 fileNames.push(relativeToBuildInfo(path));
117520                 fileNameToFileId.set(path, fileId = fileNames.length);
117521             }
117522             return fileId;
117523         }
117524         function toFileIdListId(set) {
117525             var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues);
117526             var key = fileIds.join();
117527             var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key);
117528             if (fileIdListId === undefined) {
117529                 (fileIdsList || (fileIdsList = [])).push(fileIds);
117530                 (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length);
117531             }
117532             return fileIdListId;
117533         }
117534     }
117535     function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) {
117536         var result;
117537         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
117538         for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
117539             var name = _a[_i];
117540             var optionKey = name.toLowerCase();
117541             var optionInfo = optionsNameMap.get(optionKey);
117542             if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) ||
117543                 // We need to store `strict`, even though it won't be examined directly, so that the
117544                 // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo
117545                 optionKey === "strict" ||
117546                 // We need to store these to determine whether `lib` files need to be rechecked.
117547                 optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") {
117548                 (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo);
117549             }
117550         }
117551         return result;
117552     }
117553     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
117554         if (option) {
117555             if (option.type === "list") {
117556                 var values = value;
117557                 if (option.element.isFilePath && values.length) {
117558                     return values.map(relativeToBuildInfo);
117559                 }
117560             }
117561             else if (option.isFilePath) {
117562                 return relativeToBuildInfo(value);
117563             }
117564         }
117565         return value;
117566     }
117567     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
117568         ts.Debug.assert(!!diagnostics.length);
117569         return diagnostics.map(function (diagnostic) {
117570             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
117571             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
117572             result.reportDeprecated = diagnostic.reportsDeprecated;
117573             result.source = diagnostic.source;
117574             result.skippedOn = diagnostic.skippedOn;
117575             var relatedInformation = diagnostic.relatedInformation;
117576             result.relatedInformation = relatedInformation ?
117577                 relatedInformation.length ?
117578                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
117579                     [] :
117580                 undefined;
117581             return result;
117582         });
117583     }
117584     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
117585         var file = diagnostic.file;
117586         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
117587     }
117588     var BuilderProgramKind;
117589     (function (BuilderProgramKind) {
117590         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
117591         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
117592     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
117593     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
117594         var host;
117595         var newProgram;
117596         var oldProgram;
117597         if (newProgramOrRootNames === undefined) {
117598             ts.Debug.assert(hostOrOptions === undefined);
117599             host = oldProgramOrHost;
117600             oldProgram = configFileParsingDiagnosticsOrOldProgram;
117601             ts.Debug.assert(!!oldProgram);
117602             newProgram = oldProgram.getProgram();
117603         }
117604         else if (ts.isArray(newProgramOrRootNames)) {
117605             oldProgram = configFileParsingDiagnosticsOrOldProgram;
117606             newProgram = ts.createProgram({
117607                 rootNames: newProgramOrRootNames,
117608                 options: hostOrOptions,
117609                 host: oldProgramOrHost,
117610                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
117611                 configFileParsingDiagnostics: configFileParsingDiagnostics,
117612                 projectReferences: projectReferences
117613             });
117614             host = oldProgramOrHost;
117615         }
117616         else {
117617             newProgram = newProgramOrRootNames;
117618             host = hostOrOptions;
117619             oldProgram = oldProgramOrHost;
117620             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
117621         }
117622         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
117623     }
117624     ts.getBuilderCreationParameters = getBuilderCreationParameters;
117625     function createBuilderProgram(kind, _a) {
117626         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
117627         // Return same program if underlying program doesnt change
117628         var oldState = oldProgram && oldProgram.getState();
117629         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
117630             newProgram = undefined; // TODO: GH#18217
117631             oldState = undefined;
117632             return oldProgram;
117633         }
117634         /**
117635          * Create the canonical file name for identity
117636          */
117637         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
117638         /**
117639          * Computing hash to for signature verification
117640          */
117641         var computeHash = ts.maybeBind(host, host.createHash);
117642         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature);
117643         var backupState;
117644         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
117645         // To ensure that we arent storing any references to old program or new program without state
117646         newProgram = undefined; // TODO: GH#18217
117647         oldProgram = undefined;
117648         oldState = undefined;
117649         var getState = function () { return state; };
117650         var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics);
117651         builderProgram.getState = getState;
117652         builderProgram.backupState = function () {
117653             ts.Debug.assert(backupState === undefined);
117654             backupState = cloneBuilderProgramState(state);
117655         };
117656         builderProgram.restoreState = function () {
117657             state = ts.Debug.checkDefined(backupState);
117658             backupState = undefined;
117659         };
117660         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
117661         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
117662         builderProgram.emit = emit;
117663         builderProgram.releaseProgram = function () {
117664             releaseCache(state);
117665             backupState = undefined;
117666         };
117667         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
117668             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
117669         }
117670         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
117671             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
117672             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
117673             builderProgram.emitBuildInfo = emitBuildInfo;
117674         }
117675         else {
117676             ts.notImplemented();
117677         }
117678         return builderProgram;
117679         function emitBuildInfo(writeFile, cancellationToken) {
117680             if (state.buildInfoEmitPending) {
117681                 var result = ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken);
117682                 state.buildInfoEmitPending = false;
117683                 return result;
117684             }
117685             return ts.emitSkippedWithNoDiagnostics;
117686         }
117687         /**
117688          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
117689          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
117690          * in that order would be used to write the files
117691          */
117692         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
117693             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
117694             var emitKind = 1 /* Full */;
117695             var isPendingEmitFile = false;
117696             if (!affected) {
117697                 if (!ts.outFile(state.compilerOptions)) {
117698                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
117699                     if (!pendingAffectedFile) {
117700                         if (!state.buildInfoEmitPending) {
117701                             return undefined;
117702                         }
117703                         var affected_1 = ts.Debug.checkDefined(state.program);
117704                         return toAffectedFileEmitResult(state, 
117705                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
117706                         // Otherwise just affected file
117707                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
117708                         /*isPendingEmitFile*/ false, 
117709                         /*isBuildInfoEmit*/ true);
117710                     }
117711                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
117712                     isPendingEmitFile = true;
117713                 }
117714                 else {
117715                     var program = ts.Debug.checkDefined(state.program);
117716                     if (state.programEmitComplete)
117717                         return undefined;
117718                     affected = program;
117719                 }
117720             }
117721             return toAffectedFileEmitResult(state, 
117722             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
117723             // Otherwise just affected file
117724             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);
117725         }
117726         /**
117727          * Emits the JavaScript and declaration files.
117728          * When targetSource file is specified, emits the files corresponding to that source file,
117729          * otherwise for the whole program.
117730          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
117731          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
117732          * it will only emit all the affected files instead of whole program
117733          *
117734          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
117735          * in that order would be used to write the files
117736          */
117737         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
117738             var restorePendingEmitOnHandlingNoEmitSuccess = false;
117739             var savedAffectedFilesPendingEmit;
117740             var savedAffectedFilesPendingEmitKind;
117741             var savedAffectedFilesPendingEmitIndex;
117742             // 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
117743             // This ensures pending files to emit is updated in tsbuildinfo
117744             // 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)
117745             if (kind !== BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
117746                 !targetSourceFile &&
117747                 !ts.outFile(state.compilerOptions) &&
117748                 !state.compilerOptions.noEmit &&
117749                 state.compilerOptions.noEmitOnError) {
117750                 restorePendingEmitOnHandlingNoEmitSuccess = true;
117751                 savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
117752                 savedAffectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
117753                 savedAffectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
117754             }
117755             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
117756                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
117757             }
117758             var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, writeFile, cancellationToken);
117759             if (result)
117760                 return result;
117761             if (restorePendingEmitOnHandlingNoEmitSuccess) {
117762                 state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
117763                 state.affectedFilesPendingEmitKind = savedAffectedFilesPendingEmitKind;
117764                 state.affectedFilesPendingEmitIndex = savedAffectedFilesPendingEmitIndex;
117765             }
117766             // Emit only affected files if using builder for emit
117767             if (!targetSourceFile && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
117768                 // Emit and report any errors we ran into.
117769                 var sourceMaps = [];
117770                 var emitSkipped = false;
117771                 var diagnostics = void 0;
117772                 var emittedFiles = [];
117773                 var affectedEmitResult = void 0;
117774                 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
117775                     emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
117776                     diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
117777                     emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
117778                     sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
117779                 }
117780                 return {
117781                     emitSkipped: emitSkipped,
117782                     diagnostics: diagnostics || ts.emptyArray,
117783                     emittedFiles: emittedFiles,
117784                     sourceMaps: sourceMaps
117785                 };
117786             }
117787             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
117788         }
117789         /**
117790          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
117791          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
117792          */
117793         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
117794             while (true) {
117795                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
117796                 if (!affected) {
117797                     // Done
117798                     return undefined;
117799                 }
117800                 else if (affected === state.program) {
117801                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
117802                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
117803                 }
117804                 // Add file to affected file pending emit to handle for later emit time
117805                 // 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
117806                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram || state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
117807                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
117808                 }
117809                 // Get diagnostics for the affected file if its not ignored
117810                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
117811                     // Get next affected file
117812                     doneWithAffectedFile(state, affected);
117813                     continue;
117814                 }
117815                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
117816             }
117817         }
117818         /**
117819          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
117820          * The semantic diagnostics are cached and managed here
117821          * Note that it is assumed that when asked about semantic diagnostics through this API,
117822          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
117823          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
117824          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
117825          */
117826         function getSemanticDiagnostics(sourceFile, cancellationToken) {
117827             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
117828             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
117829             if (ts.outFile(compilerOptions)) {
117830                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
117831                 // We dont need to cache the diagnostics just return them from program
117832                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
117833             }
117834             if (sourceFile) {
117835                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
117836             }
117837             // When semantic builder asks for diagnostics of the whole program,
117838             // ensure that all the affected files are handled
117839             // eslint-disable-next-line no-empty
117840             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
117841             }
117842             var diagnostics;
117843             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
117844                 var sourceFile_1 = _a[_i];
117845                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
117846             }
117847             return diagnostics || ts.emptyArray;
117848         }
117849     }
117850     ts.createBuilderProgram = createBuilderProgram;
117851     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
117852         if (!state.affectedFilesPendingEmit)
117853             state.affectedFilesPendingEmit = [];
117854         if (!state.affectedFilesPendingEmitKind)
117855             state.affectedFilesPendingEmitKind = new ts.Map();
117856         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
117857         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
117858         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
117859         // affectedFilesPendingEmitIndex === undefined
117860         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
117861         //   so start from 0 as array would be affectedFilesPendingEmit
117862         // else, continue to iterate from existing index, the current set is appended to existing files
117863         if (state.affectedFilesPendingEmitIndex === undefined) {
117864             state.affectedFilesPendingEmitIndex = 0;
117865         }
117866     }
117867     function toBuilderStateFileInfo(fileInfo) {
117868         return ts.isString(fileInfo) ?
117869             { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined, impliedFormat: undefined } :
117870             ts.isString(fileInfo.signature) ?
117871                 fileInfo :
117872                 { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat };
117873     }
117874     ts.toBuilderStateFileInfo = toBuilderStateFileInfo;
117875     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
117876         var _a;
117877         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
117878         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
117879         var filePaths = program.fileNames.map(toPath);
117880         var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); });
117881         var fileInfos = new ts.Map();
117882         program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); });
117883         var state = {
117884             fileInfos: fileInfos,
117885             compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {},
117886             referencedMap: toManyToManyPathMap(program.referencedMap),
117887             exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap),
117888             semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }),
117889             hasReusableDiagnostic: true,
117890             affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }),
117891             affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }),
117892             affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
117893         };
117894         return {
117895             getState: function () { return state; },
117896             backupState: ts.noop,
117897             restoreState: ts.noop,
117898             getProgram: ts.notImplemented,
117899             getProgramOrUndefined: ts.returnUndefined,
117900             releaseProgram: ts.noop,
117901             getCompilerOptions: function () { return state.compilerOptions; },
117902             getSourceFile: ts.notImplemented,
117903             getSourceFiles: ts.notImplemented,
117904             getOptionsDiagnostics: ts.notImplemented,
117905             getGlobalDiagnostics: ts.notImplemented,
117906             getConfigFileParsingDiagnostics: ts.notImplemented,
117907             getSyntacticDiagnostics: ts.notImplemented,
117908             getDeclarationDiagnostics: ts.notImplemented,
117909             getSemanticDiagnostics: ts.notImplemented,
117910             emit: ts.notImplemented,
117911             getAllDependencies: ts.notImplemented,
117912             getCurrentDirectory: ts.notImplemented,
117913             emitNextAffectedFile: ts.notImplemented,
117914             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
117915             emitBuildInfo: ts.notImplemented,
117916             close: ts.noop,
117917         };
117918         function toPath(path) {
117919             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
117920         }
117921         function toAbsolutePath(path) {
117922             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
117923         }
117924         function toFilePath(fileId) {
117925             return filePaths[fileId - 1];
117926         }
117927         function toFilePathsSet(fileIdsListId) {
117928             return filePathsSetList[fileIdsListId - 1];
117929         }
117930         function toManyToManyPathMap(referenceMap) {
117931             if (!referenceMap) {
117932                 return undefined;
117933             }
117934             var map = ts.BuilderState.createManyToManyPathMap();
117935             referenceMap.forEach(function (_a) {
117936                 var fileId = _a[0], fileIdListId = _a[1];
117937                 return map.set(toFilePath(fileId), toFilePathsSet(fileIdListId));
117938             });
117939             return map;
117940         }
117941     }
117942     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
117943     function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) {
117944         return {
117945             getState: ts.notImplemented,
117946             backupState: ts.noop,
117947             restoreState: ts.noop,
117948             getProgram: getProgram,
117949             getProgramOrUndefined: function () { return getState().program; },
117950             releaseProgram: function () { return getState().program = undefined; },
117951             getCompilerOptions: function () { return getState().compilerOptions; },
117952             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
117953             getSourceFiles: function () { return getProgram().getSourceFiles(); },
117954             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
117955             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
117956             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
117957             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
117958             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
117959             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
117960             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
117961             emitBuildInfo: function (writeFile, cancellationToken) { return getProgram().emitBuildInfo(writeFile, cancellationToken); },
117962             getAllDependencies: ts.notImplemented,
117963             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
117964             close: ts.noop,
117965         };
117966         function getProgram() {
117967             return ts.Debug.checkDefined(getState().program);
117968         }
117969     }
117970     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
117971 })(ts || (ts = {}));
117972 var ts;
117973 (function (ts) {
117974     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
117975         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
117976     }
117977     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
117978     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
117979         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
117980     }
117981     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
117982     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
117983         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
117984         return ts.createRedirectedBuilderProgram(function () { return ({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }); }, newConfigFileParsingDiagnostics);
117985     }
117986     ts.createAbstractBuilder = createAbstractBuilder;
117987 })(ts || (ts = {}));
117988 /*@internal*/
117989 var ts;
117990 (function (ts) {
117991     function removeIgnoredPath(path) {
117992         // Consider whole staging folder as if node_modules changed.
117993         if (ts.endsWith(path, "/node_modules/.staging")) {
117994             return ts.removeSuffix(path, "/.staging");
117995         }
117996         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
117997             undefined :
117998             path;
117999     }
118000     ts.removeIgnoredPath = removeIgnoredPath;
118001     /**
118002      * Filter out paths like
118003      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
118004      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
118005      * @param dirPath
118006      */
118007     function canWatchDirectory(dirPath) {
118008         var rootLength = ts.getRootLength(dirPath);
118009         if (dirPath.length === rootLength) {
118010             // Ignore "/", "c:/"
118011             return false;
118012         }
118013         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
118014         if (nextDirectorySeparator === -1) {
118015             // ignore "/user", "c:/users" or "c:/folderAtRoot"
118016             return false;
118017         }
118018         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
118019         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
118020         if (isNonDirectorySeparatorRoot &&
118021             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
118022             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
118023             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
118024             if (nextDirectorySeparator === -1) {
118025                 // ignore "//vda1cs4850/c$/folderAtRoot"
118026                 return false;
118027             }
118028             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
118029         }
118030         if (isNonDirectorySeparatorRoot &&
118031             pathPartForUserCheck.search(/users\//i) !== 0) {
118032             // Paths like c:/folderAtRoot/subFolder are allowed
118033             return true;
118034         }
118035         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
118036             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
118037             if (searchIndex === 0) {
118038                 // Folder isnt at expected minimum levels
118039                 return false;
118040             }
118041         }
118042         return true;
118043     }
118044     ts.canWatchDirectory = canWatchDirectory;
118045     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
118046         var filesWithChangedSetOfUnresolvedImports;
118047         var filesWithInvalidatedResolutions;
118048         var filesWithInvalidatedNonRelativeUnresolvedImports;
118049         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
118050         var resolutionsWithFailedLookups = [];
118051         var resolvedFileToResolution = ts.createMultiMap();
118052         var hasChangedAutomaticTypeDirectiveNames = false;
118053         var failedLookupChecks;
118054         var startsWithPathChecks;
118055         var isInDirectoryChecks;
118056         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
118057         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
118058         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
118059         // The key in the map is source file's path.
118060         // The values are Map of resolutions with key being name lookedup.
118061         var resolvedModuleNames = new ts.Map();
118062         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
118063         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
118064         var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, 
118065         /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache);
118066         var resolvedTypeReferenceDirectives = new ts.Map();
118067         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
118068         var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, 
118069         /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives);
118070         /**
118071          * These are the extensions that failed lookup files will have by default,
118072          * any other extension of failed lookup will be store that path in custom failed lookup path
118073          * This helps in not having to comb through all resolutions when files are added/removed
118074          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
118075          */
118076         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
118077         var customFailedLookupPaths = new ts.Map();
118078         var directoryWatchesOfFailedLookups = new ts.Map();
118079         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
118080         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
118081         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
118082         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
118083         var typeRootsWatches = new ts.Map();
118084         return {
118085             getModuleResolutionCache: function () { return moduleResolutionCache; },
118086             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
118087             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
118088             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
118089             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
118090             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
118091             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
118092             resolveModuleNames: resolveModuleNames,
118093             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
118094             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
118095             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
118096             removeResolutionsOfFile: removeResolutionsOfFile,
118097             hasChangedAutomaticTypeDirectiveNames: function () { return hasChangedAutomaticTypeDirectiveNames; },
118098             invalidateResolutionOfFile: invalidateResolutionOfFile,
118099             invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
118100             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
118101             createHasInvalidatedResolution: createHasInvalidatedResolution,
118102             isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports,
118103             updateTypeRootsWatch: updateTypeRootsWatch,
118104             closeTypeRootsWatch: closeTypeRootsWatch,
118105             clear: clear
118106         };
118107         function getResolvedModule(resolution) {
118108             return resolution.resolvedModule;
118109         }
118110         function getResolvedTypeReferenceDirective(resolution) {
118111             return resolution.resolvedTypeReferenceDirective;
118112         }
118113         function isInDirectoryPath(dir, file) {
118114             if (dir === undefined || file.length <= dir.length) {
118115                 return false;
118116             }
118117             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
118118         }
118119         function clear() {
118120             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
118121             customFailedLookupPaths.clear();
118122             nonRelativeExternalModuleResolutions.clear();
118123             closeTypeRootsWatch();
118124             resolvedModuleNames.clear();
118125             resolvedTypeReferenceDirectives.clear();
118126             resolvedFileToResolution.clear();
118127             resolutionsWithFailedLookups.length = 0;
118128             failedLookupChecks = undefined;
118129             startsWithPathChecks = undefined;
118130             isInDirectoryChecks = undefined;
118131             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
118132             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
118133             clearPerDirectoryResolutions();
118134             hasChangedAutomaticTypeDirectiveNames = false;
118135         }
118136         function startRecordingFilesWithChangedResolutions() {
118137             filesWithChangedSetOfUnresolvedImports = [];
118138         }
118139         function finishRecordingFilesWithChangedResolutions() {
118140             var collected = filesWithChangedSetOfUnresolvedImports;
118141             filesWithChangedSetOfUnresolvedImports = undefined;
118142             return collected;
118143         }
118144         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
118145             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
118146                 return false;
118147             }
118148             // Invalidated if file has unresolved imports
118149             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
118150             return !!value && !!value.length;
118151         }
118152         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
118153             // Ensure pending resolutions are applied
118154             invalidateResolutionsOfFailedLookupLocations();
118155             if (forceAllFilesAsInvalidated) {
118156                 // Any file asked would have invalidated resolution
118157                 filesWithInvalidatedResolutions = undefined;
118158                 return ts.returnTrue;
118159             }
118160             var collected = filesWithInvalidatedResolutions;
118161             filesWithInvalidatedResolutions = undefined;
118162             return function (path) { return (!!collected && collected.has(path)) ||
118163                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
118164         }
118165         function clearPerDirectoryResolutions() {
118166             moduleResolutionCache.clear();
118167             typeReferenceDirectiveResolutionCache.clear();
118168             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
118169             nonRelativeExternalModuleResolutions.clear();
118170         }
118171         function finishCachingPerDirectoryResolution() {
118172             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
118173             clearPerDirectoryResolutions();
118174             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
118175                 if (watcher.refCount === 0) {
118176                     directoryWatchesOfFailedLookups.delete(path);
118177                     watcher.watcher.close();
118178                 }
118179             });
118180             hasChangedAutomaticTypeDirectiveNames = false;
118181         }
118182         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
118183             var _a;
118184             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
118185             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
118186             if (!resolutionHost.getGlobalCache) {
118187                 return primaryResult;
118188             }
118189             // otherwise try to load typings from @types
118190             var globalCache = resolutionHost.getGlobalCache();
118191             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
118192                 // create different collection of failed lookup locations for second pass
118193                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
118194                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
118195                 if (resolvedModule) {
118196                     // Modify existing resolution so its saved in the directory cache as well
118197                     primaryResult.resolvedModule = resolvedModule;
118198                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
118199                     return primaryResult;
118200                 }
118201             }
118202             // Default return the result from the first pass
118203             return primaryResult;
118204         }
118205         function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
118206             return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache);
118207         }
118208         function resolveNamesWithLocalCache(_a) {
118209             var _b, _c, _d;
118210             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, containingSourceFile = _a.containingSourceFile;
118211             var path = resolutionHost.toPath(containingFile);
118212             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createModeAwareCache()).get(path);
118213             var dirPath = ts.getDirectoryPath(path);
118214             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
118215             var perDirectoryResolution = perDirectoryCache.get(dirPath);
118216             if (!perDirectoryResolution) {
118217                 perDirectoryResolution = ts.createModeAwareCache();
118218                 perDirectoryCache.set(dirPath, perDirectoryResolution);
118219             }
118220             var resolvedModules = [];
118221             var compilerOptions = resolutionHost.getCompilationSettings();
118222             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
118223             // All the resolutions in this file are invalidated if this file wasn't resolved using same redirect
118224             var program = resolutionHost.getCurrentProgram();
118225             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
118226             var unmatchedRedirects = oldRedirect ?
118227                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
118228                 !!redirectedReference;
118229             var seenNamesInFile = ts.createModeAwareCache();
118230             var i = 0;
118231             for (var _i = 0, names_4 = names; _i < names_4.length; _i++) {
118232                 var name = names_4[_i];
118233                 var mode = containingSourceFile ? ts.getModeForResolutionAtIndex(containingSourceFile, i) : undefined;
118234                 i++;
118235                 var resolution = resolutionsInFile.get(name, mode);
118236                 // Resolution is valid if it is present and not invalidated
118237                 if (!seenNamesInFile.has(name, mode) &&
118238                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
118239                     // If the name is unresolved import that was invalidated, recalculate
118240                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
118241                     var existingResolution = resolution;
118242                     var resolutionInDirectory = perDirectoryResolution.get(name, mode);
118243                     if (resolutionInDirectory) {
118244                         resolution = resolutionInDirectory;
118245                         var host = ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost;
118246                         if (ts.isTraceEnabled(compilerOptions, host)) {
118247                             var resolved = getResolutionWithResolvedFileName(resolution);
118248                             ts.trace(host, loader === resolveModuleName ?
118249                                 (resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName) ?
118250                                     resolved.packagetId ?
118251                                         ts.Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4 :
118252                                         ts.Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3 :
118253                                     ts.Diagnostics.Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved :
118254                                 (resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName) ?
118255                                     resolved.packagetId ?
118256                                         ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4 :
118257                                         ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3 :
118258                                     ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved, name, containingFile, ts.getDirectoryPath(containingFile), resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName, (resolved === null || resolved === void 0 ? void 0 : resolved.packagetId) && ts.packageIdToString(resolved.packagetId));
118259                         }
118260                     }
118261                     else {
118262                         resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile);
118263                         perDirectoryResolution.set(name, mode, resolution);
118264                         if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) {
118265                             resolutionHost.onDiscoveredSymlink();
118266                         }
118267                     }
118268                     resolutionsInFile.set(name, mode, resolution);
118269                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
118270                     if (existingResolution) {
118271                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
118272                     }
118273                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
118274                         filesWithChangedSetOfUnresolvedImports.push(path);
118275                         // reset log changes to avoid recording the same file multiple times
118276                         logChanges = false;
118277                     }
118278                 }
118279                 else {
118280                     var host = ((_d = resolutionHost.getCompilerHost) === null || _d === void 0 ? void 0 : _d.call(resolutionHost)) || resolutionHost;
118281                     if (ts.isTraceEnabled(compilerOptions, host) && !seenNamesInFile.has(name, mode)) {
118282                         var resolved = getResolutionWithResolvedFileName(resolution);
118283                         ts.trace(host, loader === resolveModuleName ?
118284                             (resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName) ?
118285                                 resolved.packagetId ?
118286                                     ts.Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 :
118287                                     ts.Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 :
118288                                 ts.Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved :
118289                             (resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName) ?
118290                                 resolved.packagetId ?
118291                                     ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 :
118292                                     ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 :
118293                                 ts.Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, name, containingFile, resolved === null || resolved === void 0 ? void 0 : resolved.resolvedFileName, (resolved === null || resolved === void 0 ? void 0 : resolved.packagetId) && ts.packageIdToString(resolved.packagetId));
118294                     }
118295                 }
118296                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
118297                 seenNamesInFile.set(name, mode, true);
118298                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
118299             }
118300             // Stop watching and remove the unused name
118301             resolutionsInFile.forEach(function (resolution, name, mode) {
118302                 if (!seenNamesInFile.has(name, mode) && !ts.contains(reusedNames, name)) {
118303                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
118304                     resolutionsInFile.delete(name, mode);
118305                 }
118306             });
118307             return resolvedModules;
118308             function resolutionIsEqualTo(oldResolution, newResolution) {
118309                 if (oldResolution === newResolution) {
118310                     return true;
118311                 }
118312                 if (!oldResolution || !newResolution) {
118313                     return false;
118314                 }
118315                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
118316                 var newResult = getResolutionWithResolvedFileName(newResolution);
118317                 if (oldResult === newResult) {
118318                     return true;
118319                 }
118320                 if (!oldResult || !newResult) {
118321                     return false;
118322                 }
118323                 return oldResult.resolvedFileName === newResult.resolvedFileName;
118324             }
118325         }
118326         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
118327             return resolveNamesWithLocalCache({
118328                 names: typeDirectiveNames,
118329                 containingFile: containingFile,
118330                 redirectedReference: redirectedReference,
118331                 cache: resolvedTypeReferenceDirectives,
118332                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
118333                 loader: resolveTypeReferenceDirective,
118334                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
118335                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
118336             });
118337         }
118338         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, containingSourceFile) {
118339             return resolveNamesWithLocalCache({
118340                 names: moduleNames,
118341                 containingFile: containingFile,
118342                 redirectedReference: redirectedReference,
118343                 cache: resolvedModuleNames,
118344                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
118345                 loader: resolveModuleName,
118346                 getResolutionWithResolvedFileName: getResolvedModule,
118347                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
118348                 reusedNames: reusedNames,
118349                 logChanges: logChangesWhenResolvingModule,
118350                 containingSourceFile: containingSourceFile,
118351             });
118352         }
118353         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile, resolutionMode) {
118354             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
118355             if (!cache)
118356                 return undefined;
118357             return cache.get(moduleName, resolutionMode);
118358         }
118359         function isNodeModulesAtTypesDirectory(dirPath) {
118360             return ts.endsWith(dirPath, "/node_modules/@types");
118361         }
118362         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
118363             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
118364                 // Ensure failed look up is normalized path
118365                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
118366                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
118367                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
118368                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: ".concat(failedLookupLocation, " failedLookupLocationPath: ").concat(failedLookupLocationPath));
118369                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
118370                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
118371                     return {
118372                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
118373                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
118374                     };
118375                 }
118376                 else {
118377                     // Always watch root directory non recursively
118378                     return {
118379                         dir: rootDir,
118380                         dirPath: rootPath,
118381                         nonRecursive: false
118382                     };
118383                 }
118384             }
118385             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
118386         }
118387         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
118388             // If directory path contains node module, get the most parent node_modules directory for watching
118389             while (ts.pathContainsNodeModules(dirPath)) {
118390                 dir = ts.getDirectoryPath(dir);
118391                 dirPath = ts.getDirectoryPath(dirPath);
118392             }
118393             // If the directory is node_modules use it to watch, always watch it recursively
118394             if (ts.isNodeModulesDirectory(dirPath)) {
118395                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
118396             }
118397             var nonRecursive = true;
118398             // Use some ancestor of the root directory
118399             var subDirectoryPath, subDirectory;
118400             if (rootPath !== undefined) {
118401                 while (!isInDirectoryPath(dirPath, rootPath)) {
118402                     var parentPath = ts.getDirectoryPath(dirPath);
118403                     if (parentPath === dirPath) {
118404                         break;
118405                     }
118406                     nonRecursive = false;
118407                     subDirectoryPath = dirPath;
118408                     subDirectory = dir;
118409                     dirPath = parentPath;
118410                     dir = ts.getDirectoryPath(dir);
118411                 }
118412             }
118413             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
118414         }
118415         function isPathWithDefaultFailedLookupExtension(path) {
118416             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
118417         }
118418         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
118419             if (resolution.refCount) {
118420                 resolution.refCount++;
118421                 ts.Debug.assertDefined(resolution.files);
118422             }
118423             else {
118424                 resolution.refCount = 1;
118425                 ts.Debug.assert(ts.length(resolution.files) === 0); // This resolution shouldnt be referenced by any file yet
118426                 if (ts.isExternalModuleNameRelative(name)) {
118427                     watchFailedLookupLocationOfResolution(resolution);
118428                 }
118429                 else {
118430                     nonRelativeExternalModuleResolutions.add(name, resolution);
118431                 }
118432                 var resolved = getResolutionWithResolvedFileName(resolution);
118433                 if (resolved && resolved.resolvedFileName) {
118434                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
118435                 }
118436             }
118437             (resolution.files || (resolution.files = [])).push(filePath);
118438         }
118439         function watchFailedLookupLocationOfResolution(resolution) {
118440             ts.Debug.assert(!!resolution.refCount);
118441             var failedLookupLocations = resolution.failedLookupLocations;
118442             if (!failedLookupLocations.length)
118443                 return;
118444             resolutionsWithFailedLookups.push(resolution);
118445             var setAtRoot = false;
118446             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
118447                 var failedLookupLocation = failedLookupLocations_1[_i];
118448                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
118449                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
118450                 if (toWatch) {
118451                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
118452                     // If the failed lookup location path is not one of the supported extensions,
118453                     // store it in the custom path
118454                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
118455                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
118456                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
118457                     }
118458                     if (dirPath === rootPath) {
118459                         ts.Debug.assert(!nonRecursive);
118460                         setAtRoot = true;
118461                     }
118462                     else {
118463                         setDirectoryWatcher(dir, dirPath, nonRecursive);
118464                     }
118465                 }
118466             }
118467             if (setAtRoot) {
118468                 // This is always non recursive
118469                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
118470             }
118471         }
118472         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
118473             var program = resolutionHost.getCurrentProgram();
118474             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
118475                 resolutions.forEach(watchFailedLookupLocationOfResolution);
118476             }
118477         }
118478         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
118479             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
118480             if (dirWatcher) {
118481                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
118482                 dirWatcher.refCount++;
118483             }
118484             else {
118485                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
118486             }
118487         }
118488         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
118489             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
118490             resolution.refCount--;
118491             if (resolution.refCount) {
118492                 return;
118493             }
118494             var resolved = getResolutionWithResolvedFileName(resolution);
118495             if (resolved && resolved.resolvedFileName) {
118496                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
118497             }
118498             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
118499                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
118500                 return;
118501             }
118502             var failedLookupLocations = resolution.failedLookupLocations;
118503             var removeAtRoot = false;
118504             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
118505                 var failedLookupLocation = failedLookupLocations_2[_i];
118506                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
118507                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
118508                 if (toWatch) {
118509                     var dirPath = toWatch.dirPath;
118510                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
118511                     if (refCount) {
118512                         if (refCount === 1) {
118513                             customFailedLookupPaths.delete(failedLookupLocationPath);
118514                         }
118515                         else {
118516                             ts.Debug.assert(refCount > 1);
118517                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
118518                         }
118519                     }
118520                     if (dirPath === rootPath) {
118521                         removeAtRoot = true;
118522                     }
118523                     else {
118524                         removeDirectoryWatcher(dirPath);
118525                     }
118526                 }
118527             }
118528             if (removeAtRoot) {
118529                 removeDirectoryWatcher(rootPath);
118530             }
118531         }
118532         function removeDirectoryWatcher(dirPath) {
118533             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
118534             // Do not close the watcher yet since it might be needed by other failed lookup locations.
118535             dirWatcher.refCount--;
118536         }
118537         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
118538             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
118539                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
118540                 if (cachedDirectoryStructureHost) {
118541                     // Since the file existence changed, update the sourceFiles cache
118542                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
118543                 }
118544                 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
118545             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
118546         }
118547         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
118548             // Deleted file, stop watching failed lookups for all the resolutions in the file
118549             var resolutions = cache.get(filePath);
118550             if (resolutions) {
118551                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
118552                 cache.delete(filePath);
118553             }
118554         }
118555         function removeResolutionsFromProjectReferenceRedirects(filePath) {
118556             if (!ts.fileExtensionIs(filePath, ".json" /* Json */))
118557                 return;
118558             var program = resolutionHost.getCurrentProgram();
118559             if (!program)
118560                 return;
118561             // If this file is input file for the referenced project, get it
118562             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
118563             if (!resolvedProjectReference)
118564                 return;
118565             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
118566             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
118567         }
118568         function removeResolutionsOfFile(filePath) {
118569             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
118570             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
118571         }
118572         function invalidateResolutions(resolutions, canInvalidate) {
118573             if (!resolutions)
118574                 return false;
118575             var invalidated = false;
118576             for (var _i = 0, resolutions_1 = resolutions; _i < resolutions_1.length; _i++) {
118577                 var resolution = resolutions_1[_i];
118578                 if (resolution.isInvalidated || !canInvalidate(resolution))
118579                     continue;
118580                 resolution.isInvalidated = invalidated = true;
118581                 for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) {
118582                     var containingFilePath = _b[_a];
118583                     (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath);
118584                     // When its a file with inferred types resolution, invalidate type reference directive resolution
118585                     hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile);
118586                 }
118587             }
118588             return invalidated;
118589         }
118590         function invalidateResolutionOfFile(filePath) {
118591             removeResolutionsOfFile(filePath);
118592             // Resolution is invalidated if the resulting file name is same as the deleted file path
118593             var prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
118594             if (invalidateResolutions(resolvedFileToResolution.get(filePath), ts.returnTrue) &&
118595                 hasChangedAutomaticTypeDirectiveNames &&
118596                 !prevHasChangedAutomaticTypeDirectiveNames) {
118597                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
118598             }
118599         }
118600         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
118601             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
118602             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
118603         }
118604         function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
118605             if (isCreatingWatchedDirectory) {
118606                 // Watching directory is created
118607                 // Invalidate any resolution has failed lookup in this directory
118608                 (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath);
118609             }
118610             else {
118611                 // If something to do with folder/file starting with "." in node_modules folder, skip it
118612                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
118613                 if (!updatedPath)
118614                     return false;
118615                 fileOrDirectoryPath = updatedPath;
118616                 // prevent saving an open file from over-eagerly triggering invalidation
118617                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
118618                     return false;
118619                 }
118620                 // Some file or directory in the watching directory is created
118621                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
118622                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
118623                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
118624                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
118625                     // Invalidate any resolution from this directory
118626                     (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath);
118627                     (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath);
118628                 }
118629                 else {
118630                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
118631                         return false;
118632                     }
118633                     // Ignore emits from the program
118634                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
118635                         return false;
118636                     }
118637                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
118638                     (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath);
118639                     // If the invalidated file is from a node_modules package, invalidate everything else
118640                     // in the package since we might not get notifications for other files in the package.
118641                     // This hardens our logic against unreliable file watchers.
118642                     var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath);
118643                     if (packagePath)
118644                         (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath);
118645                 }
118646             }
118647             resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
118648         }
118649         function invalidateResolutionsOfFailedLookupLocations() {
118650             if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) {
118651                 return false;
118652             }
118653             var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution);
118654             failedLookupChecks = undefined;
118655             startsWithPathChecks = undefined;
118656             isInDirectoryChecks = undefined;
118657             return invalidated;
118658         }
118659         function canInvalidateFailedLookupResolution(resolution) {
118660             return resolution.failedLookupLocations.some(function (location) {
118661                 var locationPath = resolutionHost.toPath(location);
118662                 return ts.contains(failedLookupChecks, locationPath) ||
118663                     ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) ||
118664                     (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }));
118665             });
118666         }
118667         function closeTypeRootsWatch() {
118668             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
118669         }
118670         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
118671             if (isInDirectoryPath(rootPath, typeRootPath)) {
118672                 return rootPath;
118673             }
118674             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
118675             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
118676         }
118677         function createTypeRootsWatch(typeRootPath, typeRoot) {
118678             // Create new watch and recursive info
118679             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
118680                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
118681                 if (cachedDirectoryStructureHost) {
118682                     // Since the file existence changed, update the sourceFiles cache
118683                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
118684                 }
118685                 // For now just recompile
118686                 // We could potentially store more data here about whether it was/would be really be used or not
118687                 // and with that determine to trigger compilation but for now this is enough
118688                 hasChangedAutomaticTypeDirectiveNames = true;
118689                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
118690                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
118691                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
118692                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
118693                 if (dirPath) {
118694                     scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
118695                 }
118696             }, 1 /* Recursive */);
118697         }
118698         /**
118699          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
118700          * To be called when compiler options change
118701          */
118702         function updateTypeRootsWatch() {
118703             var options = resolutionHost.getCompilationSettings();
118704             if (options.types) {
118705                 // No need to do any watch since resolution cache is going to handle the failed lookups
118706                 // for the types added by this
118707                 closeTypeRootsWatch();
118708                 return;
118709             }
118710             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
118711             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
118712             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
118713             if (typeRoots) {
118714                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
118715                     createNewValue: createTypeRootsWatch,
118716                     onDeleteValue: ts.closeFileWatcher
118717                 });
118718             }
118719             else {
118720                 closeTypeRootsWatch();
118721             }
118722         }
118723         /**
118724          * Use this function to return if directory exists to get type roots to watch
118725          * If we return directory exists then only the paths will be added to type roots
118726          * Hence return true for all directories except root directories which are filtered from watching
118727          */
118728         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
118729             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
118730             var dirPath = resolutionHost.toPath(dir);
118731             return dirPath === rootPath || canWatchDirectory(dirPath);
118732         }
118733     }
118734     ts.createResolutionCache = createResolutionCache;
118735     function resolutionIsSymlink(resolution) {
118736         var _a, _b;
118737         return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) ||
118738             ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath));
118739     }
118740 })(ts || (ts = {}));
118741 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
118742 /* @internal */
118743 var ts;
118744 (function (ts) {
118745     var moduleSpecifiers;
118746     (function (moduleSpecifiers_1) {
118747         var RelativePreference;
118748         (function (RelativePreference) {
118749             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
118750             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
118751             RelativePreference[RelativePreference["Shortest"] = 2] = "Shortest";
118752             RelativePreference[RelativePreference["ExternalNonRelative"] = 3] = "ExternalNonRelative";
118753         })(RelativePreference || (RelativePreference = {}));
118754         // See UserPreferences#importPathEnding
118755         var Ending;
118756         (function (Ending) {
118757             Ending[Ending["Minimal"] = 0] = "Minimal";
118758             Ending[Ending["Index"] = 1] = "Index";
118759             Ending[Ending["JsExtension"] = 2] = "JsExtension";
118760         })(Ending || (Ending = {}));
118761         function getPreferences(host, _a, compilerOptions, importingSourceFile) {
118762             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
118763             return {
118764                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ :
118765                     importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ :
118766                         importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ :
118767                             2 /* Shortest */,
118768                 ending: getEnding(),
118769             };
118770             function getEnding() {
118771                 switch (importModuleSpecifierEnding) {
118772                     case "minimal": return 0 /* Minimal */;
118773                     case "index": return 1 /* Index */;
118774                     case "js": return 2 /* JsExtension */;
118775                     default: return usesJsExtensionOnImports(importingSourceFile) || isFormatRequiringExtensions(compilerOptions, importingSourceFile.path, host) ? 2 /* JsExtension */
118776                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
118777                 }
118778             }
118779         }
118780         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host) {
118781             return {
118782                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
118783                 ending: ts.hasJSFileExtension(oldImportSpecifier) || isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) ?
118784                     2 /* JsExtension */ :
118785                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
118786             };
118787         }
118788         function isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) {
118789             if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node12
118790                 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) {
118791                 return false;
118792             }
118793             return ts.getImpliedNodeFormatForFile(importingSourceFileName, /*packageJsonInfoCache*/ undefined, getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS;
118794         }
118795         function getModuleResolutionHost(host) {
118796             var _a;
118797             return {
118798                 fileExists: host.fileExists,
118799                 readFile: ts.Debug.checkDefined(host.readFile),
118800                 directoryExists: host.directoryExists,
118801                 getCurrentDirectory: host.getCurrentDirectory,
118802                 realpath: host.realpath,
118803                 useCaseSensitiveFileNames: (_a = host.useCaseSensitiveFileNames) === null || _a === void 0 ? void 0 : _a.call(host),
118804             };
118805         }
118806         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
118807             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {});
118808             if (res === oldImportSpecifier)
118809                 return undefined;
118810             return res;
118811         }
118812         moduleSpecifiers_1.updateModuleSpecifier = updateModuleSpecifier;
118813         // Note: importingSourceFile is just for usesJsExtensionOnImports
118814         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host) {
118815             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {});
118816         }
118817         moduleSpecifiers_1.getModuleSpecifier = getModuleSpecifier;
118818         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host, preferences) {
118819             var info = getInfo(importingSourceFileName, host);
118820             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host, preferences);
118821             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); });
118822         }
118823         moduleSpecifiers_1.getNodeModulesPackageName = getNodeModulesPackageName;
118824         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences, userPreferences) {
118825             var info = getInfo(importingSourceFileName, host);
118826             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences);
118827             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) ||
118828                 getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
118829         }
118830         function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences) {
118831             return tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences)[0];
118832         }
118833         moduleSpecifiers_1.tryGetModuleSpecifiersFromCache = tryGetModuleSpecifiersFromCache;
118834         function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences) {
118835             var _a;
118836             var moduleSourceFile = ts.getSourceFileOfModule(moduleSymbol);
118837             if (!moduleSourceFile) {
118838                 return ts.emptyArray;
118839             }
118840             var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host);
118841             var cached = cache === null || cache === void 0 ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences);
118842             return [cached === null || cached === void 0 ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached === null || cached === void 0 ? void 0 : cached.modulePaths, cache];
118843         }
118844         /** Returns an import for each symlink and for the realpath. */
118845         function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences) {
118846             return getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences).moduleSpecifiers;
118847         }
118848         moduleSpecifiers_1.getModuleSpecifiers = getModuleSpecifiers;
118849         function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences) {
118850             var computedWithoutCache = false;
118851             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
118852             if (ambient)
118853                 return { moduleSpecifiers: [ambient], computedWithoutCache: computedWithoutCache };
118854             // eslint-disable-next-line prefer-const
118855             var _a = tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences), specifiers = _a[0], moduleSourceFile = _a[1], modulePaths = _a[2], cache = _a[3];
118856             if (specifiers)
118857                 return { moduleSpecifiers: specifiers, computedWithoutCache: computedWithoutCache };
118858             if (!moduleSourceFile)
118859                 return { moduleSpecifiers: ts.emptyArray, computedWithoutCache: computedWithoutCache };
118860             computedWithoutCache = true;
118861             modulePaths || (modulePaths = getAllModulePathsWorker(importingSourceFile.path, moduleSourceFile.originalFileName, host));
118862             var result = computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences);
118863             cache === null || cache === void 0 ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, modulePaths, result);
118864             return { moduleSpecifiers: result, computedWithoutCache: computedWithoutCache };
118865         }
118866         moduleSpecifiers_1.getModuleSpecifiersWithCacheInfo = getModuleSpecifiersWithCacheInfo;
118867         function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences) {
118868             var info = getInfo(importingSourceFile.path, host);
118869             var preferences = getPreferences(host, userPreferences, compilerOptions, importingSourceFile);
118870             var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) {
118871                 if (reason.kind !== ts.FileIncludeKind.Import || reason.file !== importingSourceFile.path)
118872                     return undefined;
118873                 var specifier = ts.getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
118874                 // If the preference is for non relative and the module specifier is relative, ignore it
118875                 return preferences.relativePreference !== 1 /* NonRelative */ || !ts.pathIsRelative(specifier) ?
118876                     specifier :
118877                     undefined;
118878             }); });
118879             if (existingSpecifier) {
118880                 var moduleSpecifiers_2 = [existingSpecifier];
118881                 return moduleSpecifiers_2;
118882             }
118883             var importedFileIsInNodeModules = ts.some(modulePaths, function (p) { return p.isInNodeModules; });
118884             // Module specifier priority:
118885             //   1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
118886             //   2. Specifiers generated using "paths" from tsconfig
118887             //   3. Non-relative specfiers resulting from a path through node_modules (e.g. "@foo/bar/path/to/file")
118888             //   4. Relative paths
118889             var nodeModulesSpecifiers;
118890             var pathsSpecifiers;
118891             var relativeSpecifiers;
118892             for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) {
118893                 var modulePath = modulePaths_1[_i];
118894                 var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions);
118895                 nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier);
118896                 if (specifier && modulePath.isRedirect) {
118897                     // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
118898                     // not "@foo/bar/path/to/file"). No other specifier will be this good, so stop looking.
118899                     return nodeModulesSpecifiers;
118900                 }
118901                 if (!specifier && !modulePath.isRedirect) {
118902                     var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences);
118903                     if (ts.pathIsBareSpecifier(local)) {
118904                         pathsSpecifiers = ts.append(pathsSpecifiers, local);
118905                     }
118906                     else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) {
118907                         // Why this extra conditional, not just an `else`? If some path to the file contained
118908                         // 'node_modules', but we can't create a non-relative specifier (e.g. "@foo/bar/path/to/file"),
118909                         // that means we had to go through a *sibling's* node_modules, not one we can access directly.
118910                         // If some path to the file was in node_modules but another was not, this likely indicates that
118911                         // we have a monorepo structure with symlinks. In this case, the non-node_modules path is
118912                         // probably the realpath, e.g. "../bar/path/to/file", but a relative path to another package
118913                         // in a monorepo is probably not portable. So, the module specifier we actually go with will be
118914                         // the relative path through node_modules, so that the declaration emitter can produce a
118915                         // portability error. (See declarationEmitReexportedSymlinkReference3)
118916                         relativeSpecifiers = ts.append(relativeSpecifiers, local);
118917                     }
118918                 }
118919             }
118920             return (pathsSpecifiers === null || pathsSpecifiers === void 0 ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers :
118921                 (nodeModulesSpecifiers === null || nodeModulesSpecifiers === void 0 ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers :
118922                     ts.Debug.checkDefined(relativeSpecifiers);
118923         }
118924         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
118925         function getInfo(importingSourceFileName, host) {
118926             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
118927             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
118928             return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory };
118929         }
118930         function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) {
118931             var ending = _a.ending, relativePreference = _a.relativePreference;
118932             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
118933             var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName;
118934             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
118935                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
118936             if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
118937                 return relativePath;
118938             }
118939             var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory());
118940             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName);
118941             if (!relativeToBaseUrl) {
118942                 return relativePath;
118943             }
118944             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
118945             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
118946             var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths;
118947             if (!nonRelative) {
118948                 return relativePath;
118949             }
118950             if (relativePreference === 1 /* NonRelative */) {
118951                 return nonRelative;
118952             }
118953             if (relativePreference === 3 /* ExternalNonRelative */) {
118954                 var projectDirectory = compilerOptions.configFilePath ?
118955                     ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) :
118956                     info.getCanonicalFileName(host.getCurrentDirectory());
118957                 var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName);
118958                 var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory);
118959                 var targetIsInternal = ts.startsWith(modulePath, projectDirectory);
118960                 if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
118961                     // 1. The import path crosses the boundary of the tsconfig.json-containing directory.
118962                     //
118963                     //      src/
118964                     //        tsconfig.json
118965                     //        index.ts -------
118966                     //      lib/              | (path crosses tsconfig.json)
118967                     //        imported.ts <---
118968                     //
118969                     return nonRelative;
118970                 }
118971                 var nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, ts.getDirectoryPath(modulePath));
118972                 var nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
118973                 if (nearestSourcePackageJson !== nearestTargetPackageJson) {
118974                     // 2. The importing and imported files are part of different packages.
118975                     //
118976                     //      packages/a/
118977                     //        package.json
118978                     //        index.ts --------
118979                     //      packages/b/        | (path crosses package.json)
118980                     //        package.json     |
118981                     //        component.ts <---
118982                     //
118983                     return nonRelative;
118984                 }
118985                 return relativePath;
118986             }
118987             if (relativePreference !== 2 /* Shortest */)
118988                 ts.Debug.assertNever(relativePreference);
118989             // Prefer a relative import over a baseUrl import if it has fewer components.
118990             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
118991         }
118992         function countPathComponents(path) {
118993             var count = 0;
118994             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
118995                 if (path.charCodeAt(i) === 47 /* slash */)
118996                     count++;
118997             }
118998             return count;
118999         }
119000         moduleSpecifiers_1.countPathComponents = countPathComponents;
119001         function usesJsExtensionOnImports(_a) {
119002             var imports = _a.imports;
119003             return ts.firstDefined(imports, function (_a) {
119004                 var text = _a.text;
119005                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
119006             }) || false;
119007         }
119008         function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
119009             return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path);
119010         }
119011         function getNearestAncestorDirectoryWithPackageJson(host, fileName) {
119012             if (host.getNearestAncestorDirectoryWithPackageJson) {
119013                 return host.getNearestAncestorDirectoryWithPackageJson(fileName);
119014             }
119015             return !!ts.forEachAncestorDirectory(fileName, function (directory) {
119016                 return host.fileExists(ts.combinePaths(directory, "package.json")) ? true : undefined;
119017             });
119018         }
119019         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
119020             var _a;
119021             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
119022             var cwd = host.getCurrentDirectory();
119023             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
119024             var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName);
119025             var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray;
119026             var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray), true), [importedFileName], false), redirects, true);
119027             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
119028             var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath);
119029             if (!preferSymlinks) {
119030                 // Symlinks inside ignored paths are already filtered out of the symlink cache,
119031                 // so we only need to remove them from the realpath filenames.
119032                 var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); });
119033                 if (result_14)
119034                     return result_14;
119035             }
119036             var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath();
119037             var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd);
119038             var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) {
119039                 var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName)));
119040                 if (!symlinkDirectories)
119041                     return undefined; // Continue to ancestor directory
119042                 // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts)
119043                 if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
119044                     return false; // Stop search, each ancestor directory will also hit this condition
119045                 }
119046                 return ts.forEach(targets, function (target) {
119047                     if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
119048                         return;
119049                     }
119050                     var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
119051                     for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) {
119052                         var symlinkDirectory = symlinkDirectories_1[_i];
119053                         var option = ts.resolvePath(symlinkDirectory, relative);
119054                         var result_15 = cb(option, target === referenceRedirect);
119055                         shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths
119056                         if (result_15)
119057                             return result_15;
119058                     }
119059                 });
119060             });
119061             return result || (preferSymlinks
119062                 ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); })
119063                 : undefined);
119064         }
119065         moduleSpecifiers_1.forEachFileNameOfModule = forEachFileNameOfModule;
119066         /**
119067          * Looks for existing imports that use symlinks to this module.
119068          * Symlinks will be returned first so they are preferred over the real path.
119069          */
119070         function getAllModulePaths(importingFilePath, importedFileName, host, preferences, importedFilePath) {
119071             var _a;
119072             if (importedFilePath === void 0) { importedFilePath = ts.toPath(importedFileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }
119073             var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host);
119074             if (cache) {
119075                 var cached = cache.get(importingFilePath, importedFilePath, preferences);
119076                 if (cached === null || cached === void 0 ? void 0 : cached.modulePaths)
119077                     return cached.modulePaths;
119078             }
119079             var modulePaths = getAllModulePathsWorker(importingFilePath, importedFileName, host);
119080             if (cache) {
119081                 cache.setModulePaths(importingFilePath, importedFilePath, preferences, modulePaths);
119082             }
119083             return modulePaths;
119084         }
119085         function getAllModulePathsWorker(importingFileName, importedFileName, host) {
119086             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
119087             var allFileNames = new ts.Map();
119088             var importedFileFromNodeModules = false;
119089             forEachFileNameOfModule(importingFileName, importedFileName, host, 
119090             /*preferSymlinks*/ true, function (path, isRedirect) {
119091                 var isInNodeModules = ts.pathContainsNodeModules(path);
119092                 allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect: isRedirect, isInNodeModules: isInNodeModules });
119093                 importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
119094                 // don't return value, so we collect everything
119095             });
119096             // Sort by paths closest to importing file Name directory
119097             var sortedPaths = [];
119098             var _loop_31 = function (directory) {
119099                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
119100                 var pathsInDirectory;
119101                 allFileNames.forEach(function (_a, fileName) {
119102                     var path = _a.path, isRedirect = _a.isRedirect, isInNodeModules = _a.isInNodeModules;
119103                     if (ts.startsWith(path, directoryStart)) {
119104                         (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect: isRedirect, isInNodeModules: isInNodeModules });
119105                         allFileNames.delete(fileName);
119106                     }
119107                 });
119108                 if (pathsInDirectory) {
119109                     if (pathsInDirectory.length > 1) {
119110                         pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
119111                     }
119112                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
119113                 }
119114                 var newDirectory = ts.getDirectoryPath(directory);
119115                 if (newDirectory === directory)
119116                     return out_directory_1 = directory, "break";
119117                 directory = newDirectory;
119118                 out_directory_1 = directory;
119119             };
119120             var out_directory_1;
119121             for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) {
119122                 var state_9 = _loop_31(directory);
119123                 directory = out_directory_1;
119124                 if (state_9 === "break")
119125                     break;
119126             }
119127             if (allFileNames.size) {
119128                 var remainingPaths = ts.arrayFrom(allFileNames.values());
119129                 if (remainingPaths.length > 1)
119130                     remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
119131                 sortedPaths.push.apply(sortedPaths, remainingPaths);
119132             }
119133             return sortedPaths;
119134         }
119135         function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) {
119136             var _a;
119137             var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
119138             if (decl) {
119139                 return decl.name.text;
119140             }
119141             // the module could be a namespace, which is export through "export=" from an ambient module.
119142             /**
119143              * declare module "m" {
119144              *     namespace ns {
119145              *         class c {}
119146              *     }
119147              *     export = ns;
119148              * }
119149              */
119150             // `import {c} from "m";` is valid, in which case, `moduleSymbol` is "ns", but the module name should be "m"
119151             var ambientModuleDeclareCandidates = ts.mapDefined(moduleSymbol.declarations, function (d) {
119152                 var _a, _b, _c, _d;
119153                 if (!ts.isModuleDeclaration(d))
119154                     return;
119155                 var topNamespace = getTopNamespace(d);
119156                 if (!(((_a = topNamespace === null || topNamespace === void 0 ? void 0 : topNamespace.parent) === null || _a === void 0 ? void 0 : _a.parent)
119157                     && ts.isModuleBlock(topNamespace.parent) && ts.isAmbientModule(topNamespace.parent.parent) && ts.isSourceFile(topNamespace.parent.parent.parent)))
119158                     return;
119159                 var exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) === null || _b === void 0 ? void 0 : _b.get("export=")) === null || _c === void 0 ? void 0 : _c.valueDeclaration) === null || _d === void 0 ? void 0 : _d.expression;
119160                 if (!exportAssignment)
119161                     return;
119162                 var exportSymbol = checker.getSymbolAtLocation(exportAssignment);
119163                 if (!exportSymbol)
119164                     return;
119165                 var originalExportSymbol = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
119166                 if (originalExportSymbol === d.symbol)
119167                     return topNamespace.parent.parent;
119168                 function getTopNamespace(namespaceDeclaration) {
119169                     while (namespaceDeclaration.flags & 4 /* NestedNamespace */) {
119170                         namespaceDeclaration = namespaceDeclaration.parent;
119171                     }
119172                     return namespaceDeclaration;
119173                 }
119174             });
119175             var ambientModuleDeclare = ambientModuleDeclareCandidates[0];
119176             if (ambientModuleDeclare) {
119177                 return ambientModuleDeclare.name.text;
119178             }
119179         }
119180         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
119181             for (var key in paths) {
119182                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
119183                     var patternText_1 = _a[_i];
119184                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
119185                     var indexOfStar = pattern.indexOf("*");
119186                     if (indexOfStar !== -1) {
119187                         var prefix = pattern.substr(0, indexOfStar);
119188                         var suffix = pattern.substr(indexOfStar + 1);
119189                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
119190                             ts.startsWith(relativeToBaseUrl, prefix) &&
119191                             ts.endsWith(relativeToBaseUrl, suffix) ||
119192                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
119193                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length);
119194                             return key.replace("*", matchedStar);
119195                         }
119196                     }
119197                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
119198                         return key;
119199                     }
119200                 }
119201             }
119202         }
119203         var MatchingMode;
119204         (function (MatchingMode) {
119205             MatchingMode[MatchingMode["Exact"] = 0] = "Exact";
119206             MatchingMode[MatchingMode["Directory"] = 1] = "Directory";
119207             MatchingMode[MatchingMode["Pattern"] = 2] = "Pattern";
119208         })(MatchingMode || (MatchingMode = {}));
119209         function tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, exports, conditions, mode) {
119210             if (mode === void 0) { mode = 0 /* Exact */; }
119211             if (typeof exports === "string") {
119212                 var pathOrPattern = ts.getNormalizedAbsolutePath(ts.combinePaths(packageDirectory, exports), /*currentDirectory*/ undefined);
119213                 var extensionSwappedTarget = ts.hasTSFileExtension(targetFilePath) ? ts.removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : undefined;
119214                 switch (mode) {
119215                     case 0 /* Exact */:
119216                         if (ts.comparePaths(targetFilePath, pathOrPattern) === 0 /* EqualTo */ || (extensionSwappedTarget && ts.comparePaths(extensionSwappedTarget, pathOrPattern) === 0 /* EqualTo */)) {
119217                             return { moduleFileToTry: packageName };
119218                         }
119219                         break;
119220                     case 1 /* Directory */:
119221                         if (ts.containsPath(pathOrPattern, targetFilePath)) {
119222                             var fragment = ts.getRelativePathFromDirectory(pathOrPattern, targetFilePath, /*ignoreCase*/ false);
119223                             return { moduleFileToTry: ts.getNormalizedAbsolutePath(ts.combinePaths(ts.combinePaths(packageName, exports), fragment), /*currentDirectory*/ undefined) };
119224                         }
119225                         break;
119226                     case 2 /* Pattern */:
119227                         var starPos = pathOrPattern.indexOf("*");
119228                         var leadingSlice = pathOrPattern.slice(0, starPos);
119229                         var trailingSlice = pathOrPattern.slice(starPos + 1);
119230                         if (ts.startsWith(targetFilePath, leadingSlice) && ts.endsWith(targetFilePath, trailingSlice)) {
119231                             var starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
119232                             return { moduleFileToTry: packageName.replace("*", starReplacement) };
119233                         }
119234                         if (extensionSwappedTarget && ts.startsWith(extensionSwappedTarget, leadingSlice) && ts.endsWith(extensionSwappedTarget, trailingSlice)) {
119235                             var starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length);
119236                             return { moduleFileToTry: packageName.replace("*", starReplacement) };
119237                         }
119238                         break;
119239                 }
119240             }
119241             else if (Array.isArray(exports)) {
119242                 return ts.forEach(exports, function (e) { return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, e, conditions); });
119243             }
119244             else if (typeof exports === "object" && exports !== null) { // eslint-disable-line no-null/no-null
119245                 if (ts.allKeysStartWithDot(exports)) {
119246                     // sub-mappings
119247                     // 3 cases:
119248                     // * directory mappings (legacyish, key ends with / (technically allows index/extension resolution under cjs mode))
119249                     // * pattern mappings (contains a *)
119250                     // * exact mappings (no *, does not end with /)
119251                     return ts.forEach(ts.getOwnKeys(exports), function (k) {
119252                         var subPackageName = ts.getNormalizedAbsolutePath(ts.combinePaths(packageName, k), /*currentDirectory*/ undefined);
119253                         var mode = ts.endsWith(k, "/") ? 1 /* Directory */
119254                             : ts.stringContains(k, "*") ? 2 /* Pattern */
119255                                 : 0 /* Exact */;
119256                         return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, exports[k], conditions, mode);
119257                     });
119258                 }
119259                 else {
119260                     // conditional mapping
119261                     for (var _i = 0, _a = ts.getOwnKeys(exports); _i < _a.length; _i++) {
119262                         var key = _a[_i];
119263                         if (key === "default" || conditions.indexOf(key) >= 0 || ts.isApplicableVersionedTypesKey(conditions, key)) {
119264                             var subTarget = exports[key];
119265                             var result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions);
119266                             if (result) {
119267                                 return result;
119268                             }
119269                         }
119270                     }
119271                 }
119272             }
119273             return undefined;
119274         }
119275         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
119276             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
119277             if (normalizedTargetPath === undefined) {
119278                 return undefined;
119279             }
119280             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
119281             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
119282             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
119283                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
119284                 : ts.removeFileExtension(relativePath);
119285         }
119286         function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) {
119287             var path = _a.path, isRedirect = _a.isRedirect;
119288             var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory;
119289             if (!host.fileExists || !host.readFile) {
119290                 return undefined;
119291             }
119292             var parts = getNodeModulePathParts(path);
119293             if (!parts) {
119294                 return undefined;
119295             }
119296             // Simplify the full file path to something that can be resolved by Node.
119297             var moduleSpecifier = path;
119298             var isPackageRootPath = false;
119299             if (!packageNameOnly) {
119300                 var packageRootIndex = parts.packageRootIndex;
119301                 var moduleFileNameForExtensionless = void 0;
119302                 while (true) {
119303                     // If the module could be imported by a directory name, use that directory's name
119304                     var _c = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _c.moduleFileToTry, packageRootPath = _c.packageRootPath, blockedByExports = _c.blockedByExports, verbatimFromExports = _c.verbatimFromExports;
119305                     if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Classic) {
119306                         if (blockedByExports) {
119307                             return undefined; // File is under this package.json, but is not publicly exported - there's no way to name it via `node_modules` resolution
119308                         }
119309                         if (verbatimFromExports) {
119310                             return moduleFileToTry;
119311                         }
119312                     }
119313                     if (packageRootPath) {
119314                         moduleSpecifier = packageRootPath;
119315                         isPackageRootPath = true;
119316                         break;
119317                     }
119318                     if (!moduleFileNameForExtensionless)
119319                         moduleFileNameForExtensionless = moduleFileToTry;
119320                     // try with next level of directory
119321                     packageRootIndex = path.indexOf(ts.directorySeparator, packageRootIndex + 1);
119322                     if (packageRootIndex === -1) {
119323                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
119324                         break;
119325                     }
119326                 }
119327             }
119328             if (isRedirect && !isPackageRootPath) {
119329                 return undefined;
119330             }
119331             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
119332             // Get a path that's relative to node_modules or the importing file's path
119333             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
119334             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
119335             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
119336                 return undefined;
119337             }
119338             // If the module was found in @types, get the actual Node package name
119339             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
119340             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
119341             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
119342             return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Classic && packageName === nodeModulesDirectoryName ? undefined : packageName;
119343             function tryDirectoryWithPackageJson(packageRootIndex) {
119344                 var packageRootPath = path.substring(0, packageRootIndex);
119345                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
119346                 var moduleFileToTry = path;
119347                 if (host.fileExists(packageJsonPath)) {
119348                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
119349                     // TODO: Inject `require` or `import` condition based on the intended import mode
119350                     if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
119351                         var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined;
119352                         if (fromExports) {
119353                             var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) };
119354                             return __assign(__assign({}, withJsExtension), { verbatimFromExports: true });
119355                         }
119356                         if (packageJsonContent.exports) {
119357                             return { moduleFileToTry: path, blockedByExports: true };
119358                         }
119359                     }
119360                     var versionPaths = packageJsonContent.typesVersions
119361                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
119362                         : undefined;
119363                     if (versionPaths) {
119364                         var subModuleName = path.slice(packageRootPath.length + 1);
119365                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
119366                         if (fromPaths !== undefined) {
119367                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
119368                         }
119369                     }
119370                     // If the file is the main module, it can be imported by the package name
119371                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
119372                     if (ts.isString(mainFileRelative)) {
119373                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
119374                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
119375                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
119376                         }
119377                     }
119378                 }
119379                 return { moduleFileToTry: moduleFileToTry };
119380             }
119381             function getExtensionlessFileName(path) {
119382                 // We still have a file name - remove the extension
119383                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
119384                 // If the file is /index, it can be imported by its directory name
119385                 // IFF there is not _also_ a file by the same name
119386                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
119387                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
119388                 }
119389                 return fullModulePathWithoutExtension;
119390             }
119391         }
119392         function tryGetAnyFileFromPath(host, path) {
119393             if (!host.fileExists)
119394                 return;
119395             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
119396             var extensions = ts.flatten(ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]));
119397             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
119398                 var e = extensions_3[_i];
119399                 var fullPath = path + e;
119400                 if (host.fileExists(fullPath)) {
119401                     return fullPath;
119402                 }
119403             }
119404         }
119405         function getNodeModulePathParts(fullPath) {
119406             // If fullPath can't be valid module file within node_modules, returns undefined.
119407             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
119408             // Returns indices:                       ^            ^                                                      ^             ^
119409             var topLevelNodeModulesIndex = 0;
119410             var topLevelPackageNameIndex = 0;
119411             var packageRootIndex = 0;
119412             var fileNameIndex = 0;
119413             var States;
119414             (function (States) {
119415                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
119416                 States[States["NodeModules"] = 1] = "NodeModules";
119417                 States[States["Scope"] = 2] = "Scope";
119418                 States[States["PackageContent"] = 3] = "PackageContent";
119419             })(States || (States = {}));
119420             var partStart = 0;
119421             var partEnd = 0;
119422             var state = 0 /* BeforeNodeModules */;
119423             while (partEnd >= 0) {
119424                 partStart = partEnd;
119425                 partEnd = fullPath.indexOf("/", partStart + 1);
119426                 switch (state) {
119427                     case 0 /* BeforeNodeModules */:
119428                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
119429                             topLevelNodeModulesIndex = partStart;
119430                             topLevelPackageNameIndex = partEnd;
119431                             state = 1 /* NodeModules */;
119432                         }
119433                         break;
119434                     case 1 /* NodeModules */:
119435                     case 2 /* Scope */:
119436                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
119437                             state = 2 /* Scope */;
119438                         }
119439                         else {
119440                             packageRootIndex = partEnd;
119441                             state = 3 /* PackageContent */;
119442                         }
119443                         break;
119444                     case 3 /* PackageContent */:
119445                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
119446                             state = 1 /* NodeModules */;
119447                         }
119448                         else {
119449                             state = 3 /* PackageContent */;
119450                         }
119451                         break;
119452                 }
119453             }
119454             fileNameIndex = partStart;
119455             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
119456         }
119457         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
119458             return ts.firstDefined(rootDirs, function (rootDir) {
119459                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
119460                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
119461             });
119462         }
119463         function removeExtensionAndIndexPostFix(fileName, ending, options) {
119464             if (ts.fileExtensionIsOneOf(fileName, [".json" /* Json */, ".mjs" /* Mjs */, ".cjs" /* Cjs */]))
119465                 return fileName;
119466             var noExtension = ts.removeFileExtension(fileName);
119467             if (ts.fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */]))
119468                 return noExtension + getJSExtensionForFile(fileName, options);
119469             switch (ending) {
119470                 case 0 /* Minimal */:
119471                     return ts.removeSuffix(noExtension, "/index");
119472                 case 1 /* Index */:
119473                     return noExtension;
119474                 case 2 /* JsExtension */:
119475                     return noExtension + getJSExtensionForFile(fileName, options);
119476                 default:
119477                     return ts.Debug.assertNever(ending);
119478             }
119479         }
119480         function getJSExtensionForFile(fileName, options) {
119481             var _a;
119482             return (_a = tryGetJSExtensionForFile(fileName, options)) !== null && _a !== void 0 ? _a : ts.Debug.fail("Extension ".concat(ts.extensionFromPath(fileName), " is unsupported:: FileName:: ").concat(fileName));
119483         }
119484         function tryGetJSExtensionForFile(fileName, options) {
119485             var ext = ts.tryGetExtensionFromPath(fileName);
119486             switch (ext) {
119487                 case ".ts" /* Ts */:
119488                 case ".d.ts" /* Dts */:
119489                     return ".js" /* Js */;
119490                 case ".tsx" /* Tsx */:
119491                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
119492                 case ".js" /* Js */:
119493                 case ".jsx" /* Jsx */:
119494                 case ".json" /* Json */:
119495                     return ext;
119496                 case ".d.mts" /* Dmts */:
119497                 case ".mts" /* Mts */:
119498                 case ".mjs" /* Mjs */:
119499                     return ".mjs" /* Mjs */;
119500                 case ".d.cts" /* Dcts */:
119501                 case ".cts" /* Cts */:
119502                 case ".cjs" /* Cjs */:
119503                     return ".cjs" /* Cjs */;
119504                 default:
119505                     return undefined;
119506             }
119507         }
119508         moduleSpecifiers_1.tryGetJSExtensionForFile = tryGetJSExtensionForFile;
119509         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
119510             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
119511             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
119512         }
119513         function isPathRelativeToParent(path) {
119514             return ts.startsWith(path, "..");
119515         }
119516     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
119517 })(ts || (ts = {}));
119518 /*@internal*/
119519 var ts;
119520 (function (ts) {
119521     var sysFormatDiagnosticsHost = ts.sys ? {
119522         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
119523         getNewLine: function () { return ts.sys.newLine; },
119524         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
119525     } : undefined;
119526     /**
119527      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
119528      */
119529     function createDiagnosticReporter(system, pretty) {
119530         var host = system === ts.sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : {
119531             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
119532             getNewLine: function () { return system.newLine; },
119533             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
119534         };
119535         if (!pretty) {
119536             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
119537         }
119538         var diagnostics = new Array(1);
119539         return function (diagnostic) {
119540             diagnostics[0] = diagnostic;
119541             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
119542             diagnostics[0] = undefined; // TODO: GH#18217
119543         };
119544     }
119545     ts.createDiagnosticReporter = createDiagnosticReporter;
119546     /**
119547      * @returns Whether the screen was cleared.
119548      */
119549     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
119550         if (system.clearScreen &&
119551             !options.preserveWatchOutput &&
119552             !options.extendedDiagnostics &&
119553             !options.diagnostics &&
119554             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
119555             system.clearScreen();
119556             return true;
119557         }
119558         return false;
119559     }
119560     ts.screenStartingMessageCodes = [
119561         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
119562         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
119563     ];
119564     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
119565         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
119566             ? newLine + newLine
119567             : newLine;
119568     }
119569     /**
119570      * Get locale specific time based on whether we are in test mode
119571      */
119572     function getLocaleTimeString(system) {
119573         return !system.now ?
119574             new Date().toLocaleTimeString() :
119575             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
119576     }
119577     ts.getLocaleTimeString = getLocaleTimeString;
119578     /**
119579      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
119580      */
119581     function createWatchStatusReporter(system, pretty) {
119582         return pretty ?
119583             function (diagnostic, newLine, options) {
119584                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
119585                 var output = "[".concat(ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey), "] ");
119586                 output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(newLine + newLine);
119587                 system.write(output);
119588             } :
119589             function (diagnostic, newLine, options) {
119590                 var output = "";
119591                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
119592                     output += newLine;
119593                 }
119594                 output += "".concat(getLocaleTimeString(system), " - ");
119595                 output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(getPlainDiagnosticFollowingNewLines(diagnostic, newLine));
119596                 system.write(output);
119597             };
119598     }
119599     ts.createWatchStatusReporter = createWatchStatusReporter;
119600     /** Parses config file using System interface */
119601     function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) {
119602         var host = system;
119603         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
119604         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend);
119605         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
119606         return result;
119607     }
119608     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
119609     function getErrorCountForSummary(diagnostics) {
119610         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
119611     }
119612     ts.getErrorCountForSummary = getErrorCountForSummary;
119613     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
119614         return errorCount === 1 ?
119615             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
119616             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
119617     }
119618     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
119619     function getErrorSummaryText(errorCount, newLine) {
119620         if (errorCount === 0)
119621             return "";
119622         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
119623         return "".concat(newLine).concat(ts.flattenDiagnosticMessageText(d.messageText, newLine)).concat(newLine).concat(newLine);
119624     }
119625     ts.getErrorSummaryText = getErrorSummaryText;
119626     function isBuilderProgram(program) {
119627         return !!program.getState;
119628     }
119629     ts.isBuilderProgram = isBuilderProgram;
119630     function listFiles(program, write) {
119631         var options = program.getCompilerOptions();
119632         if (options.explainFiles) {
119633             explainFiles(isBuilderProgram(program) ? program.getProgram() : program, write);
119634         }
119635         else if (options.listFiles || options.listFilesOnly) {
119636             ts.forEach(program.getSourceFiles(), function (file) {
119637                 write(file.fileName);
119638             });
119639         }
119640     }
119641     ts.listFiles = listFiles;
119642     function explainFiles(program, write) {
119643         var _a, _b;
119644         var reasons = program.getFileIncludeReasons();
119645         var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
119646         var relativeFileName = function (fileName) { return ts.convertToRelativePath(fileName, program.getCurrentDirectory(), getCanonicalFileName); };
119647         for (var _i = 0, _c = program.getSourceFiles(); _i < _c.length; _i++) {
119648             var file = _c[_i];
119649             write("".concat(toFileName(file, relativeFileName)));
119650             (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write("  ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); });
119651             (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write("  ".concat(d.messageText)); });
119652         }
119653     }
119654     ts.explainFiles = explainFiles;
119655     function explainIfFileIsRedirect(file, fileNameConvertor) {
119656         var result;
119657         if (file.path !== file.resolvedPath) {
119658             (result || (result = [])).push(ts.chainDiagnosticMessages(
119659             /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor)));
119660         }
119661         if (file.redirectInfo) {
119662             (result || (result = [])).push(ts.chainDiagnosticMessages(
119663             /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor)));
119664         }
119665         return result;
119666     }
119667     ts.explainIfFileIsRedirect = explainIfFileIsRedirect;
119668     function getMatchedFileSpec(program, fileName) {
119669         var _a;
119670         var configFile = program.getCompilerOptions().configFile;
119671         if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedFilesSpec))
119672             return undefined;
119673         var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
119674         var filePath = getCanonicalFileName(fileName);
119675         var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
119676         return ts.find(configFile.configFileSpecs.validatedFilesSpec, function (fileSpec) { return getCanonicalFileName(ts.getNormalizedAbsolutePath(fileSpec, basePath)) === filePath; });
119677     }
119678     ts.getMatchedFileSpec = getMatchedFileSpec;
119679     function getMatchedIncludeSpec(program, fileName) {
119680         var _a, _b;
119681         var configFile = program.getCompilerOptions().configFile;
119682         if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs))
119683             return undefined;
119684         var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Json */);
119685         var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
119686         var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames();
119687         return ts.find((_b = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs, function (includeSpec) {
119688             if (isJsonFile && !ts.endsWith(includeSpec, ".json" /* Json */))
119689                 return false;
119690             var pattern = ts.getPatternFromSpec(includeSpec, basePath, "files");
119691             return !!pattern && ts.getRegexFromPattern("(".concat(pattern, ")$"), useCaseSensitiveFileNames).test(fileName);
119692         });
119693     }
119694     ts.getMatchedIncludeSpec = getMatchedIncludeSpec;
119695     function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) {
119696         var _a, _b;
119697         var options = program.getCompilerOptions();
119698         if (ts.isReferencedFile(reason)) {
119699             var referenceLocation = ts.getReferencedFileLocation(function (path) { return program.getSourceFileByPath(path); }, reason);
119700             var referenceText = ts.isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : "\"".concat(referenceLocation.text, "\"");
119701             var message = void 0;
119702             ts.Debug.assert(ts.isReferenceFileLocation(referenceLocation) || reason.kind === ts.FileIncludeKind.Import, "Only synthetic references are imports");
119703             switch (reason.kind) {
119704                 case ts.FileIncludeKind.Import:
119705                     if (ts.isReferenceFileLocation(referenceLocation)) {
119706                         message = referenceLocation.packageId ?
119707                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2 :
119708                             ts.Diagnostics.Imported_via_0_from_file_1;
119709                     }
119710                     else if (referenceLocation.text === ts.externalHelpersModuleNameText) {
119711                         message = referenceLocation.packageId ?
119712                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions :
119713                             ts.Diagnostics.Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions;
119714                     }
119715                     else {
119716                         message = referenceLocation.packageId ?
119717                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions :
119718                             ts.Diagnostics.Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions;
119719                     }
119720                     break;
119721                 case ts.FileIncludeKind.ReferenceFile:
119722                     ts.Debug.assert(!referenceLocation.packageId);
119723                     message = ts.Diagnostics.Referenced_via_0_from_file_1;
119724                     break;
119725                 case ts.FileIncludeKind.TypeReferenceDirective:
119726                     message = referenceLocation.packageId ?
119727                         ts.Diagnostics.Type_library_referenced_via_0_from_file_1_with_packageId_2 :
119728                         ts.Diagnostics.Type_library_referenced_via_0_from_file_1;
119729                     break;
119730                 case ts.FileIncludeKind.LibReferenceDirective:
119731                     ts.Debug.assert(!referenceLocation.packageId);
119732                     message = ts.Diagnostics.Library_referenced_via_0_from_file_1;
119733                     break;
119734                 default:
119735                     ts.Debug.assertNever(reason);
119736             }
119737             return ts.chainDiagnosticMessages(
119738             /*details*/ undefined, message, referenceText, toFileName(referenceLocation.file, fileNameConvertor), referenceLocation.packageId && ts.packageIdToString(referenceLocation.packageId));
119739         }
119740         switch (reason.kind) {
119741             case ts.FileIncludeKind.RootFile:
119742                 if (!((_a = options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs))
119743                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
119744                 var fileName = ts.getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory());
119745                 var matchedByFiles = getMatchedFileSpec(program, fileName);
119746                 if (matchedByFiles)
119747                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json);
119748                 var matchedByInclude = getMatchedIncludeSpec(program, fileName);
119749                 return matchedByInclude ?
119750                     ts.chainDiagnosticMessages(
119751                     /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) :
119752                     // Could be additional files specified as roots
119753                     ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
119754             case ts.FileIncludeKind.SourceFromProjectReference:
119755             case ts.FileIncludeKind.OutputFromProjectReference:
119756                 var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference;
119757                 var referencedResolvedRef = ts.Debug.checkDefined((_b = program.getResolvedProjectReferences()) === null || _b === void 0 ? void 0 : _b[reason.index]);
119758                 return ts.chainDiagnosticMessages(
119759                 /*details*/ undefined, ts.outFile(options) ?
119760                     isOutput ?
119761                         ts.Diagnostics.Output_from_referenced_project_0_included_because_1_specified :
119762                         ts.Diagnostics.Source_from_referenced_project_0_included_because_1_specified :
119763                     isOutput ?
119764                         ts.Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none :
119765                         ts.Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out");
119766             case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
119767                 return ts.chainDiagnosticMessages(
119768                 /*details*/ undefined, options.types ?
119769                     reason.packageId ?
119770                         ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1 :
119771                         ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions :
119772                     reason.packageId ?
119773                         ts.Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1 :
119774                         ts.Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference, reason.packageId && ts.packageIdToString(reason.packageId));
119775             case ts.FileIncludeKind.LibFile:
119776                 if (reason.index !== undefined)
119777                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]);
119778                 var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === ts.getEmitScriptTarget(options) ? key : undefined; });
119779                 return ts.chainDiagnosticMessages(
119780                 /*details*/ undefined, target ?
119781                     ts.Diagnostics.Default_library_for_target_0 :
119782                     ts.Diagnostics.Default_library, target);
119783             default:
119784                 ts.Debug.assertNever(reason);
119785         }
119786     }
119787     ts.fileIncludeReasonToDiagnostics = fileIncludeReasonToDiagnostics;
119788     function toFileName(file, fileNameConvertor) {
119789         var fileName = ts.isString(file) ? file : file.fileName;
119790         return fileNameConvertor ? fileNameConvertor(fileName) : fileName;
119791     }
119792     /**
119793      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
119794      */
119795     function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
119796         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
119797         // First get and report any syntactic errors.
119798         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
119799         var configFileParsingDiagnosticsLength = allDiagnostics.length;
119800         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
119801         // If we didn't have any syntactic errors, then also try getting the global and
119802         // semantic errors.
119803         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
119804             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
119805             if (!isListFilesOnly) {
119806                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
119807                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
119808                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
119809                 }
119810             }
119811         }
119812         // Emit and report any errors we ran into.
119813         var emitResult = isListFilesOnly
119814             ? { emitSkipped: true, diagnostics: ts.emptyArray }
119815             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
119816         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
119817         ts.addRange(allDiagnostics, emitDiagnostics);
119818         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
119819         diagnostics.forEach(reportDiagnostic);
119820         if (write) {
119821             var currentDir_1 = program.getCurrentDirectory();
119822             ts.forEach(emittedFiles, function (file) {
119823                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
119824                 write("TSFILE: ".concat(filepath));
119825             });
119826             listFiles(program, write);
119827         }
119828         if (reportSummary) {
119829             reportSummary(getErrorCountForSummary(diagnostics));
119830         }
119831         return {
119832             emitResult: emitResult,
119833             diagnostics: diagnostics,
119834         };
119835     }
119836     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
119837     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
119838         var _a = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
119839         if (emitResult.emitSkipped && diagnostics.length > 0) {
119840             // If the emitter didn't emit anything, then pass that value along.
119841             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
119842         }
119843         else if (diagnostics.length > 0) {
119844             // The emitter emitted something, inform the caller if that happened in the presence
119845             // of diagnostics or not.
119846             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
119847         }
119848         return ts.ExitStatus.Success;
119849     }
119850     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
119851     ts.noopFileWatcher = { close: ts.noop };
119852     ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
119853     function createWatchHost(system, reportWatchStatus) {
119854         if (system === void 0) { system = ts.sys; }
119855         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
119856         return {
119857             onWatchStatusChange: onWatchStatusChange,
119858             watchFile: ts.maybeBind(system, system.watchFile) || ts.returnNoopFileWatcher,
119859             watchDirectory: ts.maybeBind(system, system.watchDirectory) || ts.returnNoopFileWatcher,
119860             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
119861             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
119862         };
119863     }
119864     ts.createWatchHost = createWatchHost;
119865     ts.WatchType = {
119866         ConfigFile: "Config file",
119867         ExtendedConfigFile: "Extended config file",
119868         SourceFile: "Source file",
119869         MissingFile: "Missing file",
119870         WildcardDirectory: "Wild card directory",
119871         FailedLookupLocations: "Failed Lookup Locations",
119872         TypeRoots: "Type roots",
119873         ConfigFileOfReferencedProject: "Config file of referened project",
119874         ExtendedConfigOfReferencedProject: "Extended config file of referenced project",
119875         WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project",
119876         PackageJson: "package.json file",
119877     };
119878     function createWatchFactory(host, options) {
119879         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
119880         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
119881         var result = ts.getWatchFactory(host, watchLogLevel, writeLog);
119882         result.writeLog = writeLog;
119883         return result;
119884     }
119885     ts.createWatchFactory = createWatchFactory;
119886     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
119887         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
119888         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
119889         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
119890         return {
119891             getSourceFile: function (fileName, languageVersion, onError) {
119892                 var text;
119893                 try {
119894                     ts.performance.mark("beforeIORead");
119895                     text = host.readFile(fileName, getCompilerOptions().charset);
119896                     ts.performance.mark("afterIORead");
119897                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
119898                 }
119899                 catch (e) {
119900                     if (onError) {
119901                         onError(e.message);
119902                     }
119903                     text = "";
119904                 }
119905                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
119906             },
119907             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
119908             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
119909             writeFile: writeFile,
119910             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
119911             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
119912             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
119913             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
119914             fileExists: function (f) { return host.fileExists(f); },
119915             readFile: function (f) { return host.readFile(f); },
119916             trace: ts.maybeBind(host, host.trace),
119917             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
119918             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
119919             realpath: ts.maybeBind(host, host.realpath),
119920             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
119921             createHash: ts.maybeBind(host, host.createHash),
119922             readDirectory: ts.maybeBind(host, host.readDirectory),
119923             disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature,
119924         };
119925         function writeFile(fileName, text, writeByteOrderMark, onError) {
119926             try {
119927                 ts.performance.mark("beforeIOWrite");
119928                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
119929                 // the host.writeFile will do its own directory creation and
119930                 // the ensureDirectoriesExist call will always be redundant.
119931                 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); });
119932                 ts.performance.mark("afterIOWrite");
119933                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
119934             }
119935             catch (e) {
119936                 if (onError) {
119937                     onError(e.message);
119938                 }
119939             }
119940         }
119941     }
119942     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
119943     function setGetSourceFileAsHashVersioned(compilerHost, host) {
119944         var originalGetSourceFile = compilerHost.getSourceFile;
119945         var computeHash = ts.maybeBind(host, host.createHash) || ts.generateDjb2Hash;
119946         compilerHost.getSourceFile = function () {
119947             var args = [];
119948             for (var _i = 0; _i < arguments.length; _i++) {
119949                 args[_i] = arguments[_i];
119950             }
119951             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false));
119952             if (result) {
119953                 result.version = computeHash(result.text);
119954             }
119955             return result;
119956         };
119957     }
119958     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
119959     /**
119960      * Creates the watch compiler host that can be extended with config file or root file names and options host
119961      */
119962     function createProgramHost(system, createProgram) {
119963         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
119964         return {
119965             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
119966             getNewLine: function () { return system.newLine; },
119967             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
119968             getDefaultLibLocation: getDefaultLibLocation,
119969             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
119970             fileExists: function (path) { return system.fileExists(path); },
119971             readFile: function (path, encoding) { return system.readFile(path, encoding); },
119972             directoryExists: function (path) { return system.directoryExists(path); },
119973             getDirectories: function (path) { return system.getDirectories(path); },
119974             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
119975             realpath: ts.maybeBind(system, system.realpath),
119976             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
119977             trace: function (s) { return system.write(s + system.newLine); },
119978             createDirectory: function (path) { return system.createDirectory(path); },
119979             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
119980             createHash: ts.maybeBind(system, system.createHash),
119981             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram,
119982             disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature,
119983         };
119984     }
119985     ts.createProgramHost = createProgramHost;
119986     /**
119987      * Creates the watch compiler host that can be extended with config file or root file names and options host
119988      */
119989     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
119990         if (system === void 0) { system = ts.sys; }
119991         var write = function (s) { return system.write(s + system.newLine); };
119992         var result = createProgramHost(system, createProgram);
119993         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
119994         result.afterProgramCreate = function (builderProgram) {
119995             var compilerOptions = builderProgram.getCompilerOptions();
119996             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
119997             emitFilesAndReportErrors(builderProgram, reportDiagnostic, write, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
119998         };
119999         return result;
120000     }
120001     /**
120002      * Report error and exit
120003      */
120004     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
120005         reportDiagnostic(diagnostic);
120006         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
120007     }
120008     /**
120009      * Creates the watch compiler host from system for config file in watch mode
120010      */
120011     function createWatchCompilerHostOfConfigFile(_a) {
120012         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;
120013         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
120014         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
120015         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
120016         host.configFileName = configFileName;
120017         host.optionsToExtend = optionsToExtend;
120018         host.watchOptionsToExtend = watchOptionsToExtend;
120019         host.extraFileExtensions = extraFileExtensions;
120020         return host;
120021     }
120022     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
120023     /**
120024      * Creates the watch compiler host from system for compiling root files and options in watch mode
120025      */
120026     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
120027         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;
120028         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
120029         host.rootFiles = rootFiles;
120030         host.options = options;
120031         host.watchOptions = watchOptions;
120032         host.projectReferences = projectReferences;
120033         return host;
120034     }
120035     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
120036     function performIncrementalCompilation(input) {
120037         var system = input.system || ts.sys;
120038         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
120039         var builderProgram = ts.createIncrementalProgram(input);
120040         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);
120041         if (input.afterProgramEmitAndDiagnostics)
120042             input.afterProgramEmitAndDiagnostics(builderProgram);
120043         return exitStatus;
120044     }
120045     ts.performIncrementalCompilation = performIncrementalCompilation;
120046 })(ts || (ts = {}));
120047 var ts;
120048 (function (ts) {
120049     function readBuilderProgram(compilerOptions, host) {
120050         if (ts.outFile(compilerOptions))
120051             return undefined;
120052         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
120053         if (!buildInfoPath)
120054             return undefined;
120055         var content = host.readFile(buildInfoPath);
120056         if (!content)
120057             return undefined;
120058         var buildInfo = ts.getBuildInfo(content);
120059         if (buildInfo.version !== ts.version)
120060             return undefined;
120061         if (!buildInfo.program)
120062             return undefined;
120063         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
120064     }
120065     ts.readBuilderProgram = readBuilderProgram;
120066     function createIncrementalCompilerHost(options, system) {
120067         if (system === void 0) { system = ts.sys; }
120068         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
120069         host.createHash = ts.maybeBind(system, system.createHash);
120070         host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature;
120071         ts.setGetSourceFileAsHashVersioned(host, system);
120072         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
120073         return host;
120074     }
120075     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
120076     function createIncrementalProgram(_a) {
120077         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
120078         host = host || createIncrementalCompilerHost(options);
120079         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
120080         var oldProgram = readBuilderProgram(options, host);
120081         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
120082     }
120083     ts.createIncrementalProgram = createIncrementalProgram;
120084     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
120085         if (ts.isArray(rootFilesOrConfigFileName)) {
120086             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
120087                 rootFiles: rootFilesOrConfigFileName,
120088                 options: options,
120089                 watchOptions: watchOptionsOrExtraFileExtensions,
120090                 projectReferences: projectReferencesOrWatchOptionsToExtend,
120091                 system: system,
120092                 createProgram: createProgram,
120093                 reportDiagnostic: reportDiagnostic,
120094                 reportWatchStatus: reportWatchStatus,
120095             });
120096         }
120097         else {
120098             return ts.createWatchCompilerHostOfConfigFile({
120099                 configFileName: rootFilesOrConfigFileName,
120100                 optionsToExtend: options,
120101                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
120102                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
120103                 system: system,
120104                 createProgram: createProgram,
120105                 reportDiagnostic: reportDiagnostic,
120106                 reportWatchStatus: reportWatchStatus,
120107             });
120108         }
120109     }
120110     ts.createWatchCompilerHost = createWatchCompilerHost;
120111     function createWatchProgram(host) {
120112         var builderProgram;
120113         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
120114         var missingFilesMap; // Map of file watchers for the missing files
120115         var packageJsonMap; // map of watchers for package json files used in module resolution
120116         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
120117         var timerToUpdateProgram; // timer callback to recompile the program
120118         var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
120119         var parsedConfigs; // Parsed commandline and watching cached for referenced projects
120120         var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects
120121         var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation
120122         var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution
120123         var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
120124         var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files
120125         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
120126         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
120127         var currentDirectory = host.getCurrentDirectory();
120128         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
120129         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
120130         var wildcardDirectories;
120131         var configFileParsingDiagnostics;
120132         var canConfigFileJsonReportNoInputFiles = false;
120133         var hasChangedConfigFileParsingErrors = false;
120134         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
120135         var directoryStructureHost = cachedDirectoryStructureHost || host;
120136         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
120137         // From tsc we want to get already parsed result and hence check for rootFileNames
120138         var newLine = updateNewLine();
120139         if (configFileName && host.configFileParsingResult) {
120140             setConfigFileParsingResult(host.configFileParsingResult);
120141             newLine = updateNewLine();
120142         }
120143         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
120144         if (configFileName && !host.configFileParsingResult) {
120145             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
120146             ts.Debug.assert(!rootFileNames);
120147             parseConfigFile();
120148             newLine = updateNewLine();
120149         }
120150         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
120151         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
120152         writeLog("Current directory: ".concat(currentDirectory, " CaseSensitiveFileNames: ").concat(useCaseSensitiveFileNames));
120153         var configFileWatcher;
120154         if (configFileName) {
120155             configFileWatcher = watchFile(configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
120156         }
120157         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
120158         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
120159         // Members for CompilerHost
120160         var getNewSourceFile = compilerHost.getSourceFile;
120161         compilerHost.getSourceFile = function (fileName) {
120162             var args = [];
120163             for (var _i = 1; _i < arguments.length; _i++) {
120164                 args[_i - 1] = arguments[_i];
120165             }
120166             return getVersionedSourceFileByPath.apply(void 0, __spreadArray([fileName, toPath(fileName)], args, false));
120167         };
120168         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
120169         compilerHost.getNewLine = function () { return newLine; };
120170         compilerHost.fileExists = fileExists;
120171         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
120172         compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine;
120173         // Members for ResolutionCacheHost
120174         compilerHost.toPath = toPath;
120175         compilerHost.getCompilationSettings = function () { return compilerOptions; };
120176         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
120177         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
120178         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
120179         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
120180         compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
120181         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
120182         compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
120183         compilerHost.fileIsOpen = ts.returnFalse;
120184         compilerHost.getCurrentProgram = getCurrentProgram;
120185         compilerHost.writeLog = writeLog;
120186         compilerHost.getParsedCommandLine = getParsedCommandLine;
120187         // Cache for the module resolution
120188         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
120189             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
120190             currentDirectory, 
120191         /*logChangesWhenResolvingModule*/ false);
120192         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
120193         compilerHost.resolveModuleNames = host.resolveModuleNames ?
120194             (function () {
120195                 var args = [];
120196                 for (var _i = 0; _i < arguments.length; _i++) {
120197                     args[_i] = arguments[_i];
120198                 }
120199                 return host.resolveModuleNames.apply(host, args);
120200             }) :
120201             (function (moduleNames, containingFile, reusedNames, redirectedReference, _options, sourceFile) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, sourceFile); });
120202         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
120203             (function () {
120204                 var args = [];
120205                 for (var _i = 0; _i < arguments.length; _i++) {
120206                     args[_i] = arguments[_i];
120207                 }
120208                 return host.resolveTypeReferenceDirectives.apply(host, args);
120209             }) :
120210             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
120211         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
120212         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
120213         synchronizeProgram();
120214         // Update the wild card directory watch
120215         watchConfigFileWildCardDirectories();
120216         // Update extended config file watch
120217         if (configFileName)
120218             updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile);
120219         return configFileName ?
120220             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
120221             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
120222         function close() {
120223             clearInvalidateResolutionsOfFailedLookupLocations();
120224             resolutionCache.clear();
120225             ts.clearMap(sourceFilesCache, function (value) {
120226                 if (value && value.fileWatcher) {
120227                     value.fileWatcher.close();
120228                     value.fileWatcher = undefined;
120229                 }
120230             });
120231             if (configFileWatcher) {
120232                 configFileWatcher.close();
120233                 configFileWatcher = undefined;
120234             }
120235             extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear();
120236             extendedConfigCache = undefined;
120237             if (sharedExtendedConfigFileWatchers) {
120238                 ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf);
120239                 sharedExtendedConfigFileWatchers = undefined;
120240             }
120241             if (watchedWildcardDirectories) {
120242                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
120243                 watchedWildcardDirectories = undefined;
120244             }
120245             if (missingFilesMap) {
120246                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
120247                 missingFilesMap = undefined;
120248             }
120249             if (parsedConfigs) {
120250                 ts.clearMap(parsedConfigs, function (config) {
120251                     var _a;
120252                     (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close();
120253                     config.watcher = undefined;
120254                     if (config.watchedDirectories)
120255                         ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf);
120256                     config.watchedDirectories = undefined;
120257                 });
120258                 parsedConfigs = undefined;
120259             }
120260             if (packageJsonMap) {
120261                 ts.clearMap(packageJsonMap, ts.closeFileWatcher);
120262                 packageJsonMap = undefined;
120263             }
120264         }
120265         function getCurrentBuilderProgram() {
120266             return builderProgram;
120267         }
120268         function getCurrentProgram() {
120269             return builderProgram && builderProgram.getProgramOrUndefined();
120270         }
120271         function synchronizeProgram() {
120272             writeLog("Synchronizing program");
120273             clearInvalidateResolutionsOfFailedLookupLocations();
120274             var program = getCurrentBuilderProgram();
120275             if (hasChangedCompilerOptions) {
120276                 newLine = updateNewLine();
120277                 if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) {
120278                     resolutionCache.clear();
120279                 }
120280             }
120281             // All resolutions are invalid if user provided resolutions
120282             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution);
120283             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
120284                 if (hasChangedConfigFileParsingErrors) {
120285                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
120286                     hasChangedConfigFileParsingErrors = false;
120287                 }
120288             }
120289             else {
120290                 createNewProgram(hasInvalidatedResolution);
120291             }
120292             changesAffectResolution = false; // reset for next sync
120293             if (host.afterProgramCreate && program !== builderProgram) {
120294                 host.afterProgramCreate(builderProgram);
120295             }
120296             return builderProgram;
120297         }
120298         function createNewProgram(hasInvalidatedResolution) {
120299             // Compile the program
120300             writeLog("CreatingProgramWith::");
120301             writeLog("  roots: ".concat(JSON.stringify(rootFileNames)));
120302             writeLog("  options: ".concat(JSON.stringify(compilerOptions)));
120303             if (projectReferences)
120304                 writeLog("  projectReferences: ".concat(JSON.stringify(projectReferences)));
120305             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
120306             hasChangedCompilerOptions = false;
120307             hasChangedConfigFileParsingErrors = false;
120308             resolutionCache.startCachingPerDirectoryResolution();
120309             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
120310             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
120311             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
120312             // map package json cache entries to their realpaths so we don't try to watch across symlinks
120313             var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) {
120314                 var path = _a[0], data = _a[1];
120315                 return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data];
120316             });
120317             resolutionCache.finishCachingPerDirectoryResolution();
120318             // Update watches
120319             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
120320             ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath);
120321             if (needsUpdateInTypeRootWatch) {
120322                 resolutionCache.updateTypeRootsWatch();
120323             }
120324             if (missingFilePathsRequestedForRelease) {
120325                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
120326                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
120327                 // if there is already watcher for it (for missing files)
120328                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
120329                 // so that at later time we have correct result of their presence
120330                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
120331                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
120332                     if (!missingFilesMap.has(missingFilePath)) {
120333                         sourceFilesCache.delete(missingFilePath);
120334                     }
120335                 }
120336                 missingFilePathsRequestedForRelease = undefined;
120337             }
120338         }
120339         function updateRootFileNames(files) {
120340             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
120341             rootFileNames = files;
120342             scheduleProgramUpdate();
120343         }
120344         function updateNewLine() {
120345             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
120346         }
120347         function toPath(fileName) {
120348             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
120349         }
120350         function isFileMissingOnHost(hostSourceFile) {
120351             return typeof hostSourceFile === "boolean";
120352         }
120353         function isFilePresenceUnknownOnHost(hostSourceFile) {
120354             return typeof hostSourceFile.version === "boolean";
120355         }
120356         function fileExists(fileName) {
120357             var path = toPath(fileName);
120358             // If file is missing on host from cache, we can definitely say file doesnt exist
120359             // otherwise we need to ensure from the disk
120360             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
120361                 return false;
120362             }
120363             return directoryStructureHost.fileExists(fileName);
120364         }
120365         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
120366             var hostSourceFile = sourceFilesCache.get(path);
120367             // No source file on the host
120368             if (isFileMissingOnHost(hostSourceFile)) {
120369                 return undefined;
120370             }
120371             // Create new source file if requested or the versions dont match
120372             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
120373                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
120374                 if (hostSourceFile) {
120375                     if (sourceFile) {
120376                         // Set the source file and create file watcher now that file was present on the disk
120377                         hostSourceFile.sourceFile = sourceFile;
120378                         hostSourceFile.version = sourceFile.version;
120379                         if (!hostSourceFile.fileWatcher) {
120380                             hostSourceFile.fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
120381                         }
120382                     }
120383                     else {
120384                         // There is no source file on host any more, close the watch, missing file paths will track it
120385                         if (hostSourceFile.fileWatcher) {
120386                             hostSourceFile.fileWatcher.close();
120387                         }
120388                         sourceFilesCache.set(path, false);
120389                     }
120390                 }
120391                 else {
120392                     if (sourceFile) {
120393                         var fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
120394                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
120395                     }
120396                     else {
120397                         sourceFilesCache.set(path, false);
120398                     }
120399                 }
120400                 if (sourceFile) {
120401                     sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings());
120402                 }
120403                 return sourceFile;
120404             }
120405             return hostSourceFile.sourceFile;
120406         }
120407         function nextSourceFileVersion(path) {
120408             var hostSourceFile = sourceFilesCache.get(path);
120409             if (hostSourceFile !== undefined) {
120410                 if (isFileMissingOnHost(hostSourceFile)) {
120411                     // The next version, lets set it as presence unknown file
120412                     sourceFilesCache.set(path, { version: false });
120413                 }
120414                 else {
120415                     hostSourceFile.version = false;
120416                 }
120417             }
120418         }
120419         function getSourceVersion(path) {
120420             var hostSourceFile = sourceFilesCache.get(path);
120421             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
120422         }
120423         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
120424             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
120425             // If this is the source file thats in the cache and new program doesnt need it,
120426             // remove the cached entry.
120427             // Note we arent deleting entry if file became missing in new program or
120428             // there was version update and new source file was created.
120429             if (hostSourceFileInfo !== undefined) {
120430                 // record the missing file paths so they can be removed later if watchers arent tracking them
120431                 if (isFileMissingOnHost(hostSourceFileInfo)) {
120432                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
120433                 }
120434                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
120435                     if (hostSourceFileInfo.fileWatcher) {
120436                         hostSourceFileInfo.fileWatcher.close();
120437                     }
120438                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
120439                     if (!hasSourceFileByPath) {
120440                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
120441                     }
120442                 }
120443             }
120444         }
120445         function reportWatchDiagnostic(message) {
120446             if (host.onWatchStatusChange) {
120447                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
120448             }
120449         }
120450         function hasChangedAutomaticTypeDirectiveNames() {
120451             return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
120452         }
120453         function clearInvalidateResolutionsOfFailedLookupLocations() {
120454             if (!timerToInvalidateFailedLookupResolutions)
120455                 return false;
120456             host.clearTimeout(timerToInvalidateFailedLookupResolutions);
120457             timerToInvalidateFailedLookupResolutions = undefined;
120458             return true;
120459         }
120460         function scheduleInvalidateResolutionsOfFailedLookupLocations() {
120461             if (!host.setTimeout || !host.clearTimeout) {
120462                 return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
120463             }
120464             var pending = clearInvalidateResolutionsOfFailedLookupLocations();
120465             writeLog("Scheduling invalidateFailedLookup".concat(pending ? ", Cancelled earlier one" : ""));
120466             timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
120467         }
120468         function invalidateResolutionsOfFailedLookup() {
120469             timerToInvalidateFailedLookupResolutions = undefined;
120470             if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
120471                 scheduleProgramUpdate();
120472             }
120473         }
120474         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
120475         // operations (such as saving all modified files in an editor) a chance to complete before we kick
120476         // off a new compilation.
120477         function scheduleProgramUpdate() {
120478             if (!host.setTimeout || !host.clearTimeout) {
120479                 return;
120480             }
120481             if (timerToUpdateProgram) {
120482                 host.clearTimeout(timerToUpdateProgram);
120483             }
120484             writeLog("Scheduling update");
120485             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
120486         }
120487         function scheduleProgramReload() {
120488             ts.Debug.assert(!!configFileName);
120489             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
120490             scheduleProgramUpdate();
120491         }
120492         function updateProgramWithWatchStatus() {
120493             timerToUpdateProgram = undefined;
120494             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
120495             updateProgram();
120496         }
120497         function updateProgram() {
120498             switch (reloadLevel) {
120499                 case ts.ConfigFileProgramReloadLevel.Partial:
120500                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
120501                     reloadFileNamesFromConfigFile();
120502                     break;
120503                 case ts.ConfigFileProgramReloadLevel.Full:
120504                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
120505                     reloadConfigFile();
120506                     break;
120507                 default:
120508                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
120509                     synchronizeProgram();
120510                     break;
120511             }
120512             ts.perfLogger.logStopUpdateProgram("Done");
120513             return getCurrentBuilderProgram();
120514         }
120515         function reloadFileNamesFromConfigFile() {
120516             writeLog("Reloading new file names and options");
120517             rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
120518             if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
120519                 hasChangedConfigFileParsingErrors = true;
120520             }
120521             // Update the program
120522             synchronizeProgram();
120523         }
120524         function reloadConfigFile() {
120525             writeLog("Reloading config file: ".concat(configFileName));
120526             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
120527             if (cachedDirectoryStructureHost) {
120528                 cachedDirectoryStructureHost.clearCache();
120529             }
120530             parseConfigFile();
120531             hasChangedCompilerOptions = true;
120532             synchronizeProgram();
120533             // Update the wild card directory watch
120534             watchConfigFileWildCardDirectories();
120535             // Update extended config file watch
120536             updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile);
120537         }
120538         function parseConfigFile() {
120539             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
120540         }
120541         function setConfigFileParsingResult(configFileParseResult) {
120542             rootFileNames = configFileParseResult.fileNames;
120543             compilerOptions = configFileParseResult.options;
120544             watchOptions = configFileParseResult.watchOptions;
120545             projectReferences = configFileParseResult.projectReferences;
120546             wildcardDirectories = configFileParseResult.wildcardDirectories;
120547             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
120548             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
120549             hasChangedConfigFileParsingErrors = true;
120550         }
120551         function getParsedCommandLine(configFileName) {
120552             var configPath = toPath(configFileName);
120553             var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath);
120554             if (config) {
120555                 if (!config.reloadLevel)
120556                     return config.parsedCommandLine;
120557                 // With host implementing getParsedCommandLine we cant just update file names
120558                 if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) {
120559                     writeLog("Reloading new file names and options");
120560                     var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
120561                     config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames });
120562                     config.reloadLevel = undefined;
120563                     return config.parsedCommandLine;
120564                 }
120565             }
120566             writeLog("Loading config file: ".concat(configFileName));
120567             var parsedCommandLine = host.getParsedCommandLine ?
120568                 host.getParsedCommandLine(configFileName) :
120569                 getParsedCommandLineFromConfigFileHost(configFileName);
120570             if (config) {
120571                 config.parsedCommandLine = parsedCommandLine;
120572                 config.reloadLevel = undefined;
120573             }
120574             else {
120575                 (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine });
120576             }
120577             watchReferencedProject(configFileName, configPath, config);
120578             return parsedCommandLine;
120579         }
120580         function getParsedCommandLineFromConfigFileHost(configFileName) {
120581             // Ignore the file absent errors
120582             var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic;
120583             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
120584             var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, 
120585             /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend);
120586             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic;
120587             return parsedCommandLine;
120588         }
120589         function onReleaseParsedCommandLine(fileName) {
120590             var _a;
120591             var path = toPath(fileName);
120592             var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path);
120593             if (!config)
120594                 return;
120595             parsedConfigs.delete(path);
120596             if (config.watchedDirectories)
120597                 ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf);
120598             (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close();
120599             ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers);
120600         }
120601         function watchFilePath(path, file, callback, pollingInterval, options, watchType) {
120602             return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType);
120603         }
120604         function onSourceFileChange(fileName, eventKind, path) {
120605             updateCachedSystemWithFile(fileName, path, eventKind);
120606             // Update the source file cache
120607             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
120608                 resolutionCache.invalidateResolutionOfFile(path);
120609             }
120610             nextSourceFileVersion(path);
120611             // Update the program
120612             scheduleProgramUpdate();
120613         }
120614         function updateCachedSystemWithFile(fileName, path, eventKind) {
120615             if (cachedDirectoryStructureHost) {
120616                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
120617             }
120618         }
120619         function watchMissingFilePath(missingFilePath) {
120620             // If watching missing referenced config file, we are already watching it so no need for separate watcher
120621             return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ?
120622                 ts.noopFileWatcher :
120623                 watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile);
120624         }
120625         function watchPackageJsonLookupPath(packageJsonPath) {
120626             // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here
120627             return sourceFilesCache.has(packageJsonPath) ?
120628                 ts.noopFileWatcher :
120629                 watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson);
120630         }
120631         function onPackageJsonChange(fileName, eventKind, path) {
120632             updateCachedSystemWithFile(fileName, path, eventKind);
120633             // package.json changes invalidate module resolution and can change the set of loaded files
120634             // so if we witness a change to one, we have to do a full reload
120635             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
120636             changesAffectResolution = true;
120637             // Update the program
120638             scheduleProgramUpdate();
120639         }
120640         function onMissingFileChange(fileName, eventKind, missingFilePath) {
120641             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
120642             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
120643                 missingFilesMap.get(missingFilePath).close();
120644                 missingFilesMap.delete(missingFilePath);
120645                 // Delete the entry in the source files cache so that new source file is created
120646                 nextSourceFileVersion(missingFilePath);
120647                 // When a missing file is created, we should update the graph.
120648                 scheduleProgramUpdate();
120649             }
120650         }
120651         function watchConfigFileWildCardDirectories() {
120652             if (wildcardDirectories) {
120653                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(wildcardDirectories)), watchWildcardDirectory);
120654             }
120655             else if (watchedWildcardDirectories) {
120656                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
120657             }
120658         }
120659         function watchWildcardDirectory(directory, flags) {
120660             return watchDirectory(directory, function (fileOrDirectory) {
120661                 ts.Debug.assert(!!configFileName);
120662                 var fileOrDirectoryPath = toPath(fileOrDirectory);
120663                 // Since the file existence changed, update the sourceFiles cache
120664                 if (cachedDirectoryStructureHost) {
120665                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
120666                 }
120667                 nextSourceFileVersion(fileOrDirectoryPath);
120668                 if (ts.isIgnoredFileFromWildCardWatching({
120669                     watchedDirPath: toPath(directory),
120670                     fileOrDirectory: fileOrDirectory,
120671                     fileOrDirectoryPath: fileOrDirectoryPath,
120672                     configFileName: configFileName,
120673                     extraFileExtensions: extraFileExtensions,
120674                     options: compilerOptions,
120675                     program: getCurrentBuilderProgram() || rootFileNames,
120676                     currentDirectory: currentDirectory,
120677                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
120678                     writeLog: writeLog,
120679                     toPath: toPath,
120680                 }))
120681                     return;
120682                 // Reload is pending, do the reload
120683                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
120684                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
120685                     // Schedule Update the program
120686                     scheduleProgramUpdate();
120687                 }
120688             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
120689         }
120690         function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) {
120691             ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) {
120692                 var _a;
120693                 updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind);
120694                 // Update extended config cache
120695                 if (extendedConfigCache)
120696                     ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath);
120697                 // Update projects
120698                 var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects;
120699                 // If there are no referenced projects this extended config file watcher depend on ignore
120700                 if (!(projects === null || projects === void 0 ? void 0 : projects.size))
120701                     return;
120702                 projects.forEach(function (projectPath) {
120703                     if (toPath(configFileName) === projectPath) {
120704                         // If this is the config file of the project, reload completely
120705                         reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
120706                     }
120707                     else {
120708                         // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed
120709                         var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath);
120710                         if (config)
120711                             config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
120712                         resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath);
120713                     }
120714                     scheduleProgramUpdate();
120715                 });
120716             }, ts.PollingInterval.High, watchOptions, watchType); }, toPath);
120717         }
120718         function watchReferencedProject(configFileName, configPath, commandLine) {
120719             var _a, _b, _c, _d, _e;
120720             // Watch file
120721             commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) {
120722                 updateCachedSystemWithFile(configFileName, configPath, eventKind);
120723                 var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath);
120724                 if (config)
120725                     config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
120726                 resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath);
120727                 scheduleProgramUpdate();
120728             }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject));
120729             // Watch Wild card
120730             if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) {
120731                 ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) {
120732                     var _a;
120733                     return watchDirectory(directory, function (fileOrDirectory) {
120734                         var fileOrDirectoryPath = toPath(fileOrDirectory);
120735                         // Since the file existence changed, update the sourceFiles cache
120736                         if (cachedDirectoryStructureHost) {
120737                             cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
120738                         }
120739                         nextSourceFileVersion(fileOrDirectoryPath);
120740                         var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath);
120741                         if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine))
120742                             return;
120743                         if (ts.isIgnoredFileFromWildCardWatching({
120744                             watchedDirPath: toPath(directory),
120745                             fileOrDirectory: fileOrDirectory,
120746                             fileOrDirectoryPath: fileOrDirectoryPath,
120747                             configFileName: configFileName,
120748                             options: config.parsedCommandLine.options,
120749                             program: config.parsedCommandLine.fileNames,
120750                             currentDirectory: currentDirectory,
120751                             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
120752                             writeLog: writeLog,
120753                             toPath: toPath,
120754                         }))
120755                             return;
120756                         // Reload is pending, do the reload
120757                         if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
120758                             config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
120759                             // Schedule Update the program
120760                             scheduleProgramUpdate();
120761                         }
120762                     }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject);
120763                 });
120764             }
120765             else if (commandLine.watchedDirectories) {
120766                 ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf);
120767                 commandLine.watchedDirectories = undefined;
120768             }
120769             // Watch extended config files
120770             updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject);
120771         }
120772     }
120773     ts.createWatchProgram = createWatchProgram;
120774 })(ts || (ts = {}));
120775 /*@internal*/
120776 var ts;
120777 (function (ts) {
120778     var UpToDateStatusType;
120779     (function (UpToDateStatusType) {
120780         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
120781         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
120782         /**
120783          * The project appears out of date because its upstream inputs are newer than its outputs,
120784          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
120785          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
120786          */
120787         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
120788         /**
120789          * The project appears out of date because its upstream inputs are newer than its outputs,
120790          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
120791          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
120792          */
120793         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
120794         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
120795         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
120796         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
120797         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
120798         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
120799         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
120800         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
120801         /**
120802          * Projects with no outputs (i.e. "solution" files)
120803          */
120804         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
120805     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
120806     function resolveConfigFileProjectName(project) {
120807         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
120808             return project;
120809         }
120810         return ts.combinePaths(project, "tsconfig.json");
120811     }
120812     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
120813 })(ts || (ts = {}));
120814 var ts;
120815 (function (ts) {
120816     var minimumDate = new Date(-8640000000000000);
120817     var maximumDate = new Date(8640000000000000);
120818     var BuildResultFlags;
120819     (function (BuildResultFlags) {
120820         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
120821         /**
120822          * No errors of any kind occurred during build
120823          */
120824         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
120825         /**
120826          * None of the .d.ts files emitted by this build were
120827          * different from the existing files on disk
120828          */
120829         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
120830         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
120831         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
120832         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
120833         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
120834         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
120835         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
120836     })(BuildResultFlags || (BuildResultFlags = {}));
120837     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
120838         var existingValue = configFileMap.get(resolved);
120839         var newValue;
120840         if (!existingValue) {
120841             newValue = createT();
120842             configFileMap.set(resolved, newValue);
120843         }
120844         return existingValue || newValue;
120845     }
120846     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
120847         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); });
120848     }
120849     function newer(date1, date2) {
120850         return date2 > date1 ? date2 : date1;
120851     }
120852     function isDeclarationFile(fileName) {
120853         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
120854     }
120855     /*@internal*/
120856     function isCircularBuildOrder(buildOrder) {
120857         return !!buildOrder && !!buildOrder.buildOrder;
120858     }
120859     ts.isCircularBuildOrder = isCircularBuildOrder;
120860     /*@internal*/
120861     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
120862         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
120863     }
120864     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
120865     /**
120866      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
120867      */
120868     function createBuilderStatusReporter(system, pretty) {
120869         return function (diagnostic) {
120870             var output = pretty ? "[".concat(ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey), "] ") : "".concat(ts.getLocaleTimeString(system), " - ");
120871             output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(system.newLine + system.newLine);
120872             system.write(output);
120873         };
120874     }
120875     ts.createBuilderStatusReporter = createBuilderStatusReporter;
120876     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
120877         var host = ts.createProgramHost(system, createProgram);
120878         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
120879         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
120880         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
120881         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
120882         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
120883         host.now = ts.maybeBind(system, system.now); // For testing
120884         return host;
120885     }
120886     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
120887         if (system === void 0) { system = ts.sys; }
120888         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
120889         host.reportErrorSummary = reportErrorSummary;
120890         return host;
120891     }
120892     ts.createSolutionBuilderHost = createSolutionBuilderHost;
120893     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
120894         if (system === void 0) { system = ts.sys; }
120895         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
120896         var watchHost = ts.createWatchHost(system, reportWatchStatus);
120897         ts.copyProperties(host, watchHost);
120898         return host;
120899     }
120900     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
120901     function getCompilerOptionsOfBuildOptions(buildOptions) {
120902         var result = {};
120903         ts.commonOptionsWithBuild.forEach(function (option) {
120904             if (ts.hasProperty(buildOptions, option.name))
120905                 result[option.name] = buildOptions[option.name];
120906         });
120907         return result;
120908     }
120909     function createSolutionBuilder(host, rootNames, defaultOptions) {
120910         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
120911     }
120912     ts.createSolutionBuilder = createSolutionBuilder;
120913     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
120914         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
120915     }
120916     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
120917     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
120918         var host = hostOrHostWithWatch;
120919         var hostWithWatch = hostOrHostWithWatch;
120920         var currentDirectory = host.getCurrentDirectory();
120921         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
120922         // State of the solution
120923         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
120924         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
120925         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
120926         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
120927         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
120928         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
120929         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
120930         var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined;
120931         if (!compilerHost.resolveModuleNames) {
120932             var loader_3 = function (moduleName, resolverMode, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference, resolverMode).resolvedModule; };
120933             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference, _options, containingSourceFile) {
120934                 return ts.loadWithModeAwareCache(ts.Debug.checkEachDefined(moduleNames), ts.Debug.checkDefined(containingSourceFile), containingFile, redirectedReference, loader_3);
120935             };
120936             compilerHost.getModuleResolutionCache = function () { return moduleResolutionCache; };
120937         }
120938         if (!compilerHost.resolveTypeReferenceDirectives) {
120939             var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; };
120940             compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) {
120941                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4);
120942             };
120943         }
120944         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
120945         var state = {
120946             host: host,
120947             hostWithWatch: hostWithWatch,
120948             currentDirectory: currentDirectory,
120949             getCanonicalFileName: getCanonicalFileName,
120950             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
120951             write: ts.maybeBind(host, host.trace),
120952             // State of solution
120953             options: options,
120954             baseCompilerOptions: baseCompilerOptions,
120955             rootNames: rootNames,
120956             baseWatchOptions: baseWatchOptions,
120957             resolvedConfigFilePaths: new ts.Map(),
120958             configFileCache: new ts.Map(),
120959             projectStatus: new ts.Map(),
120960             buildInfoChecked: new ts.Map(),
120961             extendedConfigCache: new ts.Map(),
120962             builderPrograms: new ts.Map(),
120963             diagnostics: new ts.Map(),
120964             projectPendingBuild: new ts.Map(),
120965             projectErrorsReported: new ts.Map(),
120966             compilerHost: compilerHost,
120967             moduleResolutionCache: moduleResolutionCache,
120968             typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache,
120969             // Mutable state
120970             buildOrder: undefined,
120971             readFileWithCache: function (f) { return host.readFile(f); },
120972             projectCompilerOptions: baseCompilerOptions,
120973             cache: undefined,
120974             allProjectBuildPending: true,
120975             needsSummary: true,
120976             watchAllProjectsPending: watch,
120977             currentInvalidatedProject: undefined,
120978             // Watch state
120979             watch: watch,
120980             allWatchedWildcardDirectories: new ts.Map(),
120981             allWatchedInputFiles: new ts.Map(),
120982             allWatchedConfigFiles: new ts.Map(),
120983             allWatchedExtendedConfigFiles: new ts.Map(),
120984             allWatchedPackageJsonFiles: new ts.Map(),
120985             lastCachedPackageJsonLookups: new ts.Map(),
120986             timerToBuildInvalidatedProject: undefined,
120987             reportFileChangeDetected: false,
120988             watchFile: watchFile,
120989             watchDirectory: watchDirectory,
120990             writeLog: writeLog,
120991         };
120992         return state;
120993     }
120994     function toPath(state, fileName) {
120995         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
120996     }
120997     function toResolvedConfigFilePath(state, fileName) {
120998         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
120999         var path = resolvedConfigFilePaths.get(fileName);
121000         if (path !== undefined)
121001             return path;
121002         var resolvedPath = toPath(state, fileName);
121003         resolvedConfigFilePaths.set(fileName, resolvedPath);
121004         return resolvedPath;
121005     }
121006     function isParsedCommandLine(entry) {
121007         return !!entry.options;
121008     }
121009     function getCachedParsedConfigFile(state, configFilePath) {
121010         var value = state.configFileCache.get(configFilePath);
121011         return value && isParsedCommandLine(value) ? value : undefined;
121012     }
121013     function parseConfigFile(state, configFileName, configFilePath) {
121014         var configFileCache = state.configFileCache;
121015         var value = configFileCache.get(configFilePath);
121016         if (value) {
121017             return isParsedCommandLine(value) ? value : undefined;
121018         }
121019         var diagnostic;
121020         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
121021         var parsed;
121022         if (host.getParsedCommandLine) {
121023             parsed = host.getParsedCommandLine(configFileName);
121024             if (!parsed)
121025                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
121026         }
121027         else {
121028             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
121029             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
121030             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
121031         }
121032         configFileCache.set(configFilePath, parsed || diagnostic);
121033         return parsed;
121034     }
121035     function resolveProjectName(state, name) {
121036         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
121037     }
121038     function createBuildOrder(state, roots) {
121039         var temporaryMarks = new ts.Map();
121040         var permanentMarks = new ts.Map();
121041         var circularityReportStack = [];
121042         var buildOrder;
121043         var circularDiagnostics;
121044         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
121045             var root = roots_1[_i];
121046             visit(root);
121047         }
121048         return circularDiagnostics ?
121049             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
121050             buildOrder || ts.emptyArray;
121051         function visit(configFileName, inCircularContext) {
121052             var projPath = toResolvedConfigFilePath(state, configFileName);
121053             // Already visited
121054             if (permanentMarks.has(projPath))
121055                 return;
121056             // Circular
121057             if (temporaryMarks.has(projPath)) {
121058                 if (!inCircularContext) {
121059                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
121060                 }
121061                 return;
121062             }
121063             temporaryMarks.set(projPath, true);
121064             circularityReportStack.push(configFileName);
121065             var parsed = parseConfigFile(state, configFileName, projPath);
121066             if (parsed && parsed.projectReferences) {
121067                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
121068                     var ref = _a[_i];
121069                     var resolvedRefPath = resolveProjectName(state, ref.path);
121070                     visit(resolvedRefPath, inCircularContext || ref.circular);
121071                 }
121072             }
121073             circularityReportStack.pop();
121074             permanentMarks.set(projPath, true);
121075             (buildOrder || (buildOrder = [])).push(configFileName);
121076         }
121077     }
121078     function getBuildOrder(state) {
121079         return state.buildOrder || createStateBuildOrder(state);
121080     }
121081     function createStateBuildOrder(state) {
121082         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
121083         // Clear all to ResolvedConfigFilePaths cache to start fresh
121084         state.resolvedConfigFilePaths.clear();
121085         // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues`
121086         var currentProjects = new ts.Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(function (resolved) { return [toResolvedConfigFilePath(state, resolved), true]; }));
121087         var noopOnDelete = { onDeleteValue: ts.noop };
121088         // Config file cache
121089         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
121090         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
121091         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
121092         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
121093         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
121094         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
121095         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
121096         // Remove watches for the program no longer in the solution
121097         if (state.watch) {
121098             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
121099             state.allWatchedExtendedConfigFiles.forEach(function (watcher) {
121100                 watcher.projects.forEach(function (project) {
121101                     if (!currentProjects.has(project)) {
121102                         watcher.projects.delete(project);
121103                     }
121104                 });
121105                 watcher.close();
121106             });
121107             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
121108             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
121109             ts.mutateMapSkippingNewValues(state.allWatchedPackageJsonFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
121110         }
121111         return state.buildOrder = buildOrder;
121112     }
121113     function getBuildOrderFor(state, project, onlyReferences) {
121114         var resolvedProject = project && resolveProjectName(state, project);
121115         var buildOrderFromState = getBuildOrder(state);
121116         if (isCircularBuildOrder(buildOrderFromState))
121117             return buildOrderFromState;
121118         if (resolvedProject) {
121119             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
121120             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
121121             if (projectIndex === -1)
121122                 return undefined;
121123         }
121124         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
121125         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
121126         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
121127         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
121128         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
121129     }
121130     function enableCache(state) {
121131         if (state.cache) {
121132             disableCache(state);
121133         }
121134         var compilerHost = state.compilerHost, host = state.host;
121135         var originalReadFileWithCache = state.readFileWithCache;
121136         var originalGetSourceFile = compilerHost.getSourceFile;
121137         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
121138             var args = [];
121139             for (var _i = 0; _i < arguments.length; _i++) {
121140                 args[_i] = arguments[_i];
121141             }
121142             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false));
121143         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
121144         state.readFileWithCache = readFileWithCache;
121145         compilerHost.getSourceFile = getSourceFileWithCache;
121146         state.cache = {
121147             originalReadFile: originalReadFile,
121148             originalFileExists: originalFileExists,
121149             originalDirectoryExists: originalDirectoryExists,
121150             originalCreateDirectory: originalCreateDirectory,
121151             originalWriteFile: originalWriteFile,
121152             originalReadFileWithCache: originalReadFileWithCache,
121153             originalGetSourceFile: originalGetSourceFile,
121154         };
121155     }
121156     function disableCache(state) {
121157         if (!state.cache)
121158             return;
121159         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache;
121160         host.readFile = cache.originalReadFile;
121161         host.fileExists = cache.originalFileExists;
121162         host.directoryExists = cache.originalDirectoryExists;
121163         host.createDirectory = cache.originalCreateDirectory;
121164         host.writeFile = cache.originalWriteFile;
121165         compilerHost.getSourceFile = cache.originalGetSourceFile;
121166         state.readFileWithCache = cache.originalReadFileWithCache;
121167         extendedConfigCache.clear();
121168         moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear();
121169         typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear();
121170         state.cache = undefined;
121171     }
121172     function clearProjectStatus(state, resolved) {
121173         state.projectStatus.delete(resolved);
121174         state.diagnostics.delete(resolved);
121175     }
121176     function addProjToQueue(_a, proj, reloadLevel) {
121177         var projectPendingBuild = _a.projectPendingBuild;
121178         var value = projectPendingBuild.get(proj);
121179         if (value === undefined) {
121180             projectPendingBuild.set(proj, reloadLevel);
121181         }
121182         else if (value < reloadLevel) {
121183             projectPendingBuild.set(proj, reloadLevel);
121184         }
121185     }
121186     function setupInitialBuild(state, cancellationToken) {
121187         // Set initial build if not already built
121188         if (!state.allProjectBuildPending)
121189             return;
121190         state.allProjectBuildPending = false;
121191         if (state.options.watch)
121192             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
121193         enableCache(state);
121194         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
121195         buildOrder.forEach(function (configFileName) {
121196             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
121197         });
121198         if (cancellationToken) {
121199             cancellationToken.throwIfCancellationRequested();
121200         }
121201     }
121202     var InvalidatedProjectKind;
121203     (function (InvalidatedProjectKind) {
121204         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
121205         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
121206         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
121207     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
121208     function doneInvalidatedProject(state, projectPath) {
121209         state.projectPendingBuild.delete(projectPath);
121210         state.currentInvalidatedProject = undefined;
121211         return state.diagnostics.has(projectPath) ?
121212             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
121213             ts.ExitStatus.Success;
121214     }
121215     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
121216         var updateOutputFileStampsPending = true;
121217         return {
121218             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
121219             project: project,
121220             projectPath: projectPath,
121221             buildOrder: buildOrder,
121222             getCompilerOptions: function () { return config.options; },
121223             getCurrentDirectory: function () { return state.currentDirectory; },
121224             updateOutputFileStatmps: function () {
121225                 updateOutputTimestamps(state, config, projectPath);
121226                 updateOutputFileStampsPending = false;
121227             },
121228             done: function () {
121229                 if (updateOutputFileStampsPending) {
121230                     updateOutputTimestamps(state, config, projectPath);
121231                 }
121232                 return doneInvalidatedProject(state, projectPath);
121233             }
121234         };
121235     }
121236     var BuildStep;
121237     (function (BuildStep) {
121238         BuildStep[BuildStep["CreateProgram"] = 0] = "CreateProgram";
121239         BuildStep[BuildStep["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
121240         BuildStep[BuildStep["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
121241         BuildStep[BuildStep["Emit"] = 3] = "Emit";
121242         BuildStep[BuildStep["EmitBundle"] = 4] = "EmitBundle";
121243         BuildStep[BuildStep["EmitBuildInfo"] = 5] = "EmitBuildInfo";
121244         BuildStep[BuildStep["BuildInvalidatedProjectOfBundle"] = 6] = "BuildInvalidatedProjectOfBundle";
121245         BuildStep[BuildStep["QueueReferencingProjects"] = 7] = "QueueReferencingProjects";
121246         BuildStep[BuildStep["Done"] = 8] = "Done";
121247     })(BuildStep || (BuildStep = {}));
121248     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
121249         var step = kind === InvalidatedProjectKind.Build ? BuildStep.CreateProgram : BuildStep.EmitBundle;
121250         var program;
121251         var buildResult;
121252         var invalidatedProjectOfBundle;
121253         return kind === InvalidatedProjectKind.Build ?
121254             {
121255                 kind: kind,
121256                 project: project,
121257                 projectPath: projectPath,
121258                 buildOrder: buildOrder,
121259                 getCompilerOptions: function () { return config.options; },
121260                 getCurrentDirectory: function () { return state.currentDirectory; },
121261                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
121262                 getProgram: function () {
121263                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
121264                 },
121265                 getSourceFile: function (fileName) {
121266                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
121267                 },
121268                 getSourceFiles: function () {
121269                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
121270                 },
121271                 getOptionsDiagnostics: function (cancellationToken) {
121272                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
121273                 },
121274                 getGlobalDiagnostics: function (cancellationToken) {
121275                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
121276                 },
121277                 getConfigFileParsingDiagnostics: function () {
121278                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
121279                 },
121280                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
121281                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
121282                 },
121283                 getAllDependencies: function (sourceFile) {
121284                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
121285                 },
121286                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
121287                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
121288                 },
121289                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
121290                     return withProgramOrUndefined(function (program) {
121291                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
121292                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
121293                     });
121294                 },
121295                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
121296                     if (targetSourceFile || emitOnlyDtsFiles) {
121297                         return withProgramOrUndefined(function (program) { var _a, _b; return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) === null || _b === void 0 ? void 0 : _b.call(_a, project))); });
121298                     }
121299                     executeSteps(BuildStep.SemanticDiagnostics, cancellationToken);
121300                     if (step === BuildStep.EmitBuildInfo) {
121301                         return emitBuildInfo(writeFile, cancellationToken);
121302                     }
121303                     if (step !== BuildStep.Emit)
121304                         return undefined;
121305                     return emit(writeFile, cancellationToken, customTransformers);
121306                 },
121307                 done: done
121308             } :
121309             {
121310                 kind: kind,
121311                 project: project,
121312                 projectPath: projectPath,
121313                 buildOrder: buildOrder,
121314                 getCompilerOptions: function () { return config.options; },
121315                 getCurrentDirectory: function () { return state.currentDirectory; },
121316                 emit: function (writeFile, customTransformers) {
121317                     if (step !== BuildStep.EmitBundle)
121318                         return invalidatedProjectOfBundle;
121319                     return emitBundle(writeFile, customTransformers);
121320                 },
121321                 done: done,
121322             };
121323         function done(cancellationToken, writeFile, customTransformers) {
121324             executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers);
121325             return doneInvalidatedProject(state, projectPath);
121326         }
121327         function withProgramOrUndefined(action) {
121328             executeSteps(BuildStep.CreateProgram);
121329             return program && action(program);
121330         }
121331         function withProgramOrEmptyArray(action) {
121332             return withProgramOrUndefined(action) || ts.emptyArray;
121333         }
121334         function createProgram() {
121335             var _a, _b;
121336             ts.Debug.assert(program === undefined);
121337             if (state.options.dry) {
121338                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
121339                 buildResult = BuildResultFlags.Success;
121340                 step = BuildStep.QueueReferencingProjects;
121341                 return;
121342             }
121343             if (state.options.verbose)
121344                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
121345             if (config.fileNames.length === 0) {
121346                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
121347                 // Nothing to build - must be a solution file, basically
121348                 buildResult = BuildResultFlags.None;
121349                 step = BuildStep.QueueReferencingProjects;
121350                 return;
121351             }
121352             var host = state.host, compilerHost = state.compilerHost;
121353             state.projectCompilerOptions = config.options;
121354             // Update module resolution cache if needed
121355             (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options);
121356             (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options);
121357             // Create program
121358             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
121359             if (state.watch) {
121360                 state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) {
121361                     var path = _a[0], data = _a[1];
121362                     return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data];
121363                 }));
121364                 state.builderPrograms.set(projectPath, program);
121365             }
121366             step++;
121367         }
121368         function handleDiagnostics(diagnostics, errorFlags, errorType) {
121369             var _a;
121370             if (diagnostics.length) {
121371                 (_a = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType), buildResult = _a.buildResult, step = _a.step);
121372             }
121373             else {
121374                 step++;
121375             }
121376         }
121377         function getSyntaxDiagnostics(cancellationToken) {
121378             ts.Debug.assertIsDefined(program);
121379             handleDiagnostics(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getConfigFileParsingDiagnostics(), true), program.getOptionsDiagnostics(cancellationToken), true), program.getGlobalDiagnostics(cancellationToken), true), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken), true), BuildResultFlags.SyntaxErrors, "Syntactic");
121380         }
121381         function getSemanticDiagnostics(cancellationToken) {
121382             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
121383         }
121384         function emit(writeFileCallback, cancellationToken, customTransformers) {
121385             var _a;
121386             var _b, _c;
121387             ts.Debug.assertIsDefined(program);
121388             ts.Debug.assert(step === BuildStep.Emit);
121389             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
121390             program.backupState();
121391             var declDiagnostics;
121392             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
121393             var outputFiles = [];
121394             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
121395             /*write*/ undefined, 
121396             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
121397             /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult;
121398             // Don't emit .d.ts if there are decl file errors
121399             if (declDiagnostics) {
121400                 program.restoreState();
121401                 (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step);
121402                 return {
121403                     emitSkipped: true,
121404                     diagnostics: emitResult.diagnostics
121405                 };
121406             }
121407             // Actual Emit
121408             var host = state.host, compilerHost = state.compilerHost;
121409             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
121410             var newestDeclarationFileContentChangedTime = minimumDate;
121411             var anyDtsChanged = false;
121412             var emitterDiagnostics = ts.createDiagnosticCollection();
121413             var emittedOutputs = new ts.Map();
121414             outputFiles.forEach(function (_a) {
121415                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
121416                 var priorChangeTime;
121417                 if (!anyDtsChanged && isDeclarationFile(name)) {
121418                     // Check for unchanged .d.ts files
121419                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
121420                         priorChangeTime = host.getModifiedTime(name);
121421                     }
121422                     else {
121423                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
121424                         anyDtsChanged = true;
121425                     }
121426                 }
121427                 emittedOutputs.set(toPath(state, name), name);
121428                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
121429                 if (priorChangeTime !== undefined) {
121430                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
121431                 }
121432             });
121433             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
121434             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
121435             return emitResult;
121436         }
121437         function emitBuildInfo(writeFileCallback, cancellationToken) {
121438             ts.Debug.assertIsDefined(program);
121439             ts.Debug.assert(step === BuildStep.EmitBuildInfo);
121440             var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
121441             if (emitResult.diagnostics.length) {
121442                 reportErrors(state, emitResult.diagnostics);
121443                 state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true));
121444                 buildResult = BuildResultFlags.EmitErrors & buildResult;
121445             }
121446             if (emitResult.emittedFiles && state.write) {
121447                 emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
121448             }
121449             afterProgramDone(state, program, config);
121450             step = BuildStep.QueueReferencingProjects;
121451             return emitResult;
121452         }
121453         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
121454             var _a;
121455             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
121456             if (emitDiagnostics.length) {
121457                 (_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
121458                 return emitDiagnostics;
121459             }
121460             if (state.write) {
121461                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
121462             }
121463             // Update time stamps for rest of the outputs
121464             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
121465             state.diagnostics.delete(projectPath);
121466             state.projectStatus.set(projectPath, {
121467                 type: ts.UpToDateStatusType.UpToDate,
121468                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
121469                     maximumDate :
121470                     newestDeclarationFileContentChangedTime,
121471                 oldestOutputFileName: oldestOutputFileName
121472             });
121473             afterProgramDone(state, program, config);
121474             step = BuildStep.QueueReferencingProjects;
121475             buildResult = resultFlags;
121476             return emitDiagnostics;
121477         }
121478         function emitBundle(writeFileCallback, customTransformers) {
121479             var _a, _b;
121480             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
121481             if (state.options.dry) {
121482                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
121483                 buildResult = BuildResultFlags.Success;
121484                 step = BuildStep.QueueReferencingProjects;
121485                 return undefined;
121486             }
121487             if (state.options.verbose)
121488                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
121489             // Update js, and source map
121490             var compilerHost = state.compilerHost;
121491             state.projectCompilerOptions = config.options;
121492             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
121493                 var refName = resolveProjectName(state, ref.path);
121494                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
121495             }, customTransformers || ((_b = (_a = state.host).getCustomTransformers) === null || _b === void 0 ? void 0 : _b.call(_a, project)));
121496             if (ts.isString(outputFiles)) {
121497                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
121498                 step = BuildStep.BuildInvalidatedProjectOfBundle;
121499                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
121500             }
121501             // Actual Emit
121502             ts.Debug.assert(!!outputFiles.length);
121503             var emitterDiagnostics = ts.createDiagnosticCollection();
121504             var emittedOutputs = new ts.Map();
121505             outputFiles.forEach(function (_a) {
121506                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
121507                 emittedOutputs.set(toPath(state, name), name);
121508                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
121509             });
121510             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
121511             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
121512             return { emitSkipped: false, diagnostics: emitDiagnostics };
121513         }
121514         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
121515             while (step <= till && step < BuildStep.Done) {
121516                 var currentStep = step;
121517                 switch (step) {
121518                     case BuildStep.CreateProgram:
121519                         createProgram();
121520                         break;
121521                     case BuildStep.SyntaxDiagnostics:
121522                         getSyntaxDiagnostics(cancellationToken);
121523                         break;
121524                     case BuildStep.SemanticDiagnostics:
121525                         getSemanticDiagnostics(cancellationToken);
121526                         break;
121527                     case BuildStep.Emit:
121528                         emit(writeFile, cancellationToken, customTransformers);
121529                         break;
121530                     case BuildStep.EmitBuildInfo:
121531                         emitBuildInfo(writeFile, cancellationToken);
121532                         break;
121533                     case BuildStep.EmitBundle:
121534                         emitBundle(writeFile, customTransformers);
121535                         break;
121536                     case BuildStep.BuildInvalidatedProjectOfBundle:
121537                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers);
121538                         step = BuildStep.Done;
121539                         break;
121540                     case BuildStep.QueueReferencingProjects:
121541                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
121542                         step++;
121543                         break;
121544                     // Should never be done
121545                     case BuildStep.Done:
121546                     default:
121547                         ts.assertType(step);
121548                 }
121549                 ts.Debug.assert(step > currentStep);
121550             }
121551         }
121552     }
121553     function needsBuild(_a, status, config) {
121554         var options = _a.options;
121555         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
121556             return true;
121557         return config.fileNames.length === 0 ||
121558             !!ts.getConfigFileParsingDiagnostics(config).length ||
121559             !ts.isIncrementalCompilation(config.options);
121560     }
121561     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
121562         if (!state.projectPendingBuild.size)
121563             return undefined;
121564         if (isCircularBuildOrder(buildOrder))
121565             return undefined;
121566         if (state.currentInvalidatedProject) {
121567             // Only if same buildOrder the currentInvalidated project can be sent again
121568             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
121569                 state.currentInvalidatedProject :
121570                 undefined;
121571         }
121572         var options = state.options, projectPendingBuild = state.projectPendingBuild;
121573         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
121574             var project = buildOrder[projectIndex];
121575             var projectPath = toResolvedConfigFilePath(state, project);
121576             var reloadLevel = state.projectPendingBuild.get(projectPath);
121577             if (reloadLevel === undefined)
121578                 continue;
121579             if (reportQueue) {
121580                 reportQueue = false;
121581                 reportBuildQueue(state, buildOrder);
121582             }
121583             var config = parseConfigFile(state, project, projectPath);
121584             if (!config) {
121585                 reportParseConfigFileDiagnostic(state, projectPath);
121586                 projectPendingBuild.delete(projectPath);
121587                 continue;
121588             }
121589             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
121590                 watchConfigFile(state, project, projectPath, config);
121591                 watchExtendedConfigFiles(state, projectPath, config);
121592                 watchWildCardDirectories(state, project, projectPath, config);
121593                 watchInputFiles(state, project, projectPath, config);
121594                 watchPackageJsonFiles(state, project, projectPath, config);
121595             }
121596             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
121597                 // Update file names
121598                 config.fileNames = ts.getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
121599                 ts.updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
121600                 watchInputFiles(state, project, projectPath, config);
121601                 watchPackageJsonFiles(state, project, projectPath, config);
121602             }
121603             var status = getUpToDateStatus(state, config, projectPath);
121604             verboseReportProjectStatus(state, project, status);
121605             if (!options.force) {
121606                 if (status.type === ts.UpToDateStatusType.UpToDate) {
121607                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
121608                     projectPendingBuild.delete(projectPath);
121609                     // Up to date, skip
121610                     if (options.dry) {
121611                         // In a dry build, inform the user of this fact
121612                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
121613                     }
121614                     continue;
121615                 }
121616                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
121617                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
121618                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
121619                 }
121620             }
121621             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
121622                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
121623                 projectPendingBuild.delete(projectPath);
121624                 if (options.verbose) {
121625                     reportStatus(state, status.upstreamProjectBlocked ?
121626                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
121627                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
121628                 }
121629                 continue;
121630             }
121631             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
121632                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
121633                 projectPendingBuild.delete(projectPath);
121634                 // Do nothing
121635                 continue;
121636             }
121637             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
121638                 InvalidatedProjectKind.Build :
121639                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
121640         }
121641         return undefined;
121642     }
121643     function listEmittedFile(_a, proj, file) {
121644         var write = _a.write;
121645         if (write && proj.options.listEmittedFiles) {
121646             write("TSFILE: ".concat(file));
121647         }
121648     }
121649     function getOldProgram(_a, proj, parsed) {
121650         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
121651         if (options.force)
121652             return undefined;
121653         var value = builderPrograms.get(proj);
121654         if (value)
121655             return value;
121656         return ts.readBuilderProgram(parsed.options, compilerHost);
121657     }
121658     function afterProgramDone(state, program, config) {
121659         if (program) {
121660             if (program && state.write)
121661                 ts.listFiles(program, state.write);
121662             if (state.host.afterProgramEmitAndDiagnostics) {
121663                 state.host.afterProgramEmitAndDiagnostics(program);
121664             }
121665             program.releaseProgram();
121666         }
121667         else if (state.host.afterEmitBundle) {
121668             state.host.afterEmitBundle(config);
121669         }
121670         state.projectCompilerOptions = state.baseCompilerOptions;
121671     }
121672     function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
121673         var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
121674         reportAndStoreErrors(state, resolvedPath, diagnostics);
121675         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") });
121676         if (canEmitBuildInfo)
121677             return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
121678         afterProgramDone(state, program, config);
121679         return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects };
121680     }
121681     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
121682         // Check tsconfig time
121683         var tsconfigTime = ts.getModifiedTime(state.host, configFile);
121684         if (oldestOutputFileTime < tsconfigTime) {
121685             return {
121686                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
121687                 outOfDateOutputFileName: oldestOutputFileName,
121688                 newerInputFileName: configFile
121689             };
121690         }
121691     }
121692     function getUpToDateStatusWorker(state, project, resolvedPath) {
121693         var force = !!state.options.force;
121694         var newestInputFileName = undefined;
121695         var newestInputFileTime = minimumDate;
121696         var host = state.host;
121697         // Get timestamps of input files
121698         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
121699             var inputFile = _a[_i];
121700             if (!host.fileExists(inputFile)) {
121701                 return {
121702                     type: ts.UpToDateStatusType.Unbuildable,
121703                     reason: "".concat(inputFile, " does not exist")
121704                 };
121705             }
121706             if (!force) {
121707                 var inputTime = ts.getModifiedTime(host, inputFile);
121708                 if (inputTime > newestInputFileTime) {
121709                     newestInputFileName = inputFile;
121710                     newestInputFileTime = inputTime;
121711                 }
121712             }
121713         }
121714         // Container if no files are specified in the project
121715         if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) {
121716             return {
121717                 type: ts.UpToDateStatusType.ContainerOnly
121718             };
121719         }
121720         // Collect the expected outputs of this project
121721         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
121722         // Now see if all outputs are newer than the newest input
121723         var oldestOutputFileName = "(none)";
121724         var oldestOutputFileTime = maximumDate;
121725         var newestOutputFileName = "(none)";
121726         var newestOutputFileTime = minimumDate;
121727         var missingOutputFileName;
121728         var newestDeclarationFileContentChangedTime = minimumDate;
121729         var isOutOfDateWithInputs = false;
121730         if (!force) {
121731             for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
121732                 var output = outputs_1[_b];
121733                 // Output is missing; can stop checking
121734                 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
121735                 if (!host.fileExists(output)) {
121736                     missingOutputFileName = output;
121737                     break;
121738                 }
121739                 var outputTime = ts.getModifiedTime(host, output);
121740                 if (outputTime < oldestOutputFileTime) {
121741                     oldestOutputFileTime = outputTime;
121742                     oldestOutputFileName = output;
121743                 }
121744                 // If an output is older than the newest input, we can stop checking
121745                 // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
121746                 if (outputTime < newestInputFileTime) {
121747                     isOutOfDateWithInputs = true;
121748                     break;
121749                 }
121750                 if (outputTime > newestOutputFileTime) {
121751                     newestOutputFileTime = outputTime;
121752                     newestOutputFileName = output;
121753                 }
121754                 // Keep track of when the most recent time a .d.ts file was changed.
121755                 // In addition to file timestamps, we also keep track of when a .d.ts file
121756                 // had its file touched but not had its contents changed - this allows us
121757                 // to skip a downstream typecheck
121758                 if (isDeclarationFile(output)) {
121759                     var outputModifiedTime = ts.getModifiedTime(host, output);
121760                     newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
121761                 }
121762             }
121763         }
121764         var pseudoUpToDate = false;
121765         var usesPrepend = false;
121766         var upstreamChangedProject;
121767         if (project.projectReferences) {
121768             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
121769             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
121770                 var ref = _d[_c];
121771                 usesPrepend = usesPrepend || !!(ref.prepend);
121772                 var resolvedRef = ts.resolveProjectReferencePath(ref);
121773                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
121774                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
121775                 // Its a circular reference ignore the status of this project
121776                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
121777                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
121778                     continue;
121779                 }
121780                 // An upstream project is blocked
121781                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
121782                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
121783                     return {
121784                         type: ts.UpToDateStatusType.UpstreamBlocked,
121785                         upstreamProjectName: ref.path,
121786                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
121787                     };
121788                 }
121789                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
121790                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
121791                     return {
121792                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
121793                         upstreamProjectName: ref.path
121794                     };
121795                 }
121796                 // Check oldest output file name only if there is no missing output file name
121797                 // (a check we will have skipped if this is a forced build)
121798                 if (!force && !missingOutputFileName) {
121799                     // If the upstream project's newest file is older than our oldest output, we
121800                     // can't be out of date because of it
121801                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
121802                         continue;
121803                     }
121804                     // If the upstream project has only change .d.ts files, and we've built
121805                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
121806                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
121807                         pseudoUpToDate = true;
121808                         upstreamChangedProject = ref.path;
121809                         continue;
121810                     }
121811                     // We have an output older than an upstream output - we are out of date
121812                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
121813                     return {
121814                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
121815                         outOfDateOutputFileName: oldestOutputFileName,
121816                         newerProjectName: ref.path
121817                     };
121818                 }
121819             }
121820         }
121821         if (missingOutputFileName !== undefined) {
121822             return {
121823                 type: ts.UpToDateStatusType.OutputMissing,
121824                 missingOutputFileName: missingOutputFileName
121825             };
121826         }
121827         if (isOutOfDateWithInputs) {
121828             return {
121829                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
121830                 outOfDateOutputFileName: oldestOutputFileName,
121831                 newerInputFileName: newestInputFileName
121832             };
121833         }
121834         else {
121835             // Check tsconfig time
121836             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
121837             if (configStatus)
121838                 return configStatus;
121839             // Check extended config time
121840             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
121841             if (extendedConfigStatus)
121842                 return extendedConfigStatus;
121843             // Check package file time
121844             var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) {
121845                 var path = _a[0];
121846                 return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName);
121847             });
121848             if (dependentPackageFileStatus)
121849                 return dependentPackageFileStatus;
121850         }
121851         if (!force && !state.buildInfoChecked.has(resolvedPath)) {
121852             state.buildInfoChecked.set(resolvedPath, true);
121853             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
121854             if (buildInfoPath) {
121855                 var value = state.readFileWithCache(buildInfoPath);
121856                 var buildInfo = value && ts.getBuildInfo(value);
121857                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
121858                     return {
121859                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
121860                         version: buildInfo.version
121861                     };
121862                 }
121863             }
121864         }
121865         if (usesPrepend && pseudoUpToDate) {
121866             return {
121867                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
121868                 outOfDateOutputFileName: oldestOutputFileName,
121869                 newerProjectName: upstreamChangedProject
121870             };
121871         }
121872         // Up to date
121873         return {
121874             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
121875             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
121876             newestInputFileTime: newestInputFileTime,
121877             newestOutputFileTime: newestOutputFileTime,
121878             newestInputFileName: newestInputFileName,
121879             newestOutputFileName: newestOutputFileName,
121880             oldestOutputFileName: oldestOutputFileName
121881         };
121882     }
121883     function getUpToDateStatus(state, project, resolvedPath) {
121884         if (project === undefined) {
121885             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
121886         }
121887         var prior = state.projectStatus.get(resolvedPath);
121888         if (prior !== undefined) {
121889             return prior;
121890         }
121891         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
121892         state.projectStatus.set(resolvedPath, actual);
121893         return actual;
121894     }
121895     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
121896         if (proj.options.noEmit)
121897             return priorNewestUpdateTime;
121898         var host = state.host;
121899         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
121900         if (!skipOutputs || outputs.length !== skipOutputs.size) {
121901             var reportVerbose = !!state.options.verbose;
121902             var now = host.now ? host.now() : new Date();
121903             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
121904                 var file = outputs_2[_i];
121905                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
121906                     continue;
121907                 }
121908                 if (reportVerbose) {
121909                     reportVerbose = false;
121910                     reportStatus(state, verboseMessage, proj.options.configFilePath);
121911                 }
121912                 if (isDeclarationFile(file)) {
121913                     priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file));
121914                 }
121915                 host.setModifiedTime(file, now);
121916             }
121917         }
121918         return priorNewestUpdateTime;
121919     }
121920     function updateOutputTimestamps(state, proj, resolvedPath) {
121921         if (state.options.dry) {
121922             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
121923         }
121924         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
121925         state.projectStatus.set(resolvedPath, {
121926             type: ts.UpToDateStatusType.UpToDate,
121927             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
121928             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
121929         });
121930     }
121931     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
121932         // Queue only if there are no errors
121933         if (buildResult & BuildResultFlags.AnyErrors)
121934             return;
121935         // Only composite projects can be referenced by other projects
121936         if (!config.options.composite)
121937             return;
121938         // Always use build order to queue projects
121939         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
121940             var nextProject = buildOrder[index];
121941             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
121942             if (state.projectPendingBuild.has(nextProjectPath))
121943                 continue;
121944             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
121945             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
121946                 continue;
121947             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
121948                 var ref = _a[_i];
121949                 var resolvedRefPath = resolveProjectName(state, ref.path);
121950                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
121951                     continue;
121952                 // If the project is referenced with prepend, always build downstream projects,
121953                 // If declaration output is changed, build the project
121954                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
121955                 var status = state.projectStatus.get(nextProjectPath);
121956                 if (status) {
121957                     switch (status.type) {
121958                         case ts.UpToDateStatusType.UpToDate:
121959                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
121960                                 if (ref.prepend) {
121961                                     state.projectStatus.set(nextProjectPath, {
121962                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
121963                                         outOfDateOutputFileName: status.oldestOutputFileName,
121964                                         newerProjectName: project
121965                                     });
121966                                 }
121967                                 else {
121968                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
121969                                 }
121970                                 break;
121971                             }
121972                         // falls through
121973                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
121974                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
121975                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
121976                                 state.projectStatus.set(nextProjectPath, {
121977                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
121978                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
121979                                     newerProjectName: project
121980                                 });
121981                             }
121982                             break;
121983                         case ts.UpToDateStatusType.UpstreamBlocked:
121984                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
121985                                 clearProjectStatus(state, nextProjectPath);
121986                             }
121987                             break;
121988                     }
121989                 }
121990                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
121991                 break;
121992             }
121993         }
121994     }
121995     function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) {
121996         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
121997         if (!buildOrder)
121998             return ts.ExitStatus.InvalidProject_OutputsSkipped;
121999         setupInitialBuild(state, cancellationToken);
122000         var reportQueue = true;
122001         var successfulProjects = 0;
122002         while (true) {
122003             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
122004             if (!invalidatedProject)
122005                 break;
122006             reportQueue = false;
122007             invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project));
122008             if (!state.diagnostics.has(invalidatedProject.projectPath))
122009                 successfulProjects++;
122010         }
122011         disableCache(state);
122012         reportErrorSummary(state, buildOrder);
122013         startWatching(state, buildOrder);
122014         return isCircularBuildOrder(buildOrder)
122015             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
122016             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
122017                 ? ts.ExitStatus.Success
122018                 : successfulProjects
122019                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
122020                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
122021     }
122022     function clean(state, project, onlyReferences) {
122023         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
122024         if (!buildOrder)
122025             return ts.ExitStatus.InvalidProject_OutputsSkipped;
122026         if (isCircularBuildOrder(buildOrder)) {
122027             reportErrors(state, buildOrder.circularDiagnostics);
122028             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
122029         }
122030         var options = state.options, host = state.host;
122031         var filesToDelete = options.dry ? [] : undefined;
122032         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
122033             var proj = buildOrder_1[_i];
122034             var resolvedPath = toResolvedConfigFilePath(state, proj);
122035             var parsed = parseConfigFile(state, proj, resolvedPath);
122036             if (parsed === undefined) {
122037                 // File has gone missing; fine to ignore here
122038                 reportParseConfigFileDiagnostic(state, resolvedPath);
122039                 continue;
122040             }
122041             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
122042             if (!outputs.length)
122043                 continue;
122044             var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); }));
122045             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
122046                 var output = outputs_3[_a];
122047                 // If output name is same as input file name, do not delete and ignore the error
122048                 if (inputFileNames.has(toPath(state, output)))
122049                     continue;
122050                 if (host.fileExists(output)) {
122051                     if (filesToDelete) {
122052                         filesToDelete.push(output);
122053                     }
122054                     else {
122055                         host.deleteFile(output);
122056                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
122057                     }
122058                 }
122059             }
122060         }
122061         if (filesToDelete) {
122062             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * ".concat(f); }).join(""));
122063         }
122064         return ts.ExitStatus.Success;
122065     }
122066     function invalidateProject(state, resolved, reloadLevel) {
122067         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
122068         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
122069             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
122070         }
122071         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
122072             state.configFileCache.delete(resolved);
122073             state.buildOrder = undefined;
122074         }
122075         state.needsSummary = true;
122076         clearProjectStatus(state, resolved);
122077         addProjToQueue(state, resolved, reloadLevel);
122078         enableCache(state);
122079     }
122080     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
122081         state.reportFileChangeDetected = true;
122082         invalidateProject(state, resolvedPath, reloadLevel);
122083         scheduleBuildInvalidatedProject(state);
122084     }
122085     function scheduleBuildInvalidatedProject(state) {
122086         var hostWithWatch = state.hostWithWatch;
122087         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
122088             return;
122089         }
122090         if (state.timerToBuildInvalidatedProject) {
122091             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
122092         }
122093         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
122094     }
122095     function buildNextInvalidatedProject(state) {
122096         state.timerToBuildInvalidatedProject = undefined;
122097         if (state.reportFileChangeDetected) {
122098             state.reportFileChangeDetected = false;
122099             state.projectErrorsReported.clear();
122100             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
122101         }
122102         var buildOrder = getBuildOrder(state);
122103         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
122104         if (invalidatedProject) {
122105             invalidatedProject.done();
122106             if (state.projectPendingBuild.size) {
122107                 // Schedule next project for build
122108                 if (state.watch && !state.timerToBuildInvalidatedProject) {
122109                     scheduleBuildInvalidatedProject(state);
122110                 }
122111                 return;
122112             }
122113         }
122114         disableCache(state);
122115         reportErrorSummary(state, buildOrder);
122116     }
122117     function watchConfigFile(state, resolved, resolvedPath, parsed) {
122118         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
122119             return;
122120         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () {
122121             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
122122         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
122123     }
122124     function watchExtendedConfigFiles(state, resolvedPath, parsed) {
122125         ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () {
122126             var _a;
122127             return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) {
122128                 return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full);
122129             });
122130         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ExtendedConfigFile); }, function (fileName) { return toPath(state, fileName); });
122131     }
122132     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
122133         if (!state.watch)
122134             return;
122135         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) {
122136             var _a;
122137             if (ts.isIgnoredFileFromWildCardWatching({
122138                 watchedDirPath: toPath(state, dir),
122139                 fileOrDirectory: fileOrDirectory,
122140                 fileOrDirectoryPath: toPath(state, fileOrDirectory),
122141                 configFileName: resolved,
122142                 currentDirectory: state.currentDirectory,
122143                 options: parsed.options,
122144                 program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames),
122145                 useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
122146                 writeLog: function (s) { return state.writeLog(s); },
122147                 toPath: function (fileName) { return toPath(state, fileName); }
122148             }))
122149                 return;
122150             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
122151         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
122152     }
122153     function watchInputFiles(state, resolved, resolvedPath, parsed) {
122154         if (!state.watch)
122155             return;
122156         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
122157             createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); },
122158             onDeleteValue: ts.closeFileWatcher,
122159         });
122160     }
122161     function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) {
122162         if (!state.watch || !state.lastCachedPackageJsonLookups)
122163             return;
122164         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), {
122165             createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); },
122166             onDeleteValue: ts.closeFileWatcher,
122167         });
122168     }
122169     function startWatching(state, buildOrder) {
122170         if (!state.watchAllProjectsPending)
122171             return;
122172         state.watchAllProjectsPending = false;
122173         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
122174             var resolved = _a[_i];
122175             var resolvedPath = toResolvedConfigFilePath(state, resolved);
122176             var cfg = parseConfigFile(state, resolved, resolvedPath);
122177             // Watch this file
122178             watchConfigFile(state, resolved, resolvedPath, cfg);
122179             watchExtendedConfigFiles(state, resolvedPath, cfg);
122180             if (cfg) {
122181                 // Update watchers for wildcard directories
122182                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
122183                 // Watch input files
122184                 watchInputFiles(state, resolved, resolvedPath, cfg);
122185                 // Watch package json files
122186                 watchPackageJsonFiles(state, resolved, resolvedPath, cfg);
122187             }
122188         }
122189     }
122190     function stopWatching(state) {
122191         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
122192         ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf);
122193         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
122194         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
122195         ts.clearMap(state.allWatchedPackageJsonFiles, function (watchedPacageJsonFiles) { return ts.clearMap(watchedPacageJsonFiles, ts.closeFileWatcher); });
122196     }
122197     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
122198         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
122199         return {
122200             build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); },
122201             clean: function (project) { return clean(state, project); },
122202             buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); },
122203             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
122204             getNextInvalidatedProject: function (cancellationToken) {
122205                 setupInitialBuild(state, cancellationToken);
122206                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
122207             },
122208             getBuildOrder: function () { return getBuildOrder(state); },
122209             getUpToDateStatusOfProject: function (project) {
122210                 var configFileName = resolveProjectName(state, project);
122211                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
122212                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
122213             },
122214             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
122215             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
122216             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
122217             close: function () { return stopWatching(state); },
122218         };
122219     }
122220     function relName(state, path) {
122221         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
122222     }
122223     function reportStatus(state, message) {
122224         var args = [];
122225         for (var _i = 2; _i < arguments.length; _i++) {
122226             args[_i - 2] = arguments[_i];
122227         }
122228         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args, false)));
122229     }
122230     function reportWatchStatus(state, message) {
122231         var _a, _b;
122232         var args = [];
122233         for (var _i = 2; _i < arguments.length; _i++) {
122234             args[_i - 2] = arguments[_i];
122235         }
122236         (_b = (_a = state.hostWithWatch).onWatchStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args, false)), state.host.getNewLine(), state.baseCompilerOptions);
122237     }
122238     function reportErrors(_a, errors) {
122239         var host = _a.host;
122240         errors.forEach(function (err) { return host.reportDiagnostic(err); });
122241     }
122242     function reportAndStoreErrors(state, proj, errors) {
122243         reportErrors(state, errors);
122244         state.projectErrorsReported.set(proj, true);
122245         if (errors.length) {
122246             state.diagnostics.set(proj, errors);
122247         }
122248     }
122249     function reportParseConfigFileDiagnostic(state, proj) {
122250         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
122251     }
122252     function reportErrorSummary(state, buildOrder) {
122253         if (!state.needsSummary)
122254             return;
122255         state.needsSummary = false;
122256         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
122257         var diagnostics = state.diagnostics;
122258         var totalErrors = 0;
122259         if (isCircularBuildOrder(buildOrder)) {
122260             reportBuildQueue(state, buildOrder.buildOrder);
122261             reportErrors(state, buildOrder.circularDiagnostics);
122262             if (canReportSummary)
122263                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
122264         }
122265         else {
122266             // Report errors from the other projects
122267             buildOrder.forEach(function (project) {
122268                 var projectPath = toResolvedConfigFilePath(state, project);
122269                 if (!state.projectErrorsReported.has(projectPath)) {
122270                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
122271                 }
122272             });
122273             if (canReportSummary)
122274                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
122275         }
122276         if (state.watch) {
122277             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
122278         }
122279         else if (state.host.reportErrorSummary) {
122280             state.host.reportErrorSummary(totalErrors);
122281         }
122282     }
122283     /**
122284      * Report the build ordering inferred from the current project graph if we're in verbose mode
122285      */
122286     function reportBuildQueue(state, buildQueue) {
122287         if (state.options.verbose) {
122288             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
122289         }
122290     }
122291     function reportUpToDateStatus(state, configFileName, status) {
122292         if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) {
122293             return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName));
122294         }
122295         switch (status.type) {
122296             case ts.UpToDateStatusType.OutOfDateWithSelf:
122297                 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));
122298             case ts.UpToDateStatusType.OutOfDateWithUpstream:
122299                 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));
122300             case ts.UpToDateStatusType.OutputMissing:
122301                 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));
122302             case ts.UpToDateStatusType.UpToDate:
122303                 if (status.newestInputFileTime !== undefined) {
122304                     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 || ""));
122305                 }
122306                 // Don't report anything for "up to date because it was already built" -- too verbose
122307                 break;
122308             case ts.UpToDateStatusType.OutOfDateWithPrepend:
122309                 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));
122310             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
122311                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
122312             case ts.UpToDateStatusType.UpstreamOutOfDate:
122313                 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));
122314             case ts.UpToDateStatusType.UpstreamBlocked:
122315                 return reportStatus(state, status.upstreamProjectBlocked ?
122316                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
122317                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
122318             case ts.UpToDateStatusType.Unbuildable:
122319                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
122320             case ts.UpToDateStatusType.TsVersionOutputOfDate:
122321                 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);
122322             case ts.UpToDateStatusType.ContainerOnly:
122323             // Don't report status on "solution" projects
122324             // falls through
122325             case ts.UpToDateStatusType.ComputingUpstream:
122326                 // Should never leak from getUptoDateStatusWorker
122327                 break;
122328             default:
122329                 ts.assertType(status);
122330         }
122331     }
122332     /**
122333      * Report the up-to-date status of a project if we're in verbose mode
122334      */
122335     function verboseReportProjectStatus(state, configFileName, status) {
122336         if (state.options.verbose) {
122337             reportUpToDateStatus(state, configFileName, status);
122338         }
122339     }
122340 })(ts || (ts = {}));
122341 var ts;
122342 (function (ts) {
122343     var server;
122344     (function (server) {
122345         /* @internal */
122346         server.ActionSet = "action::set";
122347         /* @internal */
122348         server.ActionInvalidate = "action::invalidate";
122349         /* @internal */
122350         server.ActionPackageInstalled = "action::packageInstalled";
122351         /* @internal */
122352         server.EventTypesRegistry = "event::typesRegistry";
122353         /* @internal */
122354         server.EventBeginInstallTypes = "event::beginInstallTypes";
122355         /* @internal */
122356         server.EventEndInstallTypes = "event::endInstallTypes";
122357         /* @internal */
122358         server.EventInitializationFailed = "event::initializationFailed";
122359         /* @internal */
122360         var Arguments;
122361         (function (Arguments) {
122362             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
122363             Arguments.LogFile = "--logFile";
122364             Arguments.EnableTelemetry = "--enableTelemetry";
122365             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
122366             Arguments.TypesMapLocation = "--typesMapLocation";
122367             /**
122368              * This argument specifies the location of the NPM executable.
122369              * typingsInstaller will run the command with `${npmLocation} install ...`.
122370              */
122371             Arguments.NpmLocation = "--npmLocation";
122372             /**
122373              * Flag indicating that the typings installer should try to validate the default npm location.
122374              * If the default npm is not found when this flag is enabled, fallback to `npm install`
122375              */
122376             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
122377         })(Arguments = server.Arguments || (server.Arguments = {}));
122378         /* @internal */
122379         function hasArgument(argumentName) {
122380             return ts.sys.args.indexOf(argumentName) >= 0;
122381         }
122382         server.hasArgument = hasArgument;
122383         /* @internal */
122384         function findArgument(argumentName) {
122385             var index = ts.sys.args.indexOf(argumentName);
122386             return index >= 0 && index < ts.sys.args.length - 1
122387                 ? ts.sys.args[index + 1]
122388                 : undefined;
122389         }
122390         server.findArgument = findArgument;
122391         /* @internal */
122392         function nowString() {
122393             // E.g. "12:34:56.789"
122394             var d = new Date();
122395             return "".concat(ts.padLeft(d.getHours().toString(), 2, "0"), ":").concat(ts.padLeft(d.getMinutes().toString(), 2, "0"), ":").concat(ts.padLeft(d.getSeconds().toString(), 2, "0"), ".").concat(ts.padLeft(d.getMilliseconds().toString(), 3, "0"));
122396         }
122397         server.nowString = nowString;
122398     })(server = ts.server || (ts.server = {}));
122399 })(ts || (ts = {}));
122400 /* @internal */
122401 var ts;
122402 (function (ts) {
122403     var JsTyping;
122404     (function (JsTyping) {
122405         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
122406             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts".concat(ts.versionMajorMinor)) || ts.getProperty(availableTypingVersions, "latest"));
122407             return availableVersion.compareTo(cachedTyping.version) <= 0;
122408         }
122409         JsTyping.isTypingUpToDate = isTypingUpToDate;
122410         var unprefixedNodeCoreModuleList = [
122411             "assert",
122412             "assert/strict",
122413             "async_hooks",
122414             "buffer",
122415             "child_process",
122416             "cluster",
122417             "console",
122418             "constants",
122419             "crypto",
122420             "dgram",
122421             "diagnostics_channel",
122422             "dns",
122423             "dns/promises",
122424             "domain",
122425             "events",
122426             "fs",
122427             "fs/promises",
122428             "http",
122429             "https",
122430             "http2",
122431             "inspector",
122432             "module",
122433             "net",
122434             "os",
122435             "path",
122436             "perf_hooks",
122437             "process",
122438             "punycode",
122439             "querystring",
122440             "readline",
122441             "repl",
122442             "stream",
122443             "stream/promises",
122444             "string_decoder",
122445             "timers",
122446             "timers/promises",
122447             "tls",
122448             "trace_events",
122449             "tty",
122450             "url",
122451             "util",
122452             "util/types",
122453             "v8",
122454             "vm",
122455             "wasi",
122456             "worker_threads",
122457             "zlib"
122458         ];
122459         JsTyping.prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map(function (name) { return "node:".concat(name); });
122460         JsTyping.nodeCoreModuleList = __spreadArray(__spreadArray([], unprefixedNodeCoreModuleList, true), JsTyping.prefixedNodeCoreModuleList, true);
122461         JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList);
122462         function nonRelativeModuleNameForTypingCache(moduleName) {
122463             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
122464         }
122465         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
122466         function loadSafeList(host, safeListPath) {
122467             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
122468             return new ts.Map(ts.getEntries(result.config));
122469         }
122470         JsTyping.loadSafeList = loadSafeList;
122471         function loadTypesMap(host, typesMapPath) {
122472             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
122473             if (result.config) {
122474                 return new ts.Map(ts.getEntries(result.config.simpleMap));
122475             }
122476             return undefined;
122477         }
122478         JsTyping.loadTypesMap = loadTypesMap;
122479         /**
122480          * @param host is the object providing I/O related operations.
122481          * @param fileNames are the file names that belong to the same project
122482          * @param projectRootPath is the path to the project root directory
122483          * @param safeListPath is the path used to retrieve the safe list
122484          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
122485          * @param typeAcquisition is used to customize the typing acquisition process
122486          * @param compilerOptions are used as a source for typing inference
122487          */
122488         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
122489             if (!typeAcquisition || !typeAcquisition.enable) {
122490                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
122491             }
122492             // A typing name to typing file path mapping
122493             var inferredTypings = new ts.Map();
122494             // Only infer typings for .js and .jsx files
122495             fileNames = ts.mapDefined(fileNames, function (fileName) {
122496                 var path = ts.normalizePath(fileName);
122497                 if (ts.hasJSFileExtension(path)) {
122498                     return path;
122499                 }
122500             });
122501             var filesToWatch = [];
122502             if (typeAcquisition.include)
122503                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
122504             var exclude = typeAcquisition.exclude || [];
122505             // Directories to search for package.json, bower.json and other typing information
122506             var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath));
122507             possibleSearchDirs.add(projectRootPath);
122508             possibleSearchDirs.forEach(function (searchDir) {
122509                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
122510                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
122511                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
122512                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
122513                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
122514                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
122515                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
122516                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
122517             });
122518             if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
122519                 getTypingNamesFromSourceFileNames(fileNames);
122520             }
122521             // add typings for unresolved imports
122522             if (unresolvedImports) {
122523                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
122524                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
122525             }
122526             // Add the cached typing locations for inferred typings that are already installed
122527             packageNameToTypingLocation.forEach(function (typing, name) {
122528                 var registryEntry = typesRegistry.get(name);
122529                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
122530                     inferredTypings.set(name, typing.typingLocation);
122531                 }
122532             });
122533             // Remove typings that the user has added to the exclude list
122534             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
122535                 var excludeTypingName = exclude_1[_i];
122536                 var didDelete = inferredTypings.delete(excludeTypingName);
122537                 if (didDelete && log)
122538                     log("Typing for ".concat(excludeTypingName, " is in exclude list, will be ignored."));
122539             }
122540             var newTypingNames = [];
122541             var cachedTypingPaths = [];
122542             inferredTypings.forEach(function (inferred, typing) {
122543                 if (inferred !== undefined) {
122544                     cachedTypingPaths.push(inferred);
122545                 }
122546                 else {
122547                     newTypingNames.push(typing);
122548                 }
122549             });
122550             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
122551             if (log)
122552                 log("Result: ".concat(JSON.stringify(result)));
122553             return result;
122554             function addInferredTyping(typingName) {
122555                 if (!inferredTypings.has(typingName)) {
122556                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
122557                 }
122558             }
122559             function addInferredTypings(typingNames, message) {
122560                 if (log)
122561                     log("".concat(message, ": ").concat(JSON.stringify(typingNames)));
122562                 ts.forEach(typingNames, addInferredTyping);
122563             }
122564             /**
122565              * Get the typing info from common package manager json files like package.json or bower.json
122566              */
122567             function getTypingNamesFromJson(jsonPath, filesToWatch) {
122568                 if (!host.fileExists(jsonPath)) {
122569                     return;
122570                 }
122571                 filesToWatch.push(jsonPath);
122572                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
122573                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
122574                 addInferredTypings(jsonTypingNames, "Typing names in '".concat(jsonPath, "' dependencies"));
122575             }
122576             /**
122577              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
122578              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
122579              * to the 'angular-route' typing name.
122580              * @param fileNames are the names for source files in the project
122581              */
122582             function getTypingNamesFromSourceFileNames(fileNames) {
122583                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
122584                     if (!ts.hasJSFileExtension(j))
122585                         return undefined;
122586                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
122587                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
122588                     return safeList.get(cleanedTypingName);
122589                 });
122590                 if (fromFileNames.length) {
122591                     addInferredTypings(fromFileNames, "Inferred typings from file names");
122592                 }
122593                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
122594                 if (hasJsxFile) {
122595                     if (log)
122596                         log("Inferred 'react' typings due to presence of '.jsx' extension");
122597                     addInferredTyping("react");
122598                 }
122599             }
122600             /**
122601              * Infer typing names from packages folder (ex: node_module, bower_components)
122602              * @param packagesFolderPath is the path to the packages folder
122603              */
122604             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
122605                 filesToWatch.push(packagesFolderPath);
122606                 // Todo: add support for ModuleResolutionHost too
122607                 if (!host.directoryExists(packagesFolderPath)) {
122608                     return;
122609                 }
122610                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
122611                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
122612                 if (log)
122613                     log("Searching for typing names in ".concat(packagesFolderPath, "; all files: ").concat(JSON.stringify(fileNames)));
122614                 var packageNames = [];
122615                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
122616                     var fileName = fileNames_1[_i];
122617                     var normalizedFileName = ts.normalizePath(fileName);
122618                     var baseFileName = ts.getBaseFileName(normalizedFileName);
122619                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
122620                         continue;
122621                     }
122622                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
122623                     var packageJson = result_1.config;
122624                     // npm 3's package.json contains a "_requiredBy" field
122625                     // we should include all the top level module names for npm 2, and only module names whose
122626                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
122627                     if (baseFileName === "package.json" && packageJson._requiredBy &&
122628                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
122629                         continue;
122630                     }
122631                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
122632                     // to download d.ts files from DefinitelyTyped
122633                     if (!packageJson.name) {
122634                         continue;
122635                     }
122636                     var ownTypes = packageJson.types || packageJson.typings;
122637                     if (ownTypes) {
122638                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
122639                         if (log)
122640                             log("    Package '".concat(packageJson.name, "' provides its own types."));
122641                         inferredTypings.set(packageJson.name, absolutePath);
122642                     }
122643                     else {
122644                         packageNames.push(packageJson.name);
122645                     }
122646                 }
122647                 addInferredTypings(packageNames, "    Found package names");
122648             }
122649         }
122650         JsTyping.discoverTypings = discoverTypings;
122651         var NameValidationResult;
122652         (function (NameValidationResult) {
122653             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
122654             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
122655             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
122656             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
122657             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
122658             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
122659         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
122660         var maxPackageNameLength = 214;
122661         /**
122662          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
122663          */
122664         function validatePackageName(packageName) {
122665             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
122666         }
122667         JsTyping.validatePackageName = validatePackageName;
122668         function validatePackageNameWorker(packageName, supportScopedPackage) {
122669             if (!packageName) {
122670                 return 1 /* EmptyName */;
122671             }
122672             if (packageName.length > maxPackageNameLength) {
122673                 return 2 /* NameTooLong */;
122674             }
122675             if (packageName.charCodeAt(0) === 46 /* dot */) {
122676                 return 3 /* NameStartsWithDot */;
122677             }
122678             if (packageName.charCodeAt(0) === 95 /* _ */) {
122679                 return 4 /* NameStartsWithUnderscore */;
122680             }
122681             // check if name is scope package like: starts with @ and has one '/' in the middle
122682             // scoped packages are not currently supported
122683             if (supportScopedPackage) {
122684                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
122685                 if (matches) {
122686                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
122687                     if (scopeResult !== 0 /* Ok */) {
122688                         return { name: matches[1], isScopeName: true, result: scopeResult };
122689                     }
122690                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
122691                     if (packageResult !== 0 /* Ok */) {
122692                         return { name: matches[2], isScopeName: false, result: packageResult };
122693                     }
122694                     return 0 /* Ok */;
122695                 }
122696             }
122697             if (encodeURIComponent(packageName) !== packageName) {
122698                 return 5 /* NameContainsNonURISafeCharacters */;
122699             }
122700             return 0 /* Ok */;
122701         }
122702         function renderPackageNameValidationFailure(result, typing) {
122703             return typeof result === "object" ?
122704                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
122705                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
122706         }
122707         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
122708         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
122709             var kind = isScopeName ? "Scope" : "Package";
122710             switch (result) {
122711                 case 1 /* EmptyName */:
122712                     return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot be empty");
122713                 case 2 /* NameTooLong */:
122714                     return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' should be less than ").concat(maxPackageNameLength, " characters");
122715                 case 3 /* NameStartsWithDot */:
122716                     return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot start with '.'");
122717                 case 4 /* NameStartsWithUnderscore */:
122718                     return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot start with '_'");
122719                 case 5 /* NameContainsNonURISafeCharacters */:
122720                     return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' contains non URI safe characters");
122721                 case 0 /* Ok */:
122722                     return ts.Debug.fail(); // Shouldn't have called this.
122723                 default:
122724                     throw ts.Debug.assertNever(result);
122725             }
122726         }
122727     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
122728 })(ts || (ts = {}));
122729 var ts;
122730 (function (ts) {
122731     var server;
122732     (function (server) {
122733         var typingsInstaller;
122734         (function (typingsInstaller) {
122735             var nullLog = {
122736                 isEnabled: function () { return false; },
122737                 writeLine: ts.noop
122738             };
122739             function typingToFileName(cachePath, packageName, installTypingHost, log) {
122740                 try {
122741                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
122742                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
122743                 }
122744                 catch (e) {
122745                     if (log.isEnabled()) {
122746                         log.writeLine("Failed to resolve ".concat(packageName, " in folder '").concat(cachePath, "': ").concat(e.message));
122747                     }
122748                     return undefined;
122749                 }
122750             }
122751             /*@internal*/
122752             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
122753                 var hasError = false;
122754                 for (var remaining = packageNames.length; remaining > 0;) {
122755                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
122756                     remaining = result.remaining;
122757                     hasError = install(result.command) || hasError;
122758                 }
122759                 return hasError;
122760             }
122761             typingsInstaller.installNpmPackages = installNpmPackages;
122762             /*@internal*/
122763             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
122764                 var sliceStart = packageNames.length - remaining;
122765                 var command, toSlice = remaining;
122766                 while (true) {
122767                     command = "".concat(npmPath, " install --ignore-scripts ").concat((toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" "), " --save-dev --user-agent=\"typesInstaller/").concat(tsVersion, "\"");
122768                     if (command.length < 8000) {
122769                         break;
122770                     }
122771                     toSlice = toSlice - Math.floor(toSlice / 2);
122772                 }
122773                 return { command: command, remaining: remaining - toSlice };
122774             }
122775             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
122776             function endsWith(str, suffix, caseSensitive) {
122777                 var expectedPos = str.length - suffix.length;
122778                 return expectedPos >= 0 &&
122779                     (str.indexOf(suffix, expectedPos) === expectedPos ||
122780                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
122781             }
122782             function isPackageOrBowerJson(fileName, caseSensitive) {
122783                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
122784             }
122785             function sameFiles(a, b, caseSensitive) {
122786                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
122787             }
122788             var ProjectWatcherType;
122789             (function (ProjectWatcherType) {
122790                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
122791                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
122792             })(ProjectWatcherType || (ProjectWatcherType = {}));
122793             function getDetailWatchInfo(projectName, watchers) {
122794                 return "Project: ".concat(projectName, " watcher already invoked: ").concat(watchers.isInvoked);
122795             }
122796             var TypingsInstaller = /** @class */ (function () {
122797                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
122798                     var _this = this;
122799                     if (log === void 0) { log = nullLog; }
122800                     this.installTypingHost = installTypingHost;
122801                     this.globalCachePath = globalCachePath;
122802                     this.safeListPath = safeListPath;
122803                     this.typesMapLocation = typesMapLocation;
122804                     this.throttleLimit = throttleLimit;
122805                     this.log = log;
122806                     this.packageNameToTypingLocation = new ts.Map();
122807                     this.missingTypingsSet = new ts.Set();
122808                     this.knownCachesSet = new ts.Set();
122809                     this.projectWatchers = new ts.Map();
122810                     this.pendingRunRequests = [];
122811                     this.installRunCount = 1;
122812                     this.inFlightRequestCount = 0;
122813                     this.latestDistTag = "latest";
122814                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
122815                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
122816                     var isLoggingEnabled = this.log.isEnabled();
122817                     if (isLoggingEnabled) {
122818                         this.log.writeLine("Global cache location '".concat(globalCachePath, "', safe file path '").concat(safeListPath, "', types map path ").concat(typesMapLocation));
122819                     }
122820                     this.watchFactory = ts.getWatchFactory(this.installTypingHost, isLoggingEnabled ? ts.WatchLogLevel.Verbose : ts.WatchLogLevel.None, function (s) { return _this.log.writeLine(s); }, getDetailWatchInfo);
122821                     this.processCacheLocation(this.globalCachePath);
122822                 }
122823                 TypingsInstaller.prototype.closeProject = function (req) {
122824                     this.closeWatchers(req.projectName);
122825                 };
122826                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
122827                     if (this.log.isEnabled()) {
122828                         this.log.writeLine("Closing file watchers for project '".concat(projectName, "'"));
122829                     }
122830                     var watchers = this.projectWatchers.get(projectName);
122831                     if (!watchers) {
122832                         if (this.log.isEnabled()) {
122833                             this.log.writeLine("No watchers are registered for project '".concat(projectName, "'"));
122834                         }
122835                         return;
122836                     }
122837                     ts.clearMap(watchers, ts.closeFileWatcher);
122838                     this.projectWatchers.delete(projectName);
122839                     if (this.log.isEnabled()) {
122840                         this.log.writeLine("Closing file watchers for project '".concat(projectName, "' - done."));
122841                     }
122842                 };
122843                 TypingsInstaller.prototype.install = function (req) {
122844                     var _this = this;
122845                     if (this.log.isEnabled()) {
122846                         this.log.writeLine("Got install request ".concat(JSON.stringify(req)));
122847                     }
122848                     // load existing typing information from the cache
122849                     if (req.cachePath) {
122850                         if (this.log.isEnabled()) {
122851                             this.log.writeLine("Request specifies cache path '".concat(req.cachePath, "', loading cached information..."));
122852                         }
122853                         this.processCacheLocation(req.cachePath);
122854                     }
122855                     if (this.safeList === undefined) {
122856                         this.initializeSafeList();
122857                     }
122858                     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);
122859                     if (this.log.isEnabled()) {
122860                         this.log.writeLine("Finished typings discovery: ".concat(JSON.stringify(discoverTypingsResult)));
122861                     }
122862                     // start watching files
122863                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
122864                     // install typings
122865                     if (discoverTypingsResult.newTypingNames.length) {
122866                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
122867                     }
122868                     else {
122869                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
122870                         if (this.log.isEnabled()) {
122871                             this.log.writeLine("No new typings were requested as a result of typings discovery");
122872                         }
122873                     }
122874                 };
122875                 TypingsInstaller.prototype.initializeSafeList = function () {
122876                     // Prefer the safe list from the types map if it exists
122877                     if (this.typesMapLocation) {
122878                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
122879                         if (safeListFromMap) {
122880                             this.log.writeLine("Loaded safelist from types map file '".concat(this.typesMapLocation, "'"));
122881                             this.safeList = safeListFromMap;
122882                             return;
122883                         }
122884                         this.log.writeLine("Failed to load safelist from types map file '".concat(this.typesMapLocation, "'"));
122885                     }
122886                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
122887                 };
122888                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
122889                     if (this.log.isEnabled()) {
122890                         this.log.writeLine("Processing cache location '".concat(cacheLocation, "'"));
122891                     }
122892                     if (this.knownCachesSet.has(cacheLocation)) {
122893                         if (this.log.isEnabled()) {
122894                             this.log.writeLine("Cache location was already processed...");
122895                         }
122896                         return;
122897                     }
122898                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
122899                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
122900                     if (this.log.isEnabled()) {
122901                         this.log.writeLine("Trying to find '".concat(packageJson, "'..."));
122902                     }
122903                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
122904                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
122905                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
122906                         if (this.log.isEnabled()) {
122907                             this.log.writeLine("Loaded content of '".concat(packageJson, "': ").concat(JSON.stringify(npmConfig)));
122908                             this.log.writeLine("Loaded content of '".concat(packageLockJson, "'"));
122909                         }
122910                         if (npmConfig.devDependencies && npmLock.dependencies) {
122911                             for (var key in npmConfig.devDependencies) {
122912                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
122913                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
122914                                     continue;
122915                                 }
122916                                 // key is @types/<package name>
122917                                 var packageName = ts.getBaseFileName(key);
122918                                 if (!packageName) {
122919                                     continue;
122920                                 }
122921                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
122922                                 if (!typingFile) {
122923                                     this.missingTypingsSet.add(packageName);
122924                                     continue;
122925                                 }
122926                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
122927                                 if (existingTypingFile) {
122928                                     if (existingTypingFile.typingLocation === typingFile) {
122929                                         continue;
122930                                     }
122931                                     if (this.log.isEnabled()) {
122932                                         this.log.writeLine("New typing for package ".concat(packageName, " from '").concat(typingFile, "' conflicts with existing typing file '").concat(existingTypingFile, "'"));
122933                                     }
122934                                 }
122935                                 if (this.log.isEnabled()) {
122936                                     this.log.writeLine("Adding entry into typings cache: '".concat(packageName, "' => '").concat(typingFile, "'"));
122937                                 }
122938                                 var info = ts.getProperty(npmLock.dependencies, key);
122939                                 var version_1 = info && info.version;
122940                                 if (!version_1) {
122941                                     continue;
122942                                 }
122943                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
122944                                 this.packageNameToTypingLocation.set(packageName, newTyping);
122945                             }
122946                         }
122947                     }
122948                     if (this.log.isEnabled()) {
122949                         this.log.writeLine("Finished processing cache location '".concat(cacheLocation, "'"));
122950                     }
122951                     this.knownCachesSet.add(cacheLocation);
122952                 };
122953                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
122954                     var _this = this;
122955                     return ts.mapDefined(typingsToInstall, function (typing) {
122956                         var typingKey = ts.mangleScopedPackageName(typing);
122957                         if (_this.missingTypingsSet.has(typingKey)) {
122958                             if (_this.log.isEnabled())
122959                                 _this.log.writeLine("'".concat(typing, "':: '").concat(typingKey, "' is in missingTypingsSet - skipping..."));
122960                             return undefined;
122961                         }
122962                         var validationResult = ts.JsTyping.validatePackageName(typing);
122963                         if (validationResult !== 0 /* Ok */) {
122964                             // add typing name to missing set so we won't process it again
122965                             _this.missingTypingsSet.add(typingKey);
122966                             if (_this.log.isEnabled())
122967                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
122968                             return undefined;
122969                         }
122970                         if (!_this.typesRegistry.has(typingKey)) {
122971                             if (_this.log.isEnabled())
122972                                 _this.log.writeLine("'".concat(typing, "':: Entry for package '").concat(typingKey, "' does not exist in local types registry - skipping..."));
122973                             return undefined;
122974                         }
122975                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
122976                             if (_this.log.isEnabled())
122977                                 _this.log.writeLine("'".concat(typing, "':: '").concat(typingKey, "' already has an up-to-date typing - skipping..."));
122978                             return undefined;
122979                         }
122980                         return typingKey;
122981                     });
122982                 };
122983                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
122984                     var npmConfigPath = ts.combinePaths(directory, "package.json");
122985                     if (this.log.isEnabled()) {
122986                         this.log.writeLine("Npm config file: ".concat(npmConfigPath));
122987                     }
122988                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
122989                         if (this.log.isEnabled()) {
122990                             this.log.writeLine("Npm config file: '".concat(npmConfigPath, "' is missing, creating new one..."));
122991                         }
122992                         this.ensureDirectoryExists(directory, this.installTypingHost);
122993                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
122994                     }
122995                 };
122996                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
122997                     var _this = this;
122998                     if (this.log.isEnabled()) {
122999                         this.log.writeLine("Installing typings ".concat(JSON.stringify(typingsToInstall)));
123000                     }
123001                     var filteredTypings = this.filterTypings(typingsToInstall);
123002                     if (filteredTypings.length === 0) {
123003                         if (this.log.isEnabled()) {
123004                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
123005                         }
123006                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
123007                         return;
123008                     }
123009                     this.ensurePackageDirectoryExists(cachePath);
123010                     var requestId = this.installRunCount;
123011                     this.installRunCount++;
123012                     // send progress event
123013                     this.sendResponse({
123014                         kind: server.EventBeginInstallTypes,
123015                         eventId: requestId,
123016                         // qualified explicitly to prevent occasional shadowing
123017                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
123018                         typingsInstallerVersion: ts.version,
123019                         projectName: req.projectName
123020                     });
123021                     var scopedTypings = filteredTypings.map(typingsName);
123022                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
123023                         try {
123024                             if (!ok) {
123025                                 if (_this.log.isEnabled()) {
123026                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: ".concat(JSON.stringify(filteredTypings)));
123027                                 }
123028                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
123029                                     var typing = filteredTypings_1[_i];
123030                                     _this.missingTypingsSet.add(typing);
123031                                 }
123032                                 return;
123033                             }
123034                             // TODO: watch project directory
123035                             if (_this.log.isEnabled()) {
123036                                 _this.log.writeLine("Installed typings ".concat(JSON.stringify(scopedTypings)));
123037                             }
123038                             var installedTypingFiles = [];
123039                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
123040                                 var packageName = filteredTypings_2[_a];
123041                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
123042                                 if (!typingFile) {
123043                                     _this.missingTypingsSet.add(packageName);
123044                                     continue;
123045                                 }
123046                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
123047                                 var distTags = _this.typesRegistry.get(packageName);
123048                                 var newVersion = new ts.Version(distTags["ts".concat(ts.versionMajorMinor)] || distTags[_this.latestDistTag]);
123049                                 var newTyping = { typingLocation: typingFile, version: newVersion };
123050                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
123051                                 installedTypingFiles.push(typingFile);
123052                             }
123053                             if (_this.log.isEnabled()) {
123054                                 _this.log.writeLine("Installed typing files ".concat(JSON.stringify(installedTypingFiles)));
123055                             }
123056                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
123057                         }
123058                         finally {
123059                             var response = {
123060                                 kind: server.EventEndInstallTypes,
123061                                 eventId: requestId,
123062                                 projectName: req.projectName,
123063                                 packagesToInstall: scopedTypings,
123064                                 installSuccess: ok,
123065                                 // qualified explicitly to prevent occasional shadowing
123066                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
123067                                 typingsInstallerVersion: ts.version
123068                             };
123069                             _this.sendResponse(response);
123070                         }
123071                     });
123072                 };
123073                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
123074                     var directoryName = ts.getDirectoryPath(directory);
123075                     if (!host.directoryExists(directoryName)) {
123076                         this.ensureDirectoryExists(directoryName, host);
123077                     }
123078                     if (!host.directoryExists(directory)) {
123079                         host.createDirectory(directory);
123080                     }
123081                 };
123082                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
123083                     var _this = this;
123084                     if (!files.length) {
123085                         // shut down existing watchers
123086                         this.closeWatchers(projectName);
123087                         return;
123088                     }
123089                     var watchers = this.projectWatchers.get(projectName);
123090                     var toRemove = new ts.Map();
123091                     if (!watchers) {
123092                         watchers = new ts.Map();
123093                         this.projectWatchers.set(projectName, watchers);
123094                     }
123095                     else {
123096                         ts.copyEntries(watchers, toRemove);
123097                     }
123098                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
123099                     watchers.isInvoked = false;
123100                     var isLoggingEnabled = this.log.isEnabled();
123101                     var createProjectWatcher = function (path, projectWatcherType) {
123102                         var canonicalPath = _this.toCanonicalFileName(path);
123103                         toRemove.delete(canonicalPath);
123104                         if (watchers.has(canonicalPath)) {
123105                             return;
123106                         }
123107                         if (isLoggingEnabled) {
123108                             _this.log.writeLine("".concat(projectWatcherType, ":: Added:: WatchInfo: ").concat(path));
123109                         }
123110                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
123111                             _this.watchFactory.watchFile(path, function () {
123112                                 if (!watchers.isInvoked) {
123113                                     watchers.isInvoked = true;
123114                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
123115                                 }
123116                             }, ts.PollingInterval.High, options, projectName, watchers) :
123117                             _this.watchFactory.watchDirectory(path, function (f) {
123118                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
123119                                     return;
123120                                 }
123121                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
123122                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
123123                                     watchers.isInvoked = true;
123124                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
123125                                 }
123126                             }, 1 /* Recursive */, options, projectName, watchers);
123127                         watchers.set(canonicalPath, isLoggingEnabled ? {
123128                             close: function () {
123129                                 _this.log.writeLine("".concat(projectWatcherType, ":: Closed:: WatchInfo: ").concat(path));
123130                                 watcher.close();
123131                             }
123132                         } : watcher);
123133                     };
123134                     // Create watches from list of files
123135                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
123136                         var file = files_1[_i];
123137                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
123138                             // package.json or bower.json exists, watch the file to detect changes and update typings
123139                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
123140                             continue;
123141                         }
123142                         // path in projectRoot, watch project root
123143                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
123144                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
123145                             if (subDirectory !== -1) {
123146                                 // Watch subDirectory
123147                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
123148                             }
123149                             else {
123150                                 // Watch the directory itself
123151                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
123152                             }
123153                             continue;
123154                         }
123155                         // path in global cache, watch global cache
123156                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
123157                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
123158                             continue;
123159                         }
123160                         // watch node_modules or bower_components
123161                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
123162                     }
123163                     // Remove unused watches
123164                     toRemove.forEach(function (watch, path) {
123165                         watch.close();
123166                         watchers.delete(path);
123167                     });
123168                 };
123169                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
123170                     return {
123171                         projectName: request.projectName,
123172                         typeAcquisition: request.typeAcquisition,
123173                         compilerOptions: request.compilerOptions,
123174                         typings: typings,
123175                         unresolvedImports: request.unresolvedImports,
123176                         kind: server.ActionSet
123177                     };
123178                 };
123179                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
123180                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
123181                     this.executeWithThrottling();
123182                 };
123183                 TypingsInstaller.prototype.executeWithThrottling = function () {
123184                     var _this = this;
123185                     var _loop_1 = function () {
123186                         this_1.inFlightRequestCount++;
123187                         var request = this_1.pendingRunRequests.pop();
123188                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
123189                             _this.inFlightRequestCount--;
123190                             request.onRequestCompleted(ok);
123191                             _this.executeWithThrottling();
123192                         });
123193                     };
123194                     var this_1 = this;
123195                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
123196                         _loop_1();
123197                     }
123198                 };
123199                 return TypingsInstaller;
123200             }());
123201             typingsInstaller.TypingsInstaller = TypingsInstaller;
123202             /* @internal */
123203             function typingsName(packageName) {
123204                 return "@types/".concat(packageName, "@ts").concat(ts.versionMajorMinor);
123205             }
123206             typingsInstaller.typingsName = typingsName;
123207         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
123208     })(server = ts.server || (ts.server = {}));
123209 })(ts || (ts = {}));
123210 var ts;
123211 (function (ts) {
123212     var server;
123213     (function (server) {
123214         var typingsInstaller;
123215         (function (typingsInstaller) {
123216             var fs = require("fs");
123217             var path = require("path");
123218             var FileLog = (function () {
123219                 function FileLog(logFile) {
123220                     var _this = this;
123221                     this.logFile = logFile;
123222                     this.isEnabled = function () {
123223                         return typeof _this.logFile === "string";
123224                     };
123225                     this.writeLine = function (text) {
123226                         if (typeof _this.logFile !== "string")
123227                             return;
123228                         try {
123229                             fs.appendFileSync(_this.logFile, "[".concat(server.nowString(), "] ").concat(text).concat(ts.sys.newLine));
123230                         }
123231                         catch (e) {
123232                             _this.logFile = undefined;
123233                         }
123234                     };
123235                 }
123236                 return FileLog;
123237             }());
123238             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
123239                 if (path.basename(processName).indexOf("node") === 0) {
123240                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
123241                     if (!validateDefaultNpmLocation) {
123242                         return npmPath;
123243                     }
123244                     if (host.fileExists(npmPath)) {
123245                         return "\"".concat(npmPath, "\"");
123246                     }
123247                 }
123248                 return "npm";
123249             }
123250             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
123251                 if (!host.fileExists(typesRegistryFilePath)) {
123252                     if (log.isEnabled()) {
123253                         log.writeLine("Types registry file '".concat(typesRegistryFilePath, "' does not exist"));
123254                     }
123255                     return new ts.Map();
123256                 }
123257                 try {
123258                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
123259                     return new ts.Map(ts.getEntries(content.entries));
123260                 }
123261                 catch (e) {
123262                     if (log.isEnabled()) {
123263                         log.writeLine("Error when loading types registry file '".concat(typesRegistryFilePath, "': ").concat(e.message, ", ").concat(e.stack));
123264                     }
123265                     return new ts.Map();
123266                 }
123267             }
123268             var typesRegistryPackageName = "types-registry";
123269             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
123270                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/".concat(typesRegistryPackageName, "/index.json"));
123271             }
123272             var NodeTypingsInstaller = (function (_super) {
123273                 __extends(NodeTypingsInstaller, _super);
123274                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
123275                     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;
123276                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
123277                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
123278                         _this.npmPath = "\"".concat(_this.npmPath, "\"");
123279                     }
123280                     if (_this.log.isEnabled()) {
123281                         _this.log.writeLine("Process id: ".concat(process.pid));
123282                         _this.log.writeLine("NPM location: ".concat(_this.npmPath, " (explicit '").concat(server.Arguments.NpmLocation, "' ").concat(npmLocation === undefined ? "not " : "", " provided)"));
123283                         _this.log.writeLine("validateDefaultNpmLocation: ".concat(validateDefaultNpmLocation));
123284                     }
123285                     (_this.nodeExecSync = require("child_process").execSync);
123286                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
123287                     try {
123288                         if (_this.log.isEnabled()) {
123289                             _this.log.writeLine("Updating ".concat(typesRegistryPackageName, " npm package..."));
123290                         }
123291                         _this.execSyncAndLog("".concat(_this.npmPath, " install --ignore-scripts ").concat(typesRegistryPackageName, "@").concat(_this.latestDistTag), { cwd: globalTypingsCacheLocation });
123292                         if (_this.log.isEnabled()) {
123293                             _this.log.writeLine("Updated ".concat(typesRegistryPackageName, " npm package"));
123294                         }
123295                     }
123296                     catch (e) {
123297                         if (_this.log.isEnabled()) {
123298                             _this.log.writeLine("Error updating ".concat(typesRegistryPackageName, " package: ").concat(e.message));
123299                         }
123300                         _this.delayedInitializationError = {
123301                             kind: "event::initializationFailed",
123302                             message: e.message,
123303                             stack: e.stack,
123304                         };
123305                     }
123306                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
123307                     return _this;
123308                 }
123309                 NodeTypingsInstaller.prototype.listen = function () {
123310                     var _this = this;
123311                     process.on("message", function (req) {
123312                         if (_this.delayedInitializationError) {
123313                             _this.sendResponse(_this.delayedInitializationError);
123314                             _this.delayedInitializationError = undefined;
123315                         }
123316                         switch (req.kind) {
123317                             case "discover":
123318                                 _this.install(req);
123319                                 break;
123320                             case "closeProject":
123321                                 _this.closeProject(req);
123322                                 break;
123323                             case "typesRegistry": {
123324                                 var typesRegistry_1 = {};
123325                                 _this.typesRegistry.forEach(function (value, key) {
123326                                     typesRegistry_1[key] = value;
123327                                 });
123328                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
123329                                 _this.sendResponse(response);
123330                                 break;
123331                             }
123332                             case "installPackage": {
123333                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
123334                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
123335                                 if (cwd) {
123336                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
123337                                         var message = success ? "Package ".concat(packageName_1, " installed.") : "There was an error installing ".concat(packageName_1, ".");
123338                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
123339                                         _this.sendResponse(response);
123340                                     });
123341                                 }
123342                                 else {
123343                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
123344                                     _this.sendResponse(response);
123345                                 }
123346                                 break;
123347                             }
123348                             default:
123349                                 ts.Debug.assertNever(req);
123350                         }
123351                     });
123352                 };
123353                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
123354                     if (this.log.isEnabled()) {
123355                         this.log.writeLine("Sending response:\n    ".concat(JSON.stringify(response)));
123356                     }
123357                     process.send(response);
123358                     if (this.log.isEnabled()) {
123359                         this.log.writeLine("Response has been sent.");
123360                     }
123361                 };
123362                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
123363                     var _this = this;
123364                     if (this.log.isEnabled()) {
123365                         this.log.writeLine("#".concat(requestId, " with arguments'").concat(JSON.stringify(packageNames), "'."));
123366                     }
123367                     var start = Date.now();
123368                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
123369                     if (this.log.isEnabled()) {
123370                         this.log.writeLine("npm install #".concat(requestId, " took: ").concat(Date.now() - start, " ms"));
123371                     }
123372                     onRequestCompleted(!hasError);
123373                 };
123374                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
123375                     if (this.log.isEnabled()) {
123376                         this.log.writeLine("Exec: ".concat(command));
123377                     }
123378                     try {
123379                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
123380                         if (this.log.isEnabled()) {
123381                             this.log.writeLine("    Succeeded. stdout:".concat(indent(ts.sys.newLine, stdout)));
123382                         }
123383                         return false;
123384                     }
123385                     catch (error) {
123386                         var stdout = error.stdout, stderr = error.stderr;
123387                         this.log.writeLine("    Failed. stdout:".concat(indent(ts.sys.newLine, stdout)).concat(ts.sys.newLine, "    stderr:").concat(indent(ts.sys.newLine, stderr)));
123388                         return true;
123389                     }
123390                 };
123391                 return NodeTypingsInstaller;
123392             }(typingsInstaller.TypingsInstaller));
123393             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
123394             function getDirectoryOfPackageJson(fileName, host) {
123395                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
123396                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
123397                         return directory;
123398                     }
123399                 });
123400             }
123401             var logFilePath = server.findArgument(server.Arguments.LogFile);
123402             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
123403             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
123404             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
123405             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
123406             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
123407             var log = new FileLog(logFilePath);
123408             if (log.isEnabled()) {
123409                 process.on("uncaughtException", function (e) {
123410                     log.writeLine("Unhandled exception: ".concat(e, " at ").concat(e.stack));
123411                 });
123412             }
123413             process.on("disconnect", function () {
123414                 if (log.isEnabled()) {
123415                     log.writeLine("Parent process has exited, shutting down...");
123416                 }
123417                 process.exit(0);
123418             });
123419             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
123420             installer.listen();
123421             function indent(newline, str) {
123422                 return str && str.length
123423                     ? "".concat(newline, "    ") + str.replace(/\r?\n/, "".concat(newline, "    "))
123424                     : "";
123425             }
123426         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
123427     })(server = ts.server || (ts.server = {}));
123428 })(ts || (ts = {}));
123429 //# sourceMappingURL=typingsInstaller.js.map